aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGonçalo Silva <goncalossilva@gmail.com>2011-03-24 17:21:17 +0000
committerGonçalo Silva <goncalossilva@gmail.com>2011-03-24 17:21:17 +0000
commit9887f238871bb2dd73de6ce8855615bcc5d8d079 (patch)
tree74fa9ff9524a51701cfa23f708b3f777c65b7fe5
parentaff821508a16245ebc03510ba29c70379718dfb7 (diff)
parent5214e73850916de3c9127d35a4ecee0424d364a3 (diff)
downloadrails-9887f238871bb2dd73de6ce8855615bcc5d8d079.tar.gz
rails-9887f238871bb2dd73de6ce8855615bcc5d8d079.tar.bz2
rails-9887f238871bb2dd73de6ce8855615bcc5d8d079.zip
Merge branch 'master' of https://github.com/rails/rails
-rw-r--r--.gitignore3
-rw-r--r--.yardopts4
-rw-r--r--Gemfile52
-rw-r--r--RAILS_VERSION2
-rw-r--r--README.rdoc33
-rwxr-xr-x[-rw-r--r--]Rakefile95
-rw-r--r--actionmailer/CHANGELOG30
-rw-r--r--actionmailer/MIT-LICENSE2
-rw-r--r--actionmailer/README.rdoc35
-rwxr-xr-x[-rw-r--r--]actionmailer/Rakefile20
-rw-r--r--actionmailer/actionmailer.gemspec2
-rw-r--r--actionmailer/lib/action_mailer.rb4
-rw-r--r--actionmailer/lib/action_mailer/adv_attr_accessor.rb36
-rw-r--r--actionmailer/lib/action_mailer/base.rb92
-rw-r--r--actionmailer/lib/action_mailer/delivery_methods.rb4
-rw-r--r--actionmailer/lib/action_mailer/deprecated_api.rb141
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb39
-rw-r--r--actionmailer/lib/action_mailer/old_api.rb72
-rw-r--r--actionmailer/lib/action_mailer/railtie.rb23
-rw-r--r--actionmailer/lib/action_mailer/test_case.rb7
-rw-r--r--actionmailer/lib/action_mailer/tmail_compat.rb27
-rw-r--r--actionmailer/lib/action_mailer/version.rb6
-rw-r--r--actionmailer/lib/rails/generators/mailer/USAGE5
-rw-r--r--actionmailer/lib/rails/generators/mailer/templates/mailer.rb4
-rw-r--r--actionmailer/test/abstract_unit.rb17
-rw-r--r--actionmailer/test/asset_host_test.rb (renamed from actionmailer/test/old_base/asset_host_test.rb)10
-rw-r--r--actionmailer/test/base_test.rb35
-rw-r--r--actionmailer/test/delivery_methods_test.rb6
-rw-r--r--actionmailer/test/fixtures/base_mailer/email_with_translations.html.erb1
-rw-r--r--actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb4
-rw-r--r--actionmailer/test/fixtures/raw_email102
-rw-r--r--actionmailer/test/fixtures/raw_email22
-rw-r--r--actionmailer/test/fixtures/raw_email32
-rw-r--r--actionmailer/test/fixtures/raw_email52
-rw-r--r--actionmailer/test/fixtures/raw_email62
-rw-r--r--actionmailer/test/fixtures/raw_email82
-rw-r--r--actionmailer/test/fixtures/raw_email910
-rw-r--r--actionmailer/test/fixtures/templates/signed_up.erb2
-rw-r--r--actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml4
-rw-r--r--actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml4
-rw-r--r--actionmailer/test/fixtures/test_mailer/signed_up.html.erb2
-rw-r--r--actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb2
-rw-r--r--actionmailer/test/i18n_with_controller_test.rb46
-rw-r--r--actionmailer/test/mail_helper_test.rb13
-rw-r--r--actionmailer/test/mail_layout_test.rb (renamed from actionmailer/test/old_base/mail_layout_test.rb)53
-rw-r--r--actionmailer/test/mailers/base_mailer.rb4
-rw-r--r--actionmailer/test/mailers/proc_mailer.rb6
-rw-r--r--actionmailer/test/old_base/adv_attr_test.rb5
-rw-r--r--actionmailer/test/old_base/mail_render_test.rb43
-rw-r--r--actionmailer/test/old_base/mail_service_test.rb147
-rw-r--r--actionmailer/test/old_base/tmail_compat_test.rb9
-rw-r--r--actionmailer/test/test_helper_test.rb31
-rw-r--r--actionmailer/test/url_test.rb (renamed from actionmailer/test/old_base/url_test.rb)21
-rw-r--r--actionpack/CHANGELOG88
-rw-r--r--actionpack/MIT-LICENSE2
-rw-r--r--actionpack/README.rdoc8
-rw-r--r--actionpack/RUNNING_UNIT_TESTS15
-rwxr-xr-x[-rw-r--r--]actionpack/Rakefile26
-rw-r--r--actionpack/actionpack.gemspec19
-rw-r--r--actionpack/lib/abstract_controller.rb2
-rw-r--r--actionpack/lib/abstract_controller/base.rb46
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb21
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb31
-rw-r--r--actionpack/lib/abstract_controller/layouts.rb38
-rw-r--r--actionpack/lib/abstract_controller/railties/routes_helpers.rb18
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb56
-rw-r--r--actionpack/lib/abstract_controller/url_for.rb27
-rw-r--r--actionpack/lib/abstract_controller/view_paths.rb16
-rw-r--r--actionpack/lib/action_controller.rb2
-rw-r--r--actionpack/lib/action_controller/base.rb172
-rw-r--r--actionpack/lib/action_controller/caching.rb4
-rw-r--r--actionpack/lib/action_controller/caching/actions.rb94
-rw-r--r--actionpack/lib/action_controller/caching/fragments.rb60
-rw-r--r--actionpack/lib/action_controller/caching/pages.rb29
-rw-r--r--actionpack/lib/action_controller/deprecated.rb2
-rw-r--r--actionpack/lib/action_controller/deprecated/base.rb133
-rw-r--r--actionpack/lib/action_controller/deprecated/dispatcher.rb28
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb8
-rw-r--r--actionpack/lib/action_controller/metal.rb101
-rw-r--r--actionpack/lib/action_controller/metal/compatibility.rb9
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb18
-rw-r--r--actionpack/lib/action_controller/metal/head.rb8
-rw-r--r--actionpack/lib/action_controller/metal/helpers.rb49
-rw-r--r--actionpack/lib/action_controller/metal/hide_actions.rb5
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb69
-rw-r--r--actionpack/lib/action_controller/metal/implicit_render.rb4
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb2
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb22
-rw-r--r--actionpack/lib/action_controller/metal/redirecting.rb10
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb75
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb50
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb85
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb46
-rw-r--r--actionpack/lib/action_controller/metal/streaming.rb12
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb9
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb26
-rw-r--r--actionpack/lib/action_controller/middleware.rb2
-rw-r--r--actionpack/lib/action_controller/railtie.rb55
-rw-r--r--actionpack/lib/action_controller/railties/paths.rb32
-rw-r--r--actionpack/lib/action_controller/test_case.rb65
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/document.rb4
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/node.rb82
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb56
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb2
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb16
-rw-r--r--actionpack/lib/action_dispatch.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb41
-rw-r--r--actionpack/lib/action_dispatch/http/filter_parameters.rb21
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb8
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb74
-rw-r--r--actionpack/lib/action_dispatch/http/parameters.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/rack_cache.rb58
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb77
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb26
-rw-r--r--actionpack/lib/action_dispatch/http/upload.rb60
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb142
-rw-r--r--actionpack/lib/action_dispatch/middleware/callbacks.rb33
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb70
-rw-r--r--actionpack/lib/action_dispatch/middleware/flash.rb9
-rw-r--r--actionpack/lib/action_dispatch/middleware/reloader.rb76
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/abstract_store.rb280
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cookie_store.rb64
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb53
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb48
-rw-r--r--actionpack/lib/action_dispatch/middleware/stack.rb67
-rw-r--r--actionpack/lib/action_dispatch/middleware/static.rb64
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb6
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb8
-rw-r--r--actionpack/lib/action_dispatch/railtie.rb7
-rw-r--r--actionpack/lib/action_dispatch/routing.rb117
-rw-r--r--actionpack/lib/action_dispatch/routing/deprecated_mapper.rb525
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb1077
-rw-r--r--actionpack/lib/action_dispatch/routing/polymorphic_routes.rb64
-rw-r--r--actionpack/lib/action_dispatch/routing/redirection.rb110
-rw-r--r--actionpack/lib/action_dispatch/routing/route.rb27
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb206
-rw-r--r--actionpack/lib/action_dispatch/routing/routes_proxy.rb35
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb33
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/dom.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb20
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb85
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/selector.rb27
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb53
-rw-r--r--actionpack/lib/action_dispatch/testing/performance_test.rb4
-rw-r--r--actionpack/lib/action_dispatch/testing/test_process.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb12
-rw-r--r--actionpack/lib/action_dispatch/testing/test_response.rb115
-rw-r--r--actionpack/lib/action_pack.rb2
-rw-r--r--actionpack/lib/action_pack/version.rb6
-rw-r--r--actionpack/lib/action_view.rb53
-rw-r--r--actionpack/lib/action_view/base.rb67
-rw-r--r--actionpack/lib/action_view/helpers.rb5
-rw-r--r--actionpack/lib/action_view/helpers/active_model_helper.rb23
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb494
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb146
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb153
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb184
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb147
-rw-r--r--actionpack/lib/action_view/helpers/atom_feed_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/cache_helper.rb26
-rw-r--r--actionpack/lib/action_view/helpers/capture_helper.rb5
-rw-r--r--actionpack/lib/action_view/helpers/csrf_helper.rb28
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb70
-rw-r--r--actionpack/lib/action_view/helpers/debug_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb307
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb60
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb114
-rw-r--r--actionpack/lib/action_view/helpers/javascript_helper.rb3
-rw-r--r--actionpack/lib/action_view/helpers/number_helper.rb94
-rw-r--r--actionpack/lib/action_view/helpers/output_safety_helper.rb38
-rw-r--r--actionpack/lib/action_view/helpers/prototype_helper.rb26
-rw-r--r--actionpack/lib/action_view/helpers/raw_output_helper.rb18
-rw-r--r--actionpack/lib/action_view/helpers/record_tag_helper.rb6
-rw-r--r--actionpack/lib/action_view/helpers/sanitize_helper.rb4
-rw-r--r--actionpack/lib/action_view/helpers/tag_helper.rb46
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb62
-rw-r--r--actionpack/lib/action_view/helpers/translation_helper.rb50
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb136
-rw-r--r--actionpack/lib/action_view/locale/en.yml2
-rw-r--r--actionpack/lib/action_view/log_subscriber.rb2
-rw-r--r--actionpack/lib/action_view/lookup_context.rb55
-rw-r--r--actionpack/lib/action_view/partials.rb (renamed from actionpack/lib/action_view/render/partials.rb)216
-rw-r--r--actionpack/lib/action_view/path_set.rb (renamed from actionpack/lib/action_view/paths.rb)16
-rw-r--r--actionpack/lib/action_view/railtie.rb14
-rw-r--r--actionpack/lib/action_view/render/layouts.rb79
-rw-r--r--actionpack/lib/action_view/render/rendering.rb67
-rw-r--r--actionpack/lib/action_view/renderer/abstract_renderer.rb37
-rw-r--r--actionpack/lib/action_view/renderer/partial_renderer.rb167
-rw-r--r--actionpack/lib/action_view/renderer/template_renderer.rb98
-rw-r--r--actionpack/lib/action_view/rendering.rb106
-rw-r--r--actionpack/lib/action_view/template.rb155
-rw-r--r--actionpack/lib/action_view/template/error.rb19
-rw-r--r--actionpack/lib/action_view/template/handler.rb12
-rw-r--r--actionpack/lib/action_view/template/handlers.rb20
-rw-r--r--actionpack/lib/action_view/template/handlers/builder.rb8
-rw-r--r--actionpack/lib/action_view/template/handlers/erb.rb43
-rw-r--r--actionpack/lib/action_view/template/handlers/rjs.rb12
-rw-r--r--actionpack/lib/action_view/template/resolver.rb221
-rw-r--r--actionpack/lib/action_view/template/text.rb4
-rw-r--r--actionpack/lib/action_view/test_case.rb67
-rw-r--r--actionpack/lib/action_view/testing/resolvers.rb31
-rw-r--r--actionpack/test/abstract/abstract_controller_test.rb14
-rw-r--r--actionpack/test/abstract/callbacks_test.rb141
-rw-r--r--actionpack/test/abstract/helper_test.rb27
-rw-r--r--actionpack/test/abstract/layouts_test.rb2
-rw-r--r--actionpack/test/abstract/render_test.rb4
-rw-r--r--actionpack/test/abstract/translation_test.rb8
-rw-r--r--actionpack/test/abstract_unit.rb113
-rw-r--r--actionpack/test/action_dispatch/routing/mapper_test.rb58
-rw-r--r--actionpack/test/activerecord/active_record_store_test.rb36
-rw-r--r--actionpack/test/activerecord/controller_runtime_test.rb4
-rw-r--r--actionpack/test/activerecord/polymorphic_routes_test.rb82
-rw-r--r--actionpack/test/activerecord/render_partial_with_record_identification_test.rb38
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb216
-rw-r--r--actionpack/test/controller/assert_select_test.rb26
-rw-r--r--actionpack/test/controller/base_test.rb26
-rw-r--r--actionpack/test/controller/caching_test.rb55
-rw-r--r--actionpack/test/controller/capture_test.rb10
-rw-r--r--actionpack/test/controller/content_type_test.rb24
-rw-r--r--actionpack/test/controller/dispatcher_test.rb59
-rw-r--r--actionpack/test/controller/filters_test.rb122
-rw-r--r--actionpack/test/controller/flash_test.rb4
-rw-r--r--actionpack/test/controller/helper_test.rb68
-rw-r--r--actionpack/test/controller/http_basic_authentication_test.rb6
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb6
-rw-r--r--actionpack/test/controller/integration_test.rb14
-rw-r--r--actionpack/test/controller/layout_test.rb24
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb66
-rw-r--r--actionpack/test/controller/mime_responds_test.rb129
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb22
-rw-r--r--actionpack/test/controller/new_base/content_negotiation_test.rb9
-rw-r--r--actionpack/test/controller/new_base/content_type_test.rb12
-rw-r--r--actionpack/test/controller/new_base/etag_test.rb46
-rw-r--r--actionpack/test/controller/new_base/middleware_test.rb22
-rw-r--r--actionpack/test/controller/new_base/render_action_test.rb3
-rw-r--r--actionpack/test/controller/new_base/render_implicit_action_test.rb4
-rw-r--r--actionpack/test/controller/new_base/render_layout_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_once_test.rb86
-rw-r--r--actionpack/test/controller/new_base/render_partial_test.rb52
-rw-r--r--actionpack/test/controller/new_base/render_template_test.rb54
-rw-r--r--actionpack/test/controller/new_base/render_test.rb66
-rw-r--r--actionpack/test/controller/new_base/render_text_test.rb44
-rw-r--r--actionpack/test/controller/new_base/render_xml_test.rb2
-rw-r--r--actionpack/test/controller/output_escaping_test.rb2
-rw-r--r--actionpack/test/controller/record_identifier_test.rb27
-rw-r--r--actionpack/test/controller/redirect_test.rb58
-rw-r--r--actionpack/test/controller/render_json_test.rb23
-rw-r--r--actionpack/test/controller/render_other_test.rb7
-rw-r--r--actionpack/test/controller/render_test.rb164
-rw-r--r--actionpack/test/controller/render_xml_test.rb5
-rw-r--r--actionpack/test/controller/request/test_request_test.rb3
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb222
-rw-r--r--actionpack/test/controller/rescue_test.rb20
-rw-r--r--actionpack/test/controller/resources_test.rb626
-rw-r--r--actionpack/test/controller/routing_test.rb1460
-rw-r--r--actionpack/test/controller/runner_test.rb22
-rw-r--r--actionpack/test/controller/selector_test.rb10
-rw-r--r--actionpack/test/controller/test_test.rb44
-rw-r--r--actionpack/test/controller/url_for_test.rb58
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb5
-rw-r--r--actionpack/test/controller/view_paths_test.rb4
-rw-r--r--actionpack/test/controller/webservice_test.rb11
-rw-r--r--actionpack/test/dispatch/callbacks_test.rb76
-rw-r--r--actionpack/test/dispatch/cookies_test.rb255
-rw-r--r--actionpack/test/dispatch/middleware_stack/middleware_test.rb77
-rw-r--r--actionpack/test/dispatch/middleware_stack_test.rb17
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb59
-rw-r--r--actionpack/test/dispatch/mount_test.rb20
-rw-r--r--actionpack/test/dispatch/prefix_generation_test.rb317
-rw-r--r--actionpack/test/dispatch/reloader_test.rb138
-rw-r--r--actionpack/test/dispatch/request/json_params_parsing_test.rb4
-rw-r--r--actionpack/test/dispatch/request/multipart_params_parsing_test.rb13
-rw-r--r--actionpack/test/dispatch/request/query_string_parsing_test.rb4
-rw-r--r--actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb4
-rw-r--r--actionpack/test/dispatch/request/xml_params_parsing_test.rb5
-rw-r--r--actionpack/test/dispatch/request_test.rb140
-rw-r--r--actionpack/test/dispatch/response_test.rb39
-rw-r--r--actionpack/test/dispatch/routing_assertions_test.rb103
-rw-r--r--actionpack/test/dispatch/routing_test.rb616
-rw-r--r--actionpack/test/dispatch/session/cookie_store_test.rb44
-rw-r--r--actionpack/test/dispatch/session/mem_cache_store_test.rb6
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb48
-rw-r--r--actionpack/test/dispatch/static_test.rb86
-rw-r--r--actionpack/test/dispatch/test_request_test.rb4
-rw-r--r--actionpack/test/dispatch/test_response_test.rb21
-rw-r--r--actionpack/test/dispatch/uploaded_file_test.rb70
-rw-r--r--actionpack/test/dispatch/url_generation_test.rb3
-rw-r--r--actionpack/test/fixtures/alternate_helpers/foo_helper.rb2
-rw-r--r--actionpack/test/fixtures/blog_public/.gitignore1
-rw-r--r--actionpack/test/fixtures/blog_public/blog.html1
-rw-r--r--actionpack/test/fixtures/blog_public/index.html1
-rw-r--r--actionpack/test/fixtures/blog_public/subdir/index.html1
-rw-r--r--actionpack/test/fixtures/companies.yml2
-rw-r--r--actionpack/test/fixtures/company.rb2
-rw-r--r--actionpack/test/fixtures/custom_pattern/another.html.erb1
-rw-r--r--actionpack/test/fixtures/custom_pattern/html/another.erb1
-rw-r--r--actionpack/test/fixtures/custom_pattern/html/path.erb1
-rw-r--r--actionpack/test/fixtures/db_definitions/sqlite.sql20
-rw-r--r--actionpack/test/fixtures/filter_test/implicit_actions/edit.html.erb1
-rw-r--r--actionpack/test/fixtures/filter_test/implicit_actions/show.html.erb1
-rw-r--r--actionpack/test/fixtures/helpers/helpery_test_helper.rb5
-rw-r--r--actionpack/test/fixtures/helpers/just_me_helper.rb3
-rw-r--r--actionpack/test/fixtures/helpers/me_too_helper.rb3
-rw-r--r--actionpack/test/fixtures/layout_tests/alt/hello.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/alt/hello.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb (renamed from actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml)0
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/item.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/item.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/layout_test.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/goodbye.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/goodbye.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/hello.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/hello.rhtml1
-rw-r--r--actionpack/test/fixtures/layouts/_customers.erb1
-rw-r--r--actionpack/test/fixtures/layouts/_partial_and_yield.erb2
-rw-r--r--actionpack/test/fixtures/layouts/_yield_only.erb1
-rw-r--r--actionpack/test/fixtures/layouts/_yield_with_params.erb1
-rw-r--r--actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb2
-rw-r--r--actionpack/test/fixtures/old_content_type/render_default_for_builder.builder (renamed from actionpack/test/fixtures/old_content_type/render_default_for_rxml.rxml)0
-rw-r--r--actionpack/test/fixtures/old_content_type/render_default_for_erb.erb (renamed from actionpack/test/fixtures/old_content_type/render_default_for_rhtml.rhtml)0
-rw-r--r--actionpack/test/fixtures/replies.yml2
-rw-r--r--actionpack/test/fixtures/star_star_mime/index.js.erb1
-rw-r--r--actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb4
-rw-r--r--actionpack/test/fixtures/test/_object_inspector.erb1
-rw-r--r--actionpack/test/fixtures/test/_partial_with_layout.erb2
-rw-r--r--actionpack/test/fixtures/test/_partial_with_layout_block_content.erb4
-rw-r--r--actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb4
-rw-r--r--actionpack/test/fixtures/test/_partial_with_partial.erb2
-rw-r--r--actionpack/test/fixtures/test/hello_world_from_rxml.builder1
-rw-r--r--actionpack/test/fixtures/test/hello_xml_world.builder2
-rw-r--r--actionpack/test/fixtures/test/layout_render_object.erb1
-rw-r--r--actionpack/test/fixtures/test/proper_block_detection.erb2
-rw-r--r--actionpack/test/fixtures/test/scoped_translation.erb1
-rw-r--r--actionpack/test/fixtures/test/translation.erb1
-rw-r--r--actionpack/test/fixtures/topics.yml2
-rw-r--r--actionpack/test/fixtures/translations/templates/array.erb1
-rw-r--r--actionpack/test/fixtures/translations/templates/found.erb1
-rw-r--r--actionpack/test/fixtures/translations/templates/missing.erb1
-rw-r--r--actionpack/test/lib/controller/fake_models.rb53
-rw-r--r--actionpack/test/template/active_model_helper_test.rb8
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb200
-rw-r--r--actionpack/test/template/atom_feed_helper_test.rb6
-rw-r--r--actionpack/test/template/capture_helper_test.rb12
-rw-r--r--actionpack/test/template/compiled_templates_test.rb2
-rw-r--r--actionpack/test/template/date_helper_i18n_test.rb4
-rw-r--r--actionpack/test/template/date_helper_test.rb134
-rw-r--r--actionpack/test/template/erb/tag_helper_test.rb41
-rw-r--r--actionpack/test/template/erb_util_test.rb2
-rw-r--r--actionpack/test/template/form_helper_test.rb1175
-rw-r--r--actionpack/test/template/form_options_helper_test.rb115
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb69
-rw-r--r--actionpack/test/template/html-scanner/document_test.rb2
-rw-r--r--actionpack/test/template/html-scanner/node_test.rb18
-rw-r--r--actionpack/test/template/html-scanner/sanitizer_test.rb41
-rw-r--r--actionpack/test/template/html-scanner/tag_node_test.rb50
-rw-r--r--actionpack/test/template/html-scanner/text_node_test.rb10
-rw-r--r--actionpack/test/template/html-scanner/tokenizer_test.rb20
-rw-r--r--actionpack/test/template/javascript_helper_test.rb2
-rw-r--r--actionpack/test/template/log_subscriber_test.rb24
-rw-r--r--actionpack/test/template/lookup_context_test.rb133
-rw-r--r--actionpack/test/template/number_helper_i18n_test.rb15
-rw-r--r--actionpack/test/template/number_helper_test.rb113
-rw-r--r--actionpack/test/template/output_safety_helper_test.rb30
-rw-r--r--actionpack/test/template/prototype_helper_test.rb2
-rw-r--r--actionpack/test/template/raw_output_helper_test.rb21
-rw-r--r--actionpack/test/template/render_test.rb107
-rw-r--r--actionpack/test/template/resolver_patterns_test.rb31
-rw-r--r--actionpack/test/template/tag_helper_test.rb19
-rw-r--r--actionpack/test/template/template_error_test.rb13
-rw-r--r--actionpack/test/template/template_test.rb136
-rw-r--r--actionpack/test/template/test_case_test.rb75
-rw-r--r--actionpack/test/template/test_test.rb4
-rw-r--r--actionpack/test/template/text_helper_test.rb22
-rw-r--r--actionpack/test/template/translation_helper_test.rb80
-rw-r--r--actionpack/test/template/url_helper_test.rb99
-rw-r--r--activemodel/CHANGELOG34
-rw-r--r--activemodel/MIT-LICENSE2
-rw-r--r--activemodel/README.rdoc78
-rwxr-xr-x[-rw-r--r--]activemodel/Rakefile20
-rw-r--r--activemodel/activemodel.gemspec5
-rw-r--r--activemodel/lib/active_model.rb7
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb192
-rw-r--r--activemodel/lib/active_model/callbacks.rb64
-rw-r--r--activemodel/lib/active_model/conversion.rb21
-rw-r--r--activemodel/lib/active_model/deprecated_error_methods.rb33
-rw-r--r--activemodel/lib/active_model/dirty.rb39
-rw-r--r--activemodel/lib/active_model/errors.rb152
-rw-r--r--activemodel/lib/active_model/lint.rb35
-rw-r--r--activemodel/lib/active_model/mass_assignment_security.rb42
-rw-r--r--activemodel/lib/active_model/naming.rb68
-rw-r--r--activemodel/lib/active_model/observing.rb51
-rw-r--r--activemodel/lib/active_model/secure_password.rb66
-rw-r--r--activemodel/lib/active_model/serialization.rb73
-rw-r--r--activemodel/lib/active_model/serializers/json.rb36
-rw-r--r--activemodel/lib/active_model/serializers/xml.rb35
-rw-r--r--activemodel/lib/active_model/translation.rb20
-rw-r--r--activemodel/lib/active_model/validations.rb65
-rw-r--r--activemodel/lib/active_model/validations/acceptance.rb28
-rw-r--r--activemodel/lib/active_model/validations/callbacks.rb6
-rw-r--r--activemodel/lib/active_model/validations/confirmation.rb35
-rw-r--r--activemodel/lib/active_model/validations/exclusion.rb3
-rw-r--r--activemodel/lib/active_model/validations/format.rb4
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb18
-rw-r--r--activemodel/lib/active_model/validations/length.rb15
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb6
-rw-r--r--activemodel/lib/active_model/validations/presence.rb5
-rw-r--r--activemodel/lib/active_model/validations/validates.rb48
-rw-r--r--activemodel/lib/active_model/validations/with.rb16
-rw-r--r--activemodel/lib/active_model/validator.rb57
-rw-r--r--activemodel/lib/active_model/version.rb6
-rw-r--r--activemodel/test/cases/attribute_methods_test.rb95
-rw-r--r--activemodel/test/cases/callbacks_test.rb46
-rw-r--r--activemodel/test/cases/errors_test.rb17
-rw-r--r--activemodel/test/cases/helper.rb7
-rw-r--r--activemodel/test/cases/mass_assignment_security_test.rb6
-rw-r--r--activemodel/test/cases/naming_test.rb107
-rw-r--r--activemodel/test/cases/secure_password_test.rb45
-rw-r--r--activemodel/test/cases/serialization_test.rb45
-rw-r--r--activemodel/test/cases/serializeration/json_serialization_test.rb49
-rw-r--r--activemodel/test/cases/serializeration/xml_serialization_test.rb9
-rw-r--r--activemodel/test/cases/translation_test.rb34
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb9
-rw-r--r--activemodel/test/cases/validations/length_validation_test.rb11
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb2
-rw-r--r--activemodel/test/cases/validations/validates_test.rb47
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb21
-rw-r--r--activemodel/test/cases/validations_test.rb72
-rw-r--r--activemodel/test/models/administrator.rb10
-rw-r--r--activemodel/test/models/blog_post.rb13
-rw-r--r--activemodel/test/models/custom_reader.rb4
-rw-r--r--activemodel/test/models/person.rb4
-rw-r--r--activemodel/test/models/person_with_validator.rb15
-rw-r--r--activemodel/test/models/sheep.rb1
-rw-r--r--activemodel/test/models/topic.rb21
-rw-r--r--activemodel/test/models/track_back.rb7
-rw-r--r--activemodel/test/models/user.rb8
-rw-r--r--activemodel/test/models/visitor.rb9
-rw-r--r--activemodel/test/validators/namespace/email_validator.rb6
-rw-r--r--activerecord/CHANGELOG288
-rw-r--r--activerecord/MIT-LICENSE2
-rw-r--r--activerecord/README.rdoc26
-rw-r--r--activerecord/RUNNING_UNIT_TESTS23
-rwxr-xr-x[-rw-r--r--]activerecord/Rakefile44
-rw-r--r--activerecord/activerecord.gemspec4
-rw-r--r--activerecord/examples/performance.rb194
-rw-r--r--activerecord/lib/active_record.rb14
-rw-r--r--activerecord/lib/active_record/aggregations.rb163
-rw-r--r--activerecord/lib/active_record/association_preload.rb403
-rw-r--r--activerecord/lib/active_record/associations.rb1526
-rw-r--r--activerecord/lib/active_record/associations/alias_tracker.rb85
-rw-r--r--activerecord/lib/active_record/associations/association.rb230
-rw-r--r--activerecord/lib/active_record/associations/association_collection.rb557
-rw-r--r--activerecord/lib/active_record/associations/association_proxy.rb295
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb120
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb102
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb74
-rw-r--r--activerecord/lib/active_record/associations/builder/association.rb53
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb83
-rw-r--r--activerecord/lib/active_record/associations/builder/collection_association.rb75
-rw-r--r--activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb63
-rw-r--r--activerecord/lib/active_record/associations/builder/has_many.rb63
-rw-r--r--activerecord/lib/active_record/associations/builder/has_one.rb61
-rw-r--r--activerecord/lib/active_record/associations/builder/singular_association.rb32
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb536
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb127
-rw-r--r--activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb143
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb129
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb166
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb158
-rw-r--r--activerecord/lib/active_record/associations/has_one_through_association.rb46
-rw-r--r--activerecord/lib/active_record/associations/join_dependency.rb215
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_association.rb144
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_base.rb24
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_part.rb78
-rw-r--r--activerecord/lib/active_record/associations/join_helper.rb56
-rw-r--r--activerecord/lib/active_record/associations/preloader.rb177
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb126
-rw-r--r--activerecord/lib/active_record/associations/preloader/belongs_to.rb17
-rw-r--r--activerecord/lib/active_record/associations/preloader/collection_association.rb24
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb60
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_many.rb17
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_many_through.rb15
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_one.rb23
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_one_through.rb9
-rw-r--r--activerecord/lib/active_record/associations/preloader/singular_association.rb21
-rw-r--r--activerecord/lib/active_record/associations/preloader/through_association.rb67
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb55
-rw-r--r--activerecord/lib/active_record/associations/through_association.rb80
-rw-r--r--activerecord/lib/active_record/associations/through_association_scope.rb154
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb28
-rw-r--r--activerecord/lib/active_record/attribute_methods/before_type_cast.rb20
-rw-r--r--activerecord/lib/active_record/attribute_methods/dirty.rb10
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb41
-rw-r--r--activerecord/lib/active_record/attribute_methods/read.rb54
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb21
-rw-r--r--activerecord/lib/active_record/attribute_methods/write.rb10
-rw-r--r--activerecord/lib/active_record/autosave_association.rb218
-rw-r--r--activerecord/lib/active_record/base.rb703
-rw-r--r--activerecord/lib/active_record/callbacks.rb99
-rw-r--r--activerecord/lib/active_record/coders/yaml_column.rb41
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb92
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb16
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb82
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb32
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/quoting.rb46
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb283
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb128
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb38
-rw-r--r--activerecord/lib/active_record/connection_adapters/column.rb268
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb101
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb292
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb201
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb18
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb117
-rw-r--r--activerecord/lib/active_record/counter_cache.rb11
-rw-r--r--activerecord/lib/active_record/dynamic_finder_match.rb39
-rw-r--r--activerecord/lib/active_record/dynamic_scope_match.rb23
-rw-r--r--activerecord/lib/active_record/errors.rb8
-rw-r--r--activerecord/lib/active_record/fixtures.rb406
-rw-r--r--activerecord/lib/active_record/identity_map.rb102
-rw-r--r--activerecord/lib/active_record/locale/en.yml4
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb34
-rw-r--r--activerecord/lib/active_record/locking/pessimistic.rb16
-rw-r--r--activerecord/lib/active_record/log_subscriber.rb16
-rw-r--r--activerecord/lib/active_record/migration.rb475
-rw-r--r--activerecord/lib/active_record/migration/command_recorder.rb103
-rw-r--r--activerecord/lib/active_record/named_scope.rb55
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb106
-rw-r--r--activerecord/lib/active_record/observer.rb47
-rw-r--r--activerecord/lib/active_record/persistence.rb123
-rw-r--r--activerecord/lib/active_record/railtie.rb33
-rw-r--r--activerecord/lib/active_record/railties/databases.rake120
-rw-r--r--activerecord/lib/active_record/reflection.rb253
-rw-r--r--activerecord/lib/active_record/relation.rb156
-rw-r--r--activerecord/lib/active_record/relation/batches.rb12
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb188
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb110
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb32
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb314
-rw-r--r--activerecord/lib/active_record/relation/spawn_methods.rb115
-rw-r--r--activerecord/lib/active_record/result.rb34
-rw-r--r--activerecord/lib/active_record/schema.rb11
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb26
-rw-r--r--activerecord/lib/active_record/serialization.rb8
-rw-r--r--activerecord/lib/active_record/serializers/xml_serializer.rb22
-rw-r--r--activerecord/lib/active_record/session_store.rb27
-rw-r--r--activerecord/lib/active_record/test_case.rb30
-rw-r--r--activerecord/lib/active_record/timestamp.rb65
-rw-r--r--activerecord/lib/active_record/transactions.rb49
-rw-r--r--activerecord/lib/active_record/validations.rb39
-rw-r--r--activerecord/lib/active_record/validations/associated.rb8
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb88
-rw-r--r--activerecord/lib/active_record/version.rb6
-rw-r--r--activerecord/lib/rails/generators/active_record.rb8
-rw-r--r--activerecord/lib/rails/generators/active_record/migration.rb15
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/migration.rb12
-rw-r--r--activerecord/lib/rails/generators/active_record/model/model_generator.rb3
-rw-r--r--activerecord/lib/rails/generators/active_record/model/templates/migration.rb11
-rw-r--r--activerecord/lib/rails/generators/active_record/model/templates/model.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/model/templates/module.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/observer/templates/observer.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb4
-rw-r--r--activerecord/test/active_record/connection_adapters/fake_adapter.rb36
-rw-r--r--activerecord/test/cases/adapter_test.rb12
-rw-r--r--activerecord/test/cases/adapters/mysql/connection_test.rb63
-rw-r--r--activerecord/test/cases/adapters/mysql/reserved_word_test.rb24
-rw-r--r--activerecord/test/cases/adapters/mysql/schema_test.rb36
-rw-r--r--activerecord/test/cases/adapters/mysql/sp_test.rb15
-rw-r--r--activerecord/test/cases/adapters/mysql2/connection_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/reserved_word_test.rb18
-rw-r--r--activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb51
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb32
-rw-r--r--activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb19
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb67
-rw-r--r--activerecord/test/cases/aggregations_test.rb2
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb252
-rw-r--r--activerecord/test/cases/associations/callbacks_test.rb13
-rw-r--r--activerecord/test/cases/associations/cascaded_eager_loading_test.rb57
-rw-r--r--activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb3
-rw-r--r--activerecord/test/cases/associations/eager_load_nested_include_test.rb2
-rw-r--r--activerecord/test/cases/associations/eager_test.rb185
-rw-r--r--activerecord/test/cases/associations/extension_test.rb25
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb206
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb205
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb373
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb153
-rw-r--r--activerecord/test/cases/associations/has_one_through_associations_test.rb124
-rw-r--r--activerecord/test/cases/associations/identity_map_test.rb137
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb32
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb118
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb96
-rw-r--r--activerecord/test/cases/associations/nested_through_associations_test.rb546
-rw-r--r--activerecord/test/cases/associations_test.rb60
-rw-r--r--activerecord/test/cases/attribute_methods/read_test.rb61
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb101
-rw-r--r--activerecord/test/cases/autosave_association_test.rb452
-rw-r--r--activerecord/test/cases/base_test.rb392
-rw-r--r--activerecord/test/cases/batches_test.rb3
-rw-r--r--activerecord/test/cases/bind_parameter_test.rb90
-rw-r--r--activerecord/test/cases/calculations_test.rb73
-rw-r--r--activerecord/test/cases/callbacks_test.rb24
-rw-r--r--activerecord/test/cases/clone_test.rb33
-rw-r--r--activerecord/test/cases/coders/yaml_column_test.rb46
-rw-r--r--activerecord/test/cases/column_definition_test.rb206
-rw-r--r--activerecord/test/cases/connection_pool_test.rb101
-rw-r--r--activerecord/test/cases/counter_cache_test.rb2
-rw-r--r--activerecord/test/cases/custom_locking_test.rb17
-rw-r--r--activerecord/test/cases/date_time_test.rb22
-rw-r--r--activerecord/test/cases/defaults_test.rb6
-rw-r--r--activerecord/test/cases/dirty_test.rb43
-rw-r--r--activerecord/test/cases/dup_test.rb103
-rw-r--r--activerecord/test/cases/dynamic_finder_match_test.rb98
-rw-r--r--activerecord/test/cases/finder_test.rb139
-rw-r--r--activerecord/test/cases/fixtures_test.rb69
-rw-r--r--activerecord/test/cases/habtm_destroy_order_test.rb51
-rw-r--r--activerecord/test/cases/helper.rb92
-rw-r--r--activerecord/test/cases/i18n_test.rb4
-rw-r--r--activerecord/test/cases/identity_map_test.rb402
-rw-r--r--activerecord/test/cases/inheritance_test.rb22
-rw-r--r--activerecord/test/cases/invertible_migration_test.rb57
-rw-r--r--activerecord/test/cases/json_serialization_test.rb17
-rw-r--r--activerecord/test/cases/lifecycle_test.rb43
-rw-r--r--activerecord/test/cases/locking_test.rb65
-rw-r--r--activerecord/test/cases/method_scoping_test.rb20
-rw-r--r--activerecord/test/cases/migration/command_recorder_test.rb108
-rw-r--r--activerecord/test/cases/migration_test.rb491
-rw-r--r--activerecord/test/cases/modules_test.rb5
-rw-r--r--activerecord/test/cases/named_scope_test.rb64
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb251
-rw-r--r--activerecord/test/cases/persistence_test.rb55
-rw-r--r--activerecord/test/cases/pooled_connections_test.rb9
-rw-r--r--activerecord/test/cases/primary_keys_test.rb2
-rw-r--r--activerecord/test/cases/query_cache_test.rb9
-rw-r--r--activerecord/test/cases/quoting_test.rb220
-rw-r--r--activerecord/test/cases/readonly_test.rb38
-rw-r--r--activerecord/test/cases/reflection_test.rb107
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb119
-rw-r--r--activerecord/test/cases/relation_test.rb139
-rw-r--r--activerecord/test/cases/relations_test.rb350
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb4
-rw-r--r--activerecord/test/cases/serialization_test.rb8
-rw-r--r--activerecord/test/cases/session_store/session_test.rb3
-rw-r--r--activerecord/test/cases/session_store/sql_bypass.rb4
-rw-r--r--activerecord/test/cases/timestamp_test.rb102
-rw-r--r--activerecord/test/cases/transaction_callbacks_test.rb12
-rw-r--r--activerecord/test/cases/transactions_test.rb47
-rw-r--r--activerecord/test/cases/unconnected_test.rb3
-rw-r--r--activerecord/test/cases/validations/association_validation_test.rb4
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb17
-rw-r--r--activerecord/test/cases/validations_test.rb43
-rw-r--r--activerecord/test/cases/xml_serialization_test.rb27
-rw-r--r--activerecord/test/cases/yaml_serialization_test.rb35
-rw-r--r--activerecord/test/connections/native_oracle/connection.rb41
-rw-r--r--activerecord/test/connections/native_sqlite3/connection.rb9
-rw-r--r--activerecord/test/connections/native_sqlite3/in_memory_connection.rb18
-rw-r--r--activerecord/test/connections/native_sqlite3_mem/connection.rb19
-rw-r--r--activerecord/test/fixtures/authors.yml6
-rw-r--r--activerecord/test/fixtures/books.yml2
-rw-r--r--activerecord/test/fixtures/cars.yml5
-rw-r--r--activerecord/test/fixtures/categories.yml5
-rw-r--r--activerecord/test/fixtures/categories_posts.yml8
-rw-r--r--activerecord/test/fixtures/categorizations.yml6
-rw-r--r--activerecord/test/fixtures/clubs.yml4
-rw-r--r--activerecord/test/fixtures/comments.yml10
-rw-r--r--activerecord/test/fixtures/companies.yml11
-rw-r--r--activerecord/test/fixtures/dashboards.yml5
-rw-r--r--activerecord/test/fixtures/essays.yml6
-rw-r--r--activerecord/test/fixtures/items.yml1
-rw-r--r--activerecord/test/fixtures/member_details.yml8
-rw-r--r--activerecord/test/fixtures/members.yml5
-rw-r--r--activerecord/test/fixtures/memberships.yml15
-rw-r--r--activerecord/test/fixtures/mixins.yml2
-rw-r--r--activerecord/test/fixtures/owners.yml1
-rw-r--r--activerecord/test/fixtures/posts.yml30
-rw-r--r--activerecord/test/fixtures/ratings.yml14
-rw-r--r--activerecord/test/fixtures/ships.yml1
-rw-r--r--activerecord/test/fixtures/speedometers.yml6
-rw-r--r--activerecord/test/fixtures/sponsors.yml9
-rw-r--r--activerecord/test/fixtures/subscribers.yml4
-rw-r--r--activerecord/test/fixtures/taggings.yml52
-rw-r--r--activerecord/test/fixtures/tags.yml8
-rw-r--r--activerecord/test/fixtures/tasks.yml2
-rw-r--r--activerecord/test/fixtures/traffic_lights.yml6
-rw-r--r--activerecord/test/migrations/empty/.gitkeep0
-rw-r--r--activerecord/test/migrations/interleaved/pass_1/3_interleaved_innocent_jointable.rb (renamed from activerecord/test/migrations/interleaved/pass_2/3_innocent_jointable.rb)4
-rw-r--r--activerecord/test/migrations/interleaved/pass_2/1_interleaved_people_have_last_names.rb (renamed from activerecord/test/migrations/valid/1_people_have_last_names.rb)4
-rw-r--r--activerecord/test/migrations/interleaved/pass_2/3_interleaved_innocent_jointable.rb (renamed from activerecord/test/migrations/interleaved/pass_3/3_innocent_jointable.rb)4
-rw-r--r--activerecord/test/migrations/interleaved/pass_3/1_interleaved_people_have_last_names.rb (renamed from activerecord/test/migrations/interleaved/pass_3/1_people_have_last_names.rb)4
-rw-r--r--activerecord/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb8
-rw-r--r--activerecord/test/migrations/interleaved/pass_3/2_interleaved_i_raise_on_down.rb8
-rw-r--r--activerecord/test/migrations/interleaved/pass_3/3_interleaved_innocent_jointable.rb (renamed from activerecord/test/migrations/interleaved/pass_1/3_innocent_jointable.rb)4
-rw-r--r--activerecord/test/migrations/to_copy/1_people_have_hobbies.rb9
-rw-r--r--activerecord/test/migrations/to_copy/2_people_have_descriptions.rb9
-rw-r--r--activerecord/test/migrations/to_copy2/1_create_articles.rb7
-rw-r--r--activerecord/test/migrations/to_copy2/2_create_comments.rb7
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb9
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb9
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb7
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb7
-rw-r--r--activerecord/test/migrations/valid/1_valid_people_have_last_names.rb (renamed from activerecord/test/migrations/interleaved/pass_2/1_people_have_last_names.rb)4
-rw-r--r--activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb9
-rw-r--r--activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb12
-rw-r--r--activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb12
-rw-r--r--activerecord/test/models/author.rb56
-rw-r--r--activerecord/test/models/book.rb2
-rw-r--r--activerecord/test/models/boolean.rb2
-rw-r--r--activerecord/test/models/bulb.rb14
-rw-r--r--activerecord/test/models/car.rb18
-rw-r--r--activerecord/test/models/categorization.rb17
-rw-r--r--activerecord/test/models/category.rb7
-rw-r--r--activerecord/test/models/club.rb4
-rw-r--r--activerecord/test/models/comment.rb10
-rw-r--r--activerecord/test/models/company.rb37
-rw-r--r--activerecord/test/models/contact.rb10
-rw-r--r--activerecord/test/models/contract.rb2
-rw-r--r--activerecord/test/models/customer.rb2
-rw-r--r--activerecord/test/models/developer.rb5
-rw-r--r--activerecord/test/models/engine.rb1
-rw-r--r--activerecord/test/models/essay.rb2
-rw-r--r--activerecord/test/models/eye.rb37
-rw-r--r--activerecord/test/models/job.rb2
-rw-r--r--activerecord/test/models/joke.rb4
-rw-r--r--activerecord/test/models/lesson.rb11
-rw-r--r--activerecord/test/models/member.rb24
-rw-r--r--activerecord/test/models/member_detail.rb2
-rw-r--r--activerecord/test/models/minivan.rb4
-rw-r--r--activerecord/test/models/organization.rb8
-rw-r--r--activerecord/test/models/person.rb33
-rw-r--r--activerecord/test/models/pet.rb12
-rw-r--r--activerecord/test/models/pirate.rb8
-rw-r--r--activerecord/test/models/post.rb54
-rw-r--r--activerecord/test/models/project.rb21
-rw-r--r--activerecord/test/models/rating.rb4
-rw-r--r--activerecord/test/models/reader.rb3
-rw-r--r--activerecord/test/models/reference.rb14
-rw-r--r--activerecord/test/models/reply.rb7
-rw-r--r--activerecord/test/models/shop.rb2
-rw-r--r--activerecord/test/models/sponsor.rb5
-rw-r--r--activerecord/test/models/student.rb3
-rw-r--r--activerecord/test/models/subject.rb12
-rw-r--r--activerecord/test/models/tagging.rb6
-rw-r--r--activerecord/test/models/task.rb4
-rw-r--r--activerecord/test/models/topic.rb15
-rw-r--r--activerecord/test/models/traffic_light.rb3
-rw-r--r--activerecord/test/models/tyre.rb3
-rw-r--r--activerecord/test/schema/mysql_specific_schema.rb11
-rw-r--r--activerecord/test/schema/postgresql_specific_schema.rb2
-rw-r--r--activerecord/test/schema/schema.rb157
-rw-r--r--activeresource/CHANGELOG39
-rw-r--r--activeresource/MIT-LICENSE2
-rw-r--r--activeresource/README.rdoc46
-rwxr-xr-x[-rw-r--r--]activeresource/Rakefile21
-rw-r--r--activeresource/lib/active_resource.rb1
-rw-r--r--activeresource/lib/active_resource/base.rb104
-rw-r--r--activeresource/lib/active_resource/connection.rb12
-rw-r--r--activeresource/lib/active_resource/custom_methods.rb4
-rw-r--r--activeresource/lib/active_resource/exceptions.rb3
-rw-r--r--activeresource/lib/active_resource/http_mock.rb129
-rw-r--r--activeresource/lib/active_resource/schema.rb4
-rw-r--r--activeresource/lib/active_resource/validations.rb30
-rw-r--r--activeresource/lib/active_resource/version.rb6
-rw-r--r--activeresource/test/abstract_unit.rb105
-rw-r--r--activeresource/test/cases/authorization_test.rb12
-rw-r--r--activeresource/test/cases/base/custom_methods_test.rb12
-rw-r--r--activeresource/test/cases/base/schema_test.rb107
-rw-r--r--activeresource/test/cases/base_test.rb185
-rw-r--r--activeresource/test/cases/finder_test.rb98
-rw-r--r--activeresource/test/cases/format_test.rb2
-rw-r--r--activeresource/test/cases/http_mock_test.rb130
-rw-r--r--activeresource/test/cases/validations_test.rb18
-rw-r--r--activeresource/test/connection_test.rb20
-rw-r--r--activeresource/test/fixtures/address.rb19
-rw-r--r--activeresource/test/fixtures/project.rb19
-rw-r--r--activeresource/test/fixtures/sound.rb6
-rw-r--r--activeresource/test/fixtures/subscription_plan.rb5
-rw-r--r--activesupport/CHANGELOG117
-rw-r--r--activesupport/MIT-LICENSE2
-rw-r--r--activesupport/README.rdoc2
-rwxr-xr-x[-rw-r--r--]activesupport/Rakefile17
-rw-r--r--activesupport/bin/generate_tables4
-rw-r--r--activesupport/lib/active_support.rb2
-rw-r--r--activesupport/lib/active_support/backtrace_cleaner.rb2
-rw-r--r--activesupport/lib/active_support/base64.rb6
-rw-r--r--activesupport/lib/active_support/benchmarkable.rb6
-rw-r--r--activesupport/lib/active_support/buffered_logger.rb1
-rw-r--r--activesupport/lib/active_support/cache.rb60
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb7
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb4
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache.rb53
-rw-r--r--activesupport/lib/active_support/callbacks.rb364
-rw-r--r--activesupport/lib/active_support/concern.rb140
-rw-r--r--activesupport/lib/active_support/configurable.rb57
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/array/random_access.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/array/wrap.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/big_decimal/conversions.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/cgi.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute.rb36
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute_accessors.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb106
-rw-r--r--activesupport/lib/active_support/core_ext/class/subclasses.rb54
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/date/conversions.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/date/zones.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/calculations.rb36
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/conversions.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/zones.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb15
-rw-r--r--activesupport/lib/active_support/core_ext/float/rounding.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/hash.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/hash/conversions.rb48
-rw-r--r--activesupport/lib/active_support/core_ext/hash/deep_dup.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/hash/indifferent_access.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/hash/keys.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/hash/reverse_merge.rb23
-rw-r--r--activesupport/lib/active_support/core_ext/integer/time.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/kernel/reporting.rb21
-rw-r--r--activesupport/lib/active_support/core_ext/logger.rb49
-rw-r--r--activesupport/lib/active_support/core_ext/module/anonymous.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb27
-rw-r--r--activesupport/lib/active_support/core_ext/module/attr_internal.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/module/attribute_accessors.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/deprecation.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/remove_method.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/synchronization.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/numeric/time.rb22
-rw-r--r--activesupport/lib/active_support/core_ext/object.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/object/blank.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/instance_variables.rb40
-rw-r--r--activesupport/lib/active_support/core_ext/object/returning.rb43
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_param.rb22
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_query.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/object/with_options.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/range.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/range/conversions.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/range/cover.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/string.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/string/access.rb14
-rw-r--r--activesupport/lib/active_support/core_ext/string/filters.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/string/inflections.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/string/multibyte.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb27
-rw-r--r--activesupport/lib/active_support/core_ext/string/strip.rb26
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb33
-rw-r--r--activesupport/lib/active_support/core_ext/time/conversions.rb30
-rw-r--r--activesupport/lib/active_support/core_ext/time/zones.rb18
-rw-r--r--activesupport/lib/active_support/core_ext/uri.rb8
-rw-r--r--activesupport/lib/active_support/dependencies.rb190
-rw-r--r--activesupport/lib/active_support/deprecation.rb4
-rw-r--r--activesupport/lib/active_support/deprecation/behaviors.rb7
-rw-r--r--activesupport/lib/active_support/deprecation/proxy_wrappers.rb4
-rw-r--r--activesupport/lib/active_support/deprecation/reporting.rb18
-rw-r--r--activesupport/lib/active_support/duration.rb8
-rw-r--r--activesupport/lib/active_support/file_update_checker.rb2
-rw-r--r--activesupport/lib/active_support/file_watcher.rb36
-rw-r--r--activesupport/lib/active_support/gzip.rb6
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb28
-rw-r--r--activesupport/lib/active_support/i18n.rb2
-rw-r--r--activesupport/lib/active_support/i18n_railtie.rb29
-rw-r--r--activesupport/lib/active_support/inflections.rb4
-rw-r--r--activesupport/lib/active_support/inflector/inflections.rb2
-rw-r--r--activesupport/lib/active_support/inflector/transliterate.rb1
-rw-r--r--activesupport/lib/active_support/json/backends/jsongem.rb6
-rw-r--r--activesupport/lib/active_support/json/backends/yajl.rb6
-rw-r--r--activesupport/lib/active_support/json/backends/yaml.rb45
-rw-r--r--activesupport/lib/active_support/json/encoding.rb57
-rw-r--r--activesupport/lib/active_support/lazy_load_hooks.rb18
-rw-r--r--activesupport/lib/active_support/locale/en.yml6
-rw-r--r--activesupport/lib/active_support/log_subscriber.rb71
-rw-r--r--activesupport/lib/active_support/log_subscriber/test_helper.rb9
-rw-r--r--activesupport/lib/active_support/memoizable.rb2
-rw-r--r--activesupport/lib/active_support/message_encryptor.rb36
-rw-r--r--activesupport/lib/active_support/message_verifier.rb16
-rw-r--r--activesupport/lib/active_support/multibyte.rb2
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb9
-rw-r--r--activesupport/lib/active_support/multibyte/unicode.rb2
-rw-r--r--activesupport/lib/active_support/notifications.rb17
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb29
-rw-r--r--activesupport/lib/active_support/ordered_options.rb30
-rw-r--r--activesupport/lib/active_support/rescuable.rb1
-rw-r--r--activesupport/lib/active_support/secure_random.rb16
-rw-r--r--activesupport/lib/active_support/test_case.rb3
-rw-r--r--activesupport/lib/active_support/testing/assertions.rb14
-rw-r--r--activesupport/lib/active_support/testing/declarative.rb8
-rw-r--r--activesupport/lib/active_support/testing/default.rb9
-rw-r--r--activesupport/lib/active_support/testing/isolation.rb2
-rw-r--r--activesupport/lib/active_support/testing/pending.rb10
-rw-r--r--activesupport/lib/active_support/testing/performance.rb10
-rw-r--r--activesupport/lib/active_support/testing/setup_and_teardown.rb8
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb24
-rw-r--r--activesupport/lib/active_support/version.rb6
-rw-r--r--activesupport/lib/active_support/whiny_nil.rb2
-rw-r--r--activesupport/lib/active_support/xml_mini.rb8
-rw-r--r--activesupport/lib/active_support/xml_mini/libxml.rb1
-rw-r--r--activesupport/lib/active_support/xml_mini/libxmlsax.rb3
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogiri.rb1
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogirisax.rb4
-rw-r--r--activesupport/lib/active_support/xml_mini/rexml.rb3
-rw-r--r--activesupport/test/abstract_unit.rb13
-rw-r--r--activesupport/test/autoloading_fixtures/class_folder/nested_class.rb2
-rw-r--r--activesupport/test/buffered_logger_test.rb4
-rw-r--r--activesupport/test/caching_test.rb19
-rw-r--r--activesupport/test/callback_inheritance_test.rb32
-rw-r--r--activesupport/test/callbacks_test.rb113
-rw-r--r--activesupport/test/class_cache_test.rb108
-rw-r--r--activesupport/test/clean_backtrace_test.rb14
-rw-r--r--activesupport/test/clean_logger_test.rb4
-rw-r--r--activesupport/test/configurable_test.rb26
-rw-r--r--activesupport/test/core_ext/array_ext_test.rb17
-rw-r--r--activesupport/test/core_ext/bigdecimal.rb10
-rw-r--r--activesupport/test/core_ext/bigdecimal_test.rb17
-rw-r--r--activesupport/test/core_ext/cgi_ext_test.rb15
-rw-r--r--activesupport/test/core_ext/class/attribute_accessor_test.rb10
-rw-r--r--activesupport/test/core_ext/class/attribute_test.rb5
-rw-r--r--activesupport/test/core_ext/class/class_inheritable_attributes_test.rb27
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb87
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb28
-rw-r--r--activesupport/test/core_ext/duration_test.rb31
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb2
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb127
-rw-r--r--activesupport/test/core_ext/kernel_test.rb11
-rw-r--r--activesupport/test/core_ext/module/anonymous_test.rb2
-rw-r--r--activesupport/test/core_ext/module/attr_accessor_with_default_test.rb10
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_test.rb2
-rw-r--r--activesupport/test/core_ext/module/attribute_aliasing_test.rb6
-rw-r--r--activesupport/test/core_ext/module/reachable_test.rb16
-rw-r--r--activesupport/test/core_ext/module/synchronization_test.rb1
-rw-r--r--activesupport/test/core_ext/module_test.rb17
-rw-r--r--activesupport/test/core_ext/numeric_ext_test.rb62
-rw-r--r--activesupport/test/core_ext/object/to_query_test.rb8
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb55
-rw-r--r--activesupport/test/core_ext/range_ext_test.rb12
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb103
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb38
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb32
-rw-r--r--activesupport/test/dependencies_test.rb29
-rw-r--r--activesupport/test/file_watcher_test.rb233
-rw-r--r--activesupport/test/gzip_test.rb13
-rw-r--r--activesupport/test/i18n_test.rb34
-rw-r--r--activesupport/test/inflector_test.rb39
-rw-r--r--activesupport/test/inflector_test_cases.rb1
-rw-r--r--activesupport/test/json/decoding_test.rb24
-rw-r--r--activesupport/test/json/encoding_test.rb96
-rw-r--r--activesupport/test/memoizable_test.rb14
-rw-r--r--activesupport/test/message_encryptor_test.rb14
-rw-r--r--activesupport/test/multibyte_conformance.rb30
-rw-r--r--activesupport/test/notifications_test.rb9
-rw-r--r--activesupport/test/option_merger_test.rb2
-rw-r--r--activesupport/test/ordered_hash_test.rb52
-rw-r--r--activesupport/test/rescuable_test.rb8
-rw-r--r--activesupport/test/safe_buffer_test.rb22
-rw-r--r--activesupport/test/test_case_test.rb61
-rw-r--r--activesupport/test/test_test.rb27
-rw-r--r--activesupport/test/test_xml_mini.rb117
-rw-r--r--activesupport/test/time_zone_test.rb2
-rw-r--r--activesupport/test/whiny_nil_test.rb2
-rwxr-xr-xci/ci_build.rb89
-rw-r--r--ci/ci_setup_notes.txt10
-rw-r--r--ci/site_config.rb12
-rw-r--r--load_paths.rb2
-rw-r--r--rails.gemspec2
-rw-r--r--railties/CHANGELOG198
-rw-r--r--railties/MIT-LICENSE2
-rw-r--r--railties/README.rdoc5
-rwxr-xr-x[-rw-r--r--]railties/Rakefile25
-rw-r--r--railties/guides/assets/javascripts/code_highlighter.js188
-rw-r--r--railties/guides/assets/javascripts/highlighters.js90
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js59
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js75
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js59
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js65
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js100
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js97
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js91
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js55
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js41
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js52
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js67
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js52
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js57
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js58
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js72
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js88
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js33
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js74
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js64
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js55
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js94
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js51
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js66
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js56
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js69
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shCore.js17
-rw-r--r--railties/guides/assets/stylesheets/fixes.css16
-rw-r--r--railties/guides/assets/stylesheets/main.css49
-rw-r--r--railties/guides/assets/stylesheets/syntax.css31
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css226
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css328
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css331
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css339
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css328
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css117
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css120
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css128
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css117
-rwxr-xr-xrailties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css116
-rw-r--r--railties/guides/rails_guides.rb4
-rw-r--r--railties/guides/rails_guides/generator.rb48
-rw-r--r--railties/guides/rails_guides/helpers.rb9
-rw-r--r--railties/guides/rails_guides/indexer.rb3
-rw-r--r--railties/guides/source/2_2_release_notes.textile6
-rw-r--r--railties/guides/source/2_3_release_notes.textile12
-rw-r--r--railties/guides/source/3_0_release_notes.textile64
-rw-r--r--railties/guides/source/action_controller_overview.textile82
-rw-r--r--railties/guides/source/action_mailer_basics.textile64
-rw-r--r--railties/guides/source/action_view_overview.textile143
-rw-r--r--railties/guides/source/active_record_basics.textile6
-rw-r--r--railties/guides/source/active_record_querying.textile319
-rw-r--r--railties/guides/source/active_record_validations_callbacks.textile153
-rw-r--r--railties/guides/source/active_support_core_extensions.textile290
-rw-r--r--railties/guides/source/ajax_on_rails.textile58
-rw-r--r--railties/guides/source/api_documentation_guidelines.textile30
-rw-r--r--railties/guides/source/association_basics.textile141
-rw-r--r--railties/guides/source/caching_with_rails.textile112
-rw-r--r--railties/guides/source/command_line.textile87
-rw-r--r--railties/guides/source/configuring.textile435
-rw-r--r--railties/guides/source/contribute.textile16
-rw-r--r--railties/guides/source/contributing_to_rails.textile308
-rw-r--r--railties/guides/source/contributing_to_ruby_on_rails.textile392
-rw-r--r--railties/guides/source/credits.html.erb6
-rw-r--r--railties/guides/source/debugging_rails_applications.textile70
-rw-r--r--railties/guides/source/form_helpers.textile137
-rw-r--r--railties/guides/source/generators.textile334
-rw-r--r--railties/guides/source/getting_started.textile109
-rw-r--r--railties/guides/source/i18n.textile156
-rw-r--r--railties/guides/source/index.html.erb34
-rw-r--r--railties/guides/source/initialization.textile3771
-rw-r--r--railties/guides/source/layout.html.erb46
-rw-r--r--railties/guides/source/layouts_and_rendering.textile135
-rw-r--r--railties/guides/source/migrations.textile30
-rw-r--r--railties/guides/source/nested_model_forms.textile18
-rw-r--r--railties/guides/source/performance_testing.textile46
-rw-r--r--railties/guides/source/plugins.textile1454
-rw-r--r--railties/guides/source/rails_application_templates.textile28
-rw-r--r--railties/guides/source/rails_on_rack.textile19
-rw-r--r--railties/guides/source/routing.textile255
-rw-r--r--railties/guides/source/ruby_on_rails_guides_guidelines.textile83
-rw-r--r--railties/guides/source/security.textile36
-rw-r--r--railties/guides/source/testing.textile65
-rw-r--r--railties/guides/w3c_validator.rb20
-rw-r--r--railties/lib/rails.rb8
-rw-r--r--railties/lib/rails/application.rb111
-rw-r--r--railties/lib/rails/application/bootstrap.rb17
-rw-r--r--railties/lib/rails/application/configurable.rb19
-rw-r--r--railties/lib/rails/application/configuration.rb65
-rw-r--r--railties/lib/rails/application/finisher.rb19
-rw-r--r--railties/lib/rails/application/railties.rb30
-rw-r--r--railties/lib/rails/application/routes_reloader.rb45
-rw-r--r--railties/lib/rails/backtrace_cleaner.rb2
-rw-r--r--railties/lib/rails/cli.rb14
-rw-r--r--railties/lib/rails/code_statistics.rb10
-rw-r--r--railties/lib/rails/commands.rb25
-rw-r--r--railties/lib/rails/commands/application.rb12
-rw-r--r--railties/lib/rails/commands/console.rb2
-rw-r--r--railties/lib/rails/commands/dbconsole.rb12
-rw-r--r--railties/lib/rails/commands/plugin.rb11
-rw-r--r--railties/lib/rails/commands/plugin_new.rb10
-rw-r--r--railties/lib/rails/commands/runner.rb6
-rw-r--r--railties/lib/rails/commands/server.rb4
-rw-r--r--railties/lib/rails/configuration.rb89
-rw-r--r--railties/lib/rails/console/app.rb4
-rw-r--r--railties/lib/rails/deprecation.rb62
-rw-r--r--railties/lib/rails/engine.rb543
-rw-r--r--railties/lib/rails/engine/configurable.rb25
-rw-r--r--railties/lib/rails/engine/configuration.rb67
-rw-r--r--railties/lib/rails/engine/railties.rb33
-rw-r--r--railties/lib/rails/generators.rb13
-rw-r--r--railties/lib/rails/generators/actions.rb42
-rw-r--r--railties/lib/rails/generators/app_base.rb170
-rw-r--r--railties/lib/rails/generators/base.rb6
-rw-r--r--railties/lib/rails/generators/generated_attribute.rb1
-rw-r--r--railties/lib/rails/generators/migration.rb8
-rw-r--r--railties/lib/rails/generators/named_base.rb73
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb195
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile29
-rw-r--r--railties/lib/rails/generators/rails/app/templates/README6
-rwxr-xr-x[-rw-r--r--]railties/lib/rails/generators/rails/app/templates/Rakefile2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb13
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/boot.rb13
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml17
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/locales/en.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/routes.rb10
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/index.html16
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js8176
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js148
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js733
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js208
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js175
-rw-r--r--railties/lib/rails/generators/rails/controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/rails/generator/USAGE5
-rw-r--r--railties/lib/rails/generators/rails/generator/generator_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/helper/templates/helper.rb2
-rw-r--r--railties/lib/rails/generators/rails/migration/USAGE8
-rw-r--r--railties/lib/rails/generators/rails/plugin/USAGE2
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb7
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/USAGE10
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb290
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec9
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/Gemfile11
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE20
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc3
-rwxr-xr-xrailties/lib/rails/generators/rails/plugin_new/templates/Rakefile21
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb6
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/gitignore6
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb6
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb7
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb16
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb10
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt5
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb7
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb13
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb10
-rw-r--r--railties/lib/rails/generators/rails/resource/resource_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/resource_helpers.rb8
-rw-r--r--railties/lib/rails/generators/test_case.rb22
-rw-r--r--railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/model/templates/fixtures.yml2
-rw-r--r--railties/lib/rails/generators/test_unit/model/templates/unit_test.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb2
-rw-r--r--railties/lib/rails/info.rb1
-rw-r--r--railties/lib/rails/info_controller.rb2
-rw-r--r--railties/lib/rails/info_routes.rb3
-rw-r--r--railties/lib/rails/paths.rb162
-rw-r--r--railties/lib/rails/plugin.rb41
-rw-r--r--railties/lib/rails/rack/log_tailer.rb2
-rw-r--r--railties/lib/rails/rack/logger.rb4
-rw-r--r--railties/lib/rails/railtie.rb100
-rw-r--r--railties/lib/rails/railtie/configurable.rb30
-rw-r--r--railties/lib/rails/railtie/configuration.rb47
-rw-r--r--railties/lib/rails/ruby_version_check.rb3
-rw-r--r--railties/lib/rails/script_rails_loader.rb4
-rw-r--r--railties/lib/rails/tasks.rb1
-rw-r--r--railties/lib/rails/tasks/documentation.rake10
-rw-r--r--railties/lib/rails/tasks/engine.rake69
-rw-r--r--railties/lib/rails/tasks/framework.rake19
-rw-r--r--railties/lib/rails/tasks/misc.rake2
-rw-r--r--railties/lib/rails/tasks/railties.rake29
-rw-r--r--railties/lib/rails/tasks/routes.rake31
-rw-r--r--railties/lib/rails/test_help.rb23
-rw-r--r--railties/lib/rails/test_unit/railtie.rb2
-rw-r--r--railties/lib/rails/test_unit/testing.rake10
-rw-r--r--railties/lib/rails/version.rb6
-rw-r--r--railties/railties.gemspec4
-rw-r--r--railties/test/abstract_unit.rb7
-rw-r--r--railties/test/application/configuration_test.rb128
-rw-r--r--railties/test/application/console_test.rb17
-rw-r--r--railties/test/application/generators_test.rb7
-rw-r--r--railties/test/application/initializers/frameworks_test.rb82
-rw-r--r--railties/test/application/initializers/i18n_test.rb34
-rw-r--r--railties/test/application/loading_test.rb30
-rw-r--r--railties/test/application/middleware/best_practices_test.rb26
-rw-r--r--railties/test/application/middleware/cache_test.rb150
-rw-r--r--railties/test/application/middleware/remote_ip_test.rb63
-rw-r--r--railties/test/application/middleware/sendfile_test.rb56
-rw-r--r--railties/test/application/middleware/show_exceptions_test.rb37
-rw-r--r--railties/test/application/middleware_test.rb142
-rw-r--r--railties/test/application/paths_test.rb28
-rw-r--r--railties/test/application/rackup_test.rb7
-rw-r--r--railties/test/application/rake_test.rb70
-rw-r--r--railties/test/application/routing_test.rb112
-rw-r--r--railties/test/application/runner_test.rb4
-rw-r--r--railties/test/application/test_test.rb2
-rw-r--r--railties/test/fixtures/lib/app_builders/empty_builder.rb (renamed from railties/test/fixtures/lib/empty_builder.rb)0
-rw-r--r--railties/test/fixtures/lib/app_builders/simple_builder.rb7
-rw-r--r--railties/test/fixtures/lib/app_builders/tweak_builder.rb7
-rw-r--r--railties/test/fixtures/lib/create_test_dummy_template.rb1
-rw-r--r--railties/test/fixtures/lib/plugin_builders/empty_builder.rb2
-rw-r--r--railties/test/fixtures/lib/plugin_builders/simple_builder.rb7
-rw-r--r--railties/test/fixtures/lib/plugin_builders/spec_builder.rb19
-rw-r--r--railties/test/fixtures/lib/plugin_builders/tweak_builder.rb7
-rw-r--r--railties/test/fixtures/lib/simple_builder.rb7
-rw-r--r--railties/test/fixtures/lib/tweak_builder.rb7
-rw-r--r--railties/test/generators/actions_test.rb67
-rw-r--r--railties/test/generators/app_generator_test.rb214
-rw-r--r--railties/test/generators/generated_attribute_test.rb12
-rw-r--r--railties/test/generators/generator_generator_test.rb39
-rw-r--r--railties/test/generators/generators_test_helper.rb4
-rw-r--r--railties/test/generators/mailer_generator_test.rb9
-rw-r--r--railties/test/generators/migration_generator_test.rb15
-rw-r--r--railties/test/generators/model_generator_test.rb82
-rw-r--r--railties/test/generators/named_base_test.rb5
-rw-r--r--railties/test/generators/namespaced_generators_test.rb357
-rw-r--r--railties/test/generators/plugin_generator_test.rb18
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb229
-rw-r--r--railties/test/generators/resource_generator_test.rb5
-rw-r--r--railties/test/generators/scaffold_generator_test.rb73
-rw-r--r--railties/test/generators/shared_generator_tests.rb195
-rw-r--r--railties/test/generators_test.rb24
-rw-r--r--railties/test/isolation/abstract_unit.rb36
-rw-r--r--railties/test/paths_test.rb268
-rw-r--r--railties/test/rails_info_controller_test.rb10
-rw-r--r--railties/test/railties/engine_test.rb751
-rw-r--r--railties/test/railties/mounted_engine_test.rb174
-rw-r--r--railties/test/railties/plugin_test.rb29
-rw-r--r--railties/test/railties/railtie_test.rb42
-rw-r--r--railties/test/railties/shared_tests.rb108
-rw-r--r--railties/test/script_rails_loader_test.rb8
-rw-r--r--release.rb11
-rw-r--r--tasks/release.rb96
-rw-r--r--version.rb6
1245 files changed, 56363 insertions, 27043 deletions
diff --git a/.gitignore b/.gitignore
index 2dfdf96e7f..8daa1e4dcd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,12 +10,15 @@ activerecord/doc
actionpack/doc
actionmailer/doc
activesupport/doc
+activesupport/test/tmp
activemodel/test/fixtures/fixture_database.sqlite3
actionpack/test/tmp
activesupport/test/fixtures/isolation_test
+dist
railties/test/500.html
railties/test/fixtures/tmp
railties/test/initializer/root/log
railties/doc
railties/guides/output
railties/tmp
+.rvmrc
diff --git a/.yardopts b/.yardopts
new file mode 100644
index 0000000000..25ec38658f
--- /dev/null
+++ b/.yardopts
@@ -0,0 +1,4 @@
+--exclude /templates/
+--quiet
+act*/lib/**/*.rb
+railties/lib/**/*.rb
diff --git a/Gemfile b/Gemfile
index d594d20fac..879598c6db 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,41 +1,55 @@
source 'http://rubygems.org'
+gemspec
+
if ENV['AREL']
gem "arel", :path => ENV['AREL']
else
gem "arel", :git => "git://github.com/rails/arel.git"
end
-gem "rails", :path => File.dirname(__FILE__)
+gem "rack", :git => "git://github.com/rack/rack.git"
+gem "rack-test", :git => "git://github.com/brynary/rack-test.git"
gem "rake", ">= 0.8.7"
gem "mocha", ">= 0.9.8"
-gem "rdoc", ">= 2.5.9"
-gem "horo", ">= 1.0.1"
+
+group :doc do
+ gem "rdoc", "~> 3.4"
+ gem "horo", "= 1.0.3"
+ gem "RedCloth", "~> 4.2" if RUBY_VERSION < "1.9.3"
+end
# AS
gem "memcache-client", ">= 1.8.5"
-
-# AM
-gem "text-format", "~> 1.0.0"
+gem "fssm", "~> 0.2.5"
platforms :mri_18 do
gem "system_timer"
gem "ruby-debug", ">= 0.10.3"
+ gem 'ruby-prof'
+end
+
+platforms :mri_19 do
+ # TODO: Remove the conditional when ruby-debug19 supports Ruby >= 1.9.3
+ gem "ruby-debug19", :require => 'ruby-debug' if RUBY_VERSION < "1.9.3"
end
platforms :ruby do
+ if ENV["RB_FSEVENT"]
+ gem 'rb-fsevent'
+ end
gem 'json'
gem 'yajl-ruby'
- gem "nokogiri", ">= 1.4.3.1"
+ gem "nokogiri", ">= 1.4.4"
# AR
- gem "sqlite3-ruby", "~> 1.3.1", :require => 'sqlite3'
+ gem "sqlite3", "~> 1.3.3"
group :db do
gem "pg", ">= 0.9.0"
gem "mysql", ">= 2.8.1"
- gem "mysql2", :git => 'git://github.com/brianmario/mysql2.git'
+ gem "mysql2", :git => "git://github.com/brianmario/mysql2.git"
end
end
@@ -44,17 +58,25 @@ platforms :jruby do
gem "activerecord-jdbcsqlite3-adapter"
+ # 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"
gem "activerecord-jdbcpostgresql-adapter"
end
end
-env 'CI' do
- gem "nokogiri", ">= 1.4.3.1"
-
- platforms :ruby_18 do
- # fcgi gem doesn't compile on 1.9
- gem "fcgi", ">= 0.8.8"
+# gems that are necessary for ActiveRecord tests with Oracle database
+if ENV['ORACLE_ENHANCED_PATH'] || ENV['ORACLE_ENHANCED']
+ platforms :ruby do
+ gem 'ruby-oci8', ">= 2.0.4"
+ end
+ if ENV['ORACLE_ENHANCED_PATH']
+ gem 'activerecord-oracle_enhanced-adapter', :path => ENV['ORACLE_ENHANCED_PATH']
+ else
+ gem "activerecord-oracle_enhanced-adapter", :git => "git://github.com/rsim/oracle-enhanced.git"
end
end
diff --git a/RAILS_VERSION b/RAILS_VERSION
index 7706a9b5ac..30afce968e 100644
--- a/RAILS_VERSION
+++ b/RAILS_VERSION
@@ -1 +1 @@
-3.0.0.rc
+3.1.0.beta
diff --git a/README.rdoc b/README.rdoc
index 090a6bb68c..0b209cf56f 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,6 +1,6 @@
-== Welcome to Rails
+== Welcome to \Rails
-Rails is a web-application framework that includes everything needed to create
+\Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
This pattern splits the view (also called the presentation) into "dumb"
@@ -11,30 +11,30 @@ persist themselves to a database. The controller handles the incoming requests
(such as Save New Account, Update Product, Show Post) by manipulating the model
and directing data to the view.
-In Rails, the model is handled by what's called an object-relational mapping
+In \Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
-methods. You can read more about Active Record in
-link:files/vendor/rails/activerecord/README.html.
+methods. You can read more about Active Record in its
+{README}[link:files/activerecord/README_rdoc.html].
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
-Rails. You can read more about Action Pack in
-link:files/vendor/rails/actionpack/README.html.
+\Rails. You can read more about Action Pack in its
+{README}[link:files/actionpack/README_rdoc.html].
== Getting Started
-1. Install Rails at the command prompt if you haven't yet:
+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:
+2. At the command prompt, create a new \Rails application:
- rails new myapp
+ rails new myapp
where "myapp" is the application name.
@@ -48,20 +48,21 @@ link:files/vendor/rails/actionpack/README.html.
"Welcome aboard: You're riding Ruby on Rails!"
-5. Follow the guidelines to start developing your application. You can find
-the following resources handy:
+5. Follow the guidelines to start developing your application. You can find the following resources handy:
* The README file created within your application.
-* The {Getting Started Guide}[http://guides.rubyonrails.org/getting_started.html].
-* The {Ruby on Rails Tutorial Book}[http://railstutorial.org/book].
+* The {Getting Started with Rails}[http://guides.rubyonrails.org/getting_started.html].
+* The {Ruby on Rails Tutorial}[http://railstutorial.org/book].
+* The {Ruby on Rails Guides}[http://guides.rubyonrails.org].
+* The {API Documentation}[http://api.rubyonrails.org].
== Contributing
-We encourage you to contribute to Ruby on Rails! Please check out the {Contributing to Rails
+We encourage you to contribute to Ruby on \Rails! Please check out the {Contributing to Rails
guide}[http://edgeguides.rubyonrails.org/contributing_to_rails.html] for guidelines about how
to proceed. {Join us}[http://contributors.rubyonrails.org]!
== License
-Ruby on Rails is released under the MIT license.
+Ruby on \Rails is released under the MIT license.
diff --git a/Rakefile b/Rakefile
index ceb0e832b3..607ce01fd0 100644..100755
--- a/Rakefile
+++ b/Rakefile
@@ -1,34 +1,16 @@
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
+#!/usr/bin/env rake
-require 'rake'
require 'rdoc/task'
-require 'rake/gempackagetask'
-
-# RDoc skips some files in the Rails tree due to its binary? predicate. This is a quick
-# hack for edge docs, until we decide which is the correct way to address this issue.
-# If not fixed in RDoc itself, via an option or something, we should probably move this
-# to railties and use it also in doc:rails.
-def hijack_rdoc!
- require "rdoc/parser"
- class << RDoc::Parser
- def binary?(file)
- s = File.read(file, 1024) or return false
-
- if s[0, 2] == Marshal.dump('')[0, 2] then
- true
- elsif file =~ /erb\.rb$/ then
- false
- elsif s.index("\x00") then # ORIGINAL is s.scan(/<%|%>/).length >= 4 || s.index("\x00")
- true
- elsif 0.respond_to? :fdiv then
- s.count("^ -~\t\r\n").fdiv(s.size) > 0.3
- else # HACK 1.8.6
- (s.count("^ -~\t\r\n").to_f / s.size) > 0.3
- end
- end
- end
-end
+require 'net/http'
+
+$:.unshift File.expand_path('..', __FILE__)
+require "tasks/release"
+
+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 activeresource activerecord railties)
@@ -54,27 +36,6 @@ task :smoke do
system %(cd activerecord && #{$0} sqlite3:isolated_test)
end
-spec = eval(File.read('rails.gemspec'))
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.gem_spec = spec
-end
-
-desc "Release all gems to gemcutter. Package rails, package & push components, then push rails"
-task :release => :release_projects do
- require 'rake/gemcutter'
- Rake::Gemcutter::Tasks.new(spec).define
- Rake::Task['gem:push'].invoke
-end
-
-desc "Release all components to gemcutter."
-task :release_projects => :package do
- errors = []
- PROJECTS.each do |project|
- system(%(cd #{project} && #{$0} release)) || errors << project
- end
- fail("Errors in #{errors.join(', ')}") unless errors.empty?
-end
-
desc "Install gems for all projects."
task :install => :gem do
version = File.read("RAILS_VERSION").strip
@@ -88,8 +49,6 @@ end
desc "Generate documentation for the Rails framework"
RDoc::Task.new do |rdoc|
- hijack_rdoc!
-
rdoc.rdoc_dir = 'doc/rdoc'
rdoc.title = "Ruby on Rails Documentation"
@@ -126,6 +85,7 @@ RDoc::Task.new do |rdoc|
rdoc.rdoc_files.include('actionmailer/README.rdoc')
rdoc.rdoc_files.include('actionmailer/CHANGELOG')
rdoc.rdoc_files.include('actionmailer/lib/action_mailer/base.rb')
+ rdoc.rdoc_files.include('actionmailer/lib/action_mailer/mail_helper.rb')
rdoc.rdoc_files.exclude('actionmailer/lib/action_mailer/vendor/*')
rdoc.rdoc_files.include('activesupport/README.rdoc')
@@ -144,12 +104,7 @@ task :rdoc do
FileUtils.copy "activerecord/examples/associations.png", "doc/rdoc/files/examples/associations.png"
end
-desc "Publish API docs for Rails as a whole and for each component"
-task :pdoc => :rdoc do
- require 'rake/contrib/sshpublisher'
- Rake::SshDirPublisher.new("rails@api.rubyonrails.org", "public_html/api", "doc/rdoc").upload
-end
-
+desc 'Bump all versions to match version.rb'
task :update_versions do
require File.dirname(__FILE__) + "/version"
@@ -177,3 +132,27 @@ task :update_versions do
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('rails-hooks.hashref.com').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 b/actionmailer/CHANGELOG
index 76eab935e5..167c1da9c5 100644
--- a/actionmailer/CHANGELOG
+++ b/actionmailer/CHANGELOG
@@ -1,9 +1,16 @@
-*Rails 3.0.0 [release candidate] (July 26th, 2010)*
+*Rails 3.1.0 (unreleased)*
-* No material changes
+* No changes
+*Rails 3.0.2 (unreleased)*
-*Rails 3.0.0 [beta 4] (June 8th, 2010)*
+* No changes
+
+*Rails 3.0.1 (October 15, 2010)*
+
+* No Changes, just a version bump.
+
+*Rails 3.0.0 (August 29, 2010)*
* subject is automatically looked up on I18n using mailer_name and action_name as scope as in t(".subject") [JK]
@@ -11,16 +18,10 @@
* Added ability to pass Proc objects to the defaults hash [ML]
-
-*Rails 3.0.0 [beta 3] (April 13th, 2010)*
-
* Removed all quoting.rb type files from ActionMailer and put Mail 2.2.0 in instead [ML]
* Lot of updates to various test cases that now work better with the new Mail and so have different expectations
-
-*Rails 3.0.0 [beta 2] (April 1st, 2010)*
-
* Added interceptors and observers from Mail [ML]
ActionMailer::Base.register_interceptor calls Mail.register_interceptor
@@ -38,9 +39,6 @@
* Whole new API added with tests. See base.rb for full details. Old API is deprecated.
-
-*Rails 3.0.0 [beta 1] (February 4, 2010)*
-
* The Mail::Message class has helped methods for all the field types that return 'common' defaults for the common use case, so to get the subject, mail.subject will give you a string, mail.date will give you a DateTime object, mail.from will give you an array of address specs (mikel@test.lindsaar.net) etc. If you want to access the field object itself, call mail[:field_name] which will return the field object you want, which you can then chain, like mail[:from].formatted
* Mail#content_type now returns the content_type field as a string. If you want the mime type of a mail, then you call Mail#mime_type (eg, text/plain), if you want the parameters of the content type field, you call Mail#content_type_parameters which gives you a hash, eg {'format' => 'flowed', 'charset' => 'utf-8'}
@@ -181,7 +179,7 @@
* ActionMailer::Base documentation rewrite. Closes #4991 [Kevin Clark, Marcel Molina Jr.]
-* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
+* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
@@ -327,7 +325,7 @@
* Added that deliver_* will now return the email that was sent
-* Added that quoting to UTF-8 only happens if the characters used are in that range #955 [Jamis Buck]
+* Added that quoting to UTF-8 only happens if the characters used are in that range #955 [Jamis Buck]
* Fixed quoting for all address headers, not just to #955 [Jamis Buck]
@@ -366,7 +364,7 @@
@body = "Nothing to see here."
@charset = "iso-8859-1"
end
-
+
def unencoded_subject(recipient)
@recipients = recipient
@subject = "testing unencoded subject"
@@ -375,7 +373,7 @@
@encode_subject = false
@charset = "iso-8859-1"
end
-
+
*0.6.1* (January 18th, 2005)
diff --git a/actionmailer/MIT-LICENSE b/actionmailer/MIT-LICENSE
index a345a2419d..7ad1051066 100644
--- a/actionmailer/MIT-LICENSE
+++ b/actionmailer/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc
index b52c993f56..0fa18d751b 100644
--- a/actionmailer/README.rdoc
+++ b/actionmailer/README.rdoc
@@ -5,7 +5,7 @@ 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
+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.
@@ -23,7 +23,7 @@ This can be as simple as:
class Notifier < ActionMailer::Base
delivers_from 'system@loudthinking.com'
-
+
def welcome(recipient)
@recipient = recipient
mail(:to => recipient,
@@ -36,13 +36,13 @@ 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,
+ Hello there,
Mr. <%= @recipient %>
Thank you for signing up!
-
-And if the recipient was given as "david@loudthinking.com", the email
+
+And if the recipient was given as "david@loudthinking.com", the email
generated would look like this:
Date: Mon, 25 Jan 2010 22:48:09 +1100
@@ -55,18 +55,18 @@ generated would look like this:
charset="US-ASCII";
Content-Transfer-Encoding: 7bit
- Hello there,
+ Hello there,
Mr. david@loudthinking.com
-In previous version of rails you would call <tt>create_method_name</tt> and
+In previous version of Rails you would call <tt>create_method_name</tt> and
<tt>deliver_method_name</tt>. Rails 3.0 has a much simpler interface, you
simply call the method and optionally call +deliver+ on the return value.
Calling the method returns a Mail Message object:
- message = Notifier.welcome #=> Returns a Mail::Message object
- message.deliver #=> delivers the email
+ message = Notifier.welcome # => Returns a Mail::Message object
+ message.deliver # => delivers the email
Or you can just chain the methods together like:
@@ -74,10 +74,10 @@ Or you can just chain the methods together like:
== Receiving emails
-To receive emails, you need to implement a public instance method called <tt>receive</tt> that takes a
-tmail object as its single parameter. The Action Mailer framework has a corresponding class method,
+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 tmail object and calls the receive instance method.
+into the email object and calls the receive instance method.
Example:
@@ -90,7 +90,7 @@ Example:
if email.has_attachments?
for attachment in email.attachments
- page.attachments.create({
+ page.attachments.create({
:file => attachment, :description => email.subject
})
end
@@ -98,13 +98,13 @@ Example:
end
end
-This Mailman can be the target for Postfix or other MTAs. In Rails, you would use the runner in the
+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
+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
@@ -128,7 +128,7 @@ The latest version of Action Mailer can be installed with Rubygems:
Source code can be downloaded as part of the Rails project on GitHub
-* http://github.com/rails/rails/tree/master/actionmailer/
+* https://github.com/rails/rails/tree/master/actionmailer/
== License
@@ -145,3 +145,4 @@ API documentation is at
Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:
* https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets
+
diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile
index a47426bd07..df996acbc2 100644..100755
--- a/actionmailer/Rakefile
+++ b/actionmailer/Rakefile
@@ -1,8 +1,5 @@
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
-require 'rake'
+#!/usr/bin/env rake
require 'rake/testtask'
-require 'rdoc/task'
require 'rake/packagetask'
require 'rake/gempackagetask'
@@ -20,24 +17,11 @@ namespace :test do
task :isolated do
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
Dir.glob("test/**/*_test.rb").all? do |file|
- system(ruby, '-Ilib:test', file)
+ sh(ruby, '-Ilib:test', file)
end or raise "Failures"
end
end
-# Generate the RDoc documentation
-RDoc::Task.new { |rdoc|
- rdoc.rdoc_dir = 'doc'
- rdoc.title = "Action Mailer -- Easy email delivery and testing"
- rdoc.options << '--charset' << 'utf-8'
- rdoc.options << '-f' << 'horo'
- rdoc.options << '--main' << 'README.rdoc'
- rdoc.rdoc_files.include('README.rdoc', 'CHANGELOG')
- rdoc.rdoc_files.include('lib/action_mailer.rb')
- rdoc.rdoc_files.include('lib/action_mailer/*.rb')
- rdoc.rdoc_files.include('lib/action_mailer/delivery_method/*.rb')
-}
-
spec = eval(File.read('actionmailer.gemspec'))
Rake::GemPackageTask.new(spec) do |p|
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index daf30e434a..2ae85f8b57 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -20,5 +20,5 @@ Gem::Specification.new do |s|
s.has_rdoc = true
s.add_dependency('actionpack', version)
- s.add_dependency('mail', '~> 2.2.5')
+ s.add_dependency('mail', '~> 2.2.15')
end
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
index 6e2d288082..b9e682b711 100644
--- a/actionmailer/lib/action_mailer.rb
+++ b/actionmailer/lib/action_mailer.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -26,6 +26,7 @@ $:.unshift(actionpack_path) if File.directory?(actionpack_path) && !$:.include?(
require 'abstract_controller'
require 'action_view'
+require 'action_mailer/version'
# Common Active Support usage in Action Mailer
require 'active_support/core_ext/class'
@@ -43,7 +44,6 @@ module ActionMailer
autoload :Collector
autoload :Base
autoload :DeliveryMethods
- autoload :DeprecatedApi
autoload :MailHelper
autoload :OldApi
autoload :TestCase
diff --git a/actionmailer/lib/action_mailer/adv_attr_accessor.rb b/actionmailer/lib/action_mailer/adv_attr_accessor.rb
index be6b1feca9..c1aa8021ce 100644
--- a/actionmailer/lib/action_mailer/adv_attr_accessor.rb
+++ b/actionmailer/lib/action_mailer/adv_attr_accessor.rb
@@ -1,26 +1,28 @@
module ActionMailer
module AdvAttrAccessor #:nodoc:
- def adv_attr_accessor(*names)
- names.each do |name|
- ivar = "@#{name}"
+ def adv_attr_accessor(name, deprecation=nil)
+ ivar = "@#{name}"
+ deprecation ||= "Please pass :#{name} as hash key to mail() instead"
- class_eval <<-ACCESSORS, __FILE__, __LINE__ + 1
- def #{name}=(value)
- #{ivar} = value
- end
+ class_eval <<-ACCESSORS, __FILE__, __LINE__ + 1
+ def #{name}=(value)
+ ActiveSupport::Deprecation.warn "#{name}= is deprecated. #{deprecation}"
+ #{ivar} = value
+ end
- def #{name}(*args)
- raise ArgumentError, "expected 0 or 1 parameters" unless args.length <= 1
- if args.empty?
- #{ivar} if instance_variable_names.include?(#{ivar.inspect})
- else
- #{ivar} = args.first
- end
+ def #{name}(*args)
+ raise ArgumentError, "expected 0 or 1 parameters" unless args.length <= 1
+ if args.empty?
+ ActiveSupport::Deprecation.warn "#{name}() is deprecated and will be removed in future versions."
+ #{ivar} if instance_variable_names.include?(#{ivar.inspect})
+ else
+ ActiveSupport::Deprecation.warn "#{name}(value) is deprecated. #{deprecation}"
+ #{ivar} = args.first
end
- ACCESSORS
+ end
+ ACCESSORS
- self.protected_instance_variables << ivar if self.respond_to?(:protected_instance_variables)
- end
+ self.protected_instance_variables << ivar if self.respond_to?(:protected_instance_variables)
end
end
end
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index f742f982f2..16fcf112b7 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -187,31 +187,31 @@ module ActionMailer #:nodoc:
# with the filename +free_book.pdf+.
#
# = Inline Attachments
- #
- # You can also specify that a file should be displayed inline with other HTML. This is useful
+ #
+ # 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
+ # 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
@@ -222,7 +222,7 @@ module ActionMailer #:nodoc:
#
# An interceptor object must implement the <tt>:delivering_email(message)</tt> method which will be
# called before the email is sent, allowing you to make modifications to the email before it hits
- # the delivery agents. Your object should make and needed modifications directly to the passed
+ # the delivery agents. Your object should make any needed modifications directly to the passed
# in Mail::Message instance.
#
# = Default Hash
@@ -234,8 +234,8 @@ module ActionMailer #:nodoc:
# default :sender => 'system@example.com'
# end
#
- # You can pass in any header value that a <tt>Mail::Message</tt>, out of the box, <tt>ActionMailer::Base</tt>
- # sets the following:
+ # 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>
@@ -246,7 +246,7 @@ module ActionMailer #:nodoc:
# but Action Mailer translates them appropriately and sets the correct values.
#
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
- # an underscorised symbol, so the following will work:
+ # an underscored symbol, so the following will work:
#
# class Notifier < ActionMailer::Base
# default 'Content-Transfer-Encoding' => '7bit',
@@ -273,7 +273,7 @@ module ActionMailer #:nodoc:
# = Configuration options
#
# These options are specified on the class level, like
- # <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
+ # <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
#
# * <tt>default</tt> - You can pass this in at a class level as well as within the class itself as
# per the above section.
@@ -290,13 +290,15 @@ module ActionMailer #:nodoc:
# * <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>, <tt>:login</tt>, <tt>:cram_md5</tt>.
+ # 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>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
- # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@addres</tt>
+ # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@address</tt>
# added automatically before the message is sent.
#
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
@@ -341,10 +343,11 @@ module ActionMailer #:nodoc:
include AbstractController::Translation
include AbstractController::AssetPaths
- helper ActionMailer::MailHelper
+ cattr_reader :protected_instance_variables
+ @@protected_instance_variables = []
+ helper ActionMailer::MailHelper
include ActionMailer::OldApi
- include ActionMailer::DeprecatedApi
delegate :register_observer, :to => Mail
delegate :register_interceptor, :to => Mail
@@ -360,7 +363,6 @@ module ActionMailer #:nodoc:
}.freeze
class << self
-
def mailer_name
@mailer_name ||= name.underscore
end
@@ -402,14 +404,14 @@ module ActionMailer #:nodoc:
end
end
- def respond_to?(method, *args) #:nodoc:
+ def respond_to?(method, include_private = false) #:nodoc:
super || action_methods.include?(method.to_s)
end
protected
def set_payload_for_mail(payload, mail) #:nodoc:
- payload[:mailer] = self.name
+ payload[:mailer] = name
payload[:message_id] = mail.message_id
payload[:subject] = mail.subject
payload[:to] = mail.to
@@ -421,11 +423,8 @@ module ActionMailer #:nodoc:
end
def method_missing(method, *args) #:nodoc:
- if action_methods.include?(method.to_s)
- new(method, *args).message
- else
- super
- end
+ return super unless respond_to?(method)
+ new(method, *args).message
end
end
@@ -446,6 +445,10 @@ module ActionMailer #:nodoc:
super
end
+ def mailer_name
+ self.class.mailer_name
+ end
+
# Allows you to pass random and unusual headers to the new +Mail::Message+ object
# which will add them to itself.
#
@@ -690,15 +693,8 @@ module ActionMailer #:nodoc:
end
def each_template(paths, name, &block) #:nodoc:
- Array.wrap(paths).each do |path|
- templates = lookup_context.find_all(name, path)
- templates = templates.uniq_by { |t| t.formats }
-
- unless templates.empty?
- templates.each(&block)
- return
- end
- end
+ templates = lookup_context.find_all(name, Array.wrap(paths))
+ templates.uniq_by { |t| t.formats }.each(&block)
end
def create_parts_from_responses(m, responses) #:nodoc:
@@ -720,28 +716,6 @@ module ActionMailer #:nodoc:
container.add_part(part)
end
- module DeprecatedUrlOptions
- def default_url_options
- deprecated_url_options
- end
-
- def default_url_options=(val)
- deprecated_url_options
- end
-
- def deprecated_url_options
- raise "You can no longer call ActionMailer::Base.default_url_options " \
- "directly. You need to set config.action_mailer.default_url_options. " \
- "If you are using ActionMailer standalone, you need to include the " \
- "routing url_helpers directly."
- end
- end
-
- # This module will complain if the user tries to set default_url_options
- # directly instead of through the config object. In Action Mailer's Railtie,
- # we include the router's url_helpers, which will override this module.
- extend DeprecatedUrlOptions
-
ActiveSupport.run_load_hooks(:action_mailer, self)
end
end
diff --git a/actionmailer/lib/action_mailer/delivery_methods.rb b/actionmailer/lib/action_mailer/delivery_methods.rb
index 043794bb12..b324ba790d 100644
--- a/actionmailer/lib/action_mailer/delivery_methods.rb
+++ b/actionmailer/lib/action_mailer/delivery_methods.rb
@@ -46,11 +46,11 @@ module ActionMailer
# as alias and the default options supplied:
#
# Example:
- #
+ #
# 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)
diff --git a/actionmailer/lib/action_mailer/deprecated_api.rb b/actionmailer/lib/action_mailer/deprecated_api.rb
deleted file mode 100644
index 7d57feba04..0000000000
--- a/actionmailer/lib/action_mailer/deprecated_api.rb
+++ /dev/null
@@ -1,141 +0,0 @@
-require 'active_support/core_ext/object/try'
-
-module ActionMailer
- # This is the API which is deprecated and is going to be removed on Rails 3.1 release.
- # Part of the old API will be deprecated after 3.1, for a smoother deprecation process.
- # Check those in OldApi instead.
- module DeprecatedApi #:nodoc:
- extend ActiveSupport::Concern
-
- included do
- [:charset, :content_type, :mime_version, :implicit_parts_order].each do |method|
- class_eval <<-FILE, __FILE__, __LINE__ + 1
- def self.default_#{method}
- @@default_#{method}
- end
-
- def self.default_#{method}=(value)
- ActiveSupport::Deprecation.warn "ActionMailer::Base.default_#{method}=value is deprecated, " <<
- "use default :#{method} => value instead"
- @@default_#{method} = value
- end
-
- @@default_#{method} = nil
- FILE
- end
- end
-
- module ClassMethods
- # Deliver the given mail object directly. This can be used to deliver
- # a preconstructed mail object, like:
- #
- # email = MyMailer.create_some_mail(parameters)
- # email.set_some_obscure_header "frobnicate"
- # MyMailer.deliver(email)
- def deliver(mail, show_warning=true)
- if show_warning
- ActiveSupport::Deprecation.warn "#{self}.deliver is deprecated, call " <<
- "deliver in the mailer instance instead", caller[0,2]
- end
-
- raise "no mail object available for delivery!" unless mail
- wrap_delivery_behavior(mail)
- mail.deliver
- mail
- end
-
- def template_root
- self.view_paths && self.view_paths.first
- end
-
- def template_root=(root)
- ActiveSupport::Deprecation.warn "template_root= is deprecated, use prepend_view_path instead", caller[0,2]
- self.view_paths = ActionView::Base.process_view_paths(root)
- end
-
- def respond_to?(method_symbol, include_private = false)
- matches_dynamic_method?(method_symbol) || super
- end
-
- def method_missing(method_symbol, *parameters)
- if match = matches_dynamic_method?(method_symbol)
- case match[1]
- when 'create'
- ActiveSupport::Deprecation.warn "#{self}.create_#{match[2]} is deprecated, " <<
- "use #{self}.#{match[2]} instead", caller[0,2]
- new(match[2], *parameters).message
- when 'deliver'
- ActiveSupport::Deprecation.warn "#{self}.deliver_#{match[2]} is deprecated, " <<
- "use #{self}.#{match[2]}.deliver instead", caller[0,2]
- new(match[2], *parameters).message.deliver
- else super
- end
- else
- super
- end
- end
-
- private
-
- def matches_dynamic_method?(method_name)
- method_name = method_name.to_s
- /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
- end
- end
-
- # Delivers a Mail object. By default, it delivers the cached mail
- # object (from the <tt>create!</tt> method). If no cached mail object exists, and
- # no alternate has been given as the parameter, this will fail.
- def deliver!(mail = @_message)
- ActiveSupport::Deprecation.warn "Calling deliver in the AM::Base object is deprecated, " <<
- "please call deliver in the Mail instance", caller[0,2]
- self.class.deliver(mail, false)
- end
- alias :deliver :deliver!
-
- def render(*args)
- options = args.last.is_a?(Hash) ? args.last : {}
-
- if options[:body].is_a?(Hash)
- ActiveSupport::Deprecation.warn(':body in render deprecated. Please use instance ' <<
- 'variables as assigns instead', caller[0,1])
-
- options[:body].each { |k,v| instance_variable_set(:"@#{k}", v) }
- end
- super
- end
-
- # Render a message but does not set it as mail body. Useful for rendering
- # data for part and attachments.
- #
- # Examples:
- #
- # render_message "special_message"
- # render_message :template => "special_message"
- # render_message :inline => "<%= 'Hi!' %>"
- #
- def render_message(*args)
- ActiveSupport::Deprecation.warn "render_message is deprecated, use render instead", caller[0,2]
- render(*args)
- end
-
- private
-
- def initialize_defaults(*)
- @charset ||= self.class.default_charset.try(:dup)
- @content_type ||= self.class.default_content_type.try(:dup)
- @implicit_parts_order ||= self.class.default_implicit_parts_order.try(:dup)
- @mime_version ||= self.class.default_mime_version.try(:dup)
- super
- end
-
- def create_parts
- if @body.is_a?(Hash) && !@body.empty?
- ActiveSupport::Deprecation.warn "Giving a hash to body is deprecated, please use instance variables instead", caller[0,2]
- @body.each { |k, v| instance_variable_set(:"@#{k}", v) }
- end
- super
- end
-
- end
-end
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
index b708881edf..6f22adc479 100644
--- a/actionmailer/lib/action_mailer/mail_helper.rb
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -3,23 +3,14 @@ module ActionMailer
# Uses Text::Format to take the text and format it, indented two spaces for
# each line, and wrapped at 72 columns.
def block_format(text)
- begin
- require 'text/format'
- rescue LoadError => e
- $stderr.puts "You don't have text-format installed in your application. Please add it to your Gemfile and run bundle install"
- raise e
- end unless defined?(Text::Format)
-
formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
+ format_paragraph(paragraph)
}.join("\n")
-
+
# Make list points stand on their own line
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
+
formatted
end
@@ -37,5 +28,29 @@ module ActionMailer
def attachments
@_message.attachments
end
+
+ # Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
+ #
+ # === Examples
+ #
+ # 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.last + [word]).join(' ').length > len
+ sentences << [word]
+ else
+ sentences.last << word
+ end
+ end
+
+ sentences.map { |sentence|
+ "#{" " * indent}#{sentence.join(' ')}"
+ }.join "\n"
+ end
end
end
diff --git a/actionmailer/lib/action_mailer/old_api.rb b/actionmailer/lib/action_mailer/old_api.rb
index 79d024a350..04728cafb0 100644
--- a/actionmailer/lib/action_mailer/old_api.rb
+++ b/actionmailer/lib/action_mailer/old_api.rb
@@ -8,9 +8,7 @@ module ActionMailer
included do
extend ActionMailer::AdvAttrAccessor
-
- @@protected_instance_variables = %w(@parts)
- cattr_reader :protected_instance_variables
+ self.protected_instance_variables.concat %w(@parts @mail_was_called)
# Specify the BCC addresses for the message
adv_attr_accessor :bcc
@@ -42,11 +40,11 @@ module ActionMailer
# The recipient addresses for the message, either as a string (for a single
# address) or an array (for multiple addresses).
- adv_attr_accessor :recipients
+ adv_attr_accessor :recipients, "Please pass :to as hash key to mail() instead"
# The date on which the message was sent. If not set (the default), the
# header will be set by the delivery agent.
- adv_attr_accessor :sent_on
+ adv_attr_accessor :sent_on, "Please pass :date as hash key to mail() instead"
# Specify the subject of the message.
adv_attr_accessor :subject
@@ -54,20 +52,12 @@ module ActionMailer
# Specify the template name to use for current message. This is the "base"
# template name, without the extension or directory, and may be used to
# have multiple mailer methods share the same template.
- adv_attr_accessor :template
-
- # Override the mailer name, which defaults to an inflected version of the
- # mailer's class name. If you want to use a template in a non-standard
- # location, you can use this to specify that location.
- adv_attr_accessor :mailer_name
+ adv_attr_accessor :template, "Please pass :template_name or :template_path as hash key to mail() instead"
# Define the body of the message. This is either a Hash (in which case it
# specifies the variables to pass to the template when it is rendered),
# or a string, in which case it specifies the actual text of the message.
adv_attr_accessor :body
-
- # Alias controller_path to mailer_name so render :partial in views work.
- alias :controller_path :mailer_name
end
def process(method_name, *args)
@@ -84,6 +74,8 @@ module ActionMailer
# part itself is yielded to the block so that other properties (charset,
# body, headers, etc.) can be set on it.
def part(params)
+ ActiveSupport::Deprecation.warn "part() is deprecated and will be removed in future versions. " <<
+ "Please pass a block to mail() instead."
params = {:content_type => params} if String === params
if custom_headers = params.delete(:headers)
@@ -99,6 +91,8 @@ module ActionMailer
# Add an attachment to a multipart message. This is simply a part with the
# content-disposition set to "attachment".
def attachment(params, &block)
+ ActiveSupport::Deprecation.warn "attachment() is deprecated and will be removed in future versions. " <<
+ "Please use the attachments[] API instead."
params = { :content_type => params } if String === params
params[:content] ||= params.delete(:data) || params.delete(:body)
@@ -116,43 +110,43 @@ module ActionMailer
def normalize_nonfile_hash(params)
content_disposition = "attachment;"
-
+
mime_type = params.delete(:mime_type)
-
+
if content_type = params.delete(:content_type)
content_type = "#{mime_type || content_type};"
end
params[:body] = params.delete(:data) if params[:data]
-
+
{ :content_type => content_type,
:content_disposition => content_disposition }.merge(params)
end
-
+
def normalize_file_hash(params)
filename = File.basename(params.delete(:filename))
content_disposition = "attachment; filename=\"#{File.basename(filename)}\""
-
+
mime_type = params.delete(:mime_type)
-
+
if (content_type = params.delete(:content_type)) && (content_type !~ /filename=/)
content_type = "#{mime_type || content_type}; filename=\"#{filename}\""
end
-
+
params[:body] = params.delete(:data) if params[:data]
-
+
{ :content_type => content_type,
:content_disposition => content_disposition }.merge(params)
end
- def create_mail
+ def create_mail
m = @_message
- set_fields!({:subject => subject, :to => recipients, :from => from,
- :bcc => bcc, :cc => cc, :reply_to => reply_to}, charset)
+ set_fields!({:subject => @subject, :to => @recipients, :from => @from,
+ :bcc => @bcc, :cc => @cc, :reply_to => @reply_to}, @charset)
- m.mime_version = mime_version unless mime_version.nil?
- m.date = sent_on.to_time rescue sent_on if sent_on
+ m.mime_version = @mime_version if @mime_version
+ m.date = @sent_on.to_time rescue @sent_on if @sent_on
@headers.each { |k, v| m[k] = v }
@@ -178,19 +172,21 @@ module ActionMailer
wrap_delivery_behavior!
m.content_transfer_encoding = '8bit' unless m.body.only_us_ascii?
-
+
@_message
end
-
+
# Set up the default values for the various instance variables of this
# mailer. Subclasses may override this method to provide different
# defaults.
- def initialize_defaults(method_name)
+ def initialize_defaults(method_name)
@charset ||= self.class.default[:charset].try(:dup)
@content_type ||= self.class.default[:content_type].try(:dup)
@implicit_parts_order ||= self.class.default[:parts_order].try(:dup)
@mime_version ||= self.class.default[:mime_version].try(:dup)
+ @cc, @bcc, @reply_to, @subject, @from, @recipients = nil, nil, nil, nil, nil, nil
+
@mailer_name ||= self.class.mailer_name.dup
@template ||= method_name
@mail_was_called = false
@@ -201,11 +197,11 @@ module ActionMailer
@body ||= {}
end
- def create_parts
+ def create_parts
if String === @body
@parts.unshift create_inline_part(@body)
elsif @parts.empty? || @parts.all? { |p| p.content_disposition =~ /^attachment/ }
- lookup_context.find_all(@template, @mailer_name).each do |template|
+ lookup_context.find_all(@template, [@mailer_name]).each do |template|
self.formats = template.formats
@parts << create_inline_part(render(:template => template), template.mime_type)
end
@@ -216,11 +212,11 @@ module ActionMailer
# If this is a multipart e-mail add the mime_version if it is not
# already set.
- @mime_version ||= "1.0" if !@parts.empty?
+ @mime_version ||= "1.0" unless @parts.empty?
end
end
- def create_inline_part(body, mime_type=nil)
+ def create_inline_part(body, mime_type=nil)
ct = mime_type || "text/plain"
main_type, sub_type = split_content_type(ct.to_s)
@@ -242,17 +238,17 @@ module ActionMailer
m.reply_to ||= headers.delete(:reply_to) if headers[:reply_to]
end
- def split_content_type(ct)
+ def split_content_type(ct)
ct.to_s.split("/")
end
- def parse_content_type(defaults=nil)
+ def parse_content_type
if @content_type.blank?
[ nil, {} ]
else
ctype, *attrs = @content_type.split(/;\s*/)
- attrs = attrs.inject({}) { |h,s| k,v = s.split(/\=/, 2); h[k] = v; h }
- [ctype, {"charset" => @charset}.merge(attrs)]
+ attrs = Hash[attrs.map { |attr| attr.split(/=/, 2) }]
+ [ctype, {"charset" => @charset}.merge!(attrs)]
end
end
end
diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb
index ce6d8cc5b5..4ec478067f 100644
--- a/actionmailer/lib/action_mailer/railtie.rb
+++ b/actionmailer/lib/action_mailer/railtie.rb
@@ -1,5 +1,6 @@
require "action_mailer"
require "rails"
+require "abstract_controller/railties/routes_helpers"
module ActionMailer
class Railtie < Rails::Railtie
@@ -13,14 +14,26 @@ module ActionMailer
paths = app.config.paths
options = app.config.action_mailer
- options.assets_dir ||= paths.public.to_a.first
- options.javascripts_dir ||= paths.public.javascripts.to_a.first
- options.stylesheets_dir ||= paths.public.stylesheets.to_a.first
+ 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_path ||= app.config.asset_path
+ options.asset_host ||= app.config.asset_host
ActiveSupport.on_load(:action_mailer) do
- include app.routes.url_helpers
+ include AbstractController::UrlFor
+ extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
+ include app.routes.mounted_helpers
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 \ No newline at end of file
+end
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb
index f4d1bb59f1..63e18147f6 100644
--- a/actionmailer/lib/action_mailer/test_case.rb
+++ b/actionmailer/lib/action_mailer/test_case.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/class/attribute'
+
module ActionMailer
class NonInferrableMailerError < ::StandardError
def initialize(name)
@@ -15,11 +17,11 @@ module ActionMailer
module ClassMethods
def tests(mailer)
- write_inheritable_attribute(:mailer_class, mailer)
+ self._mailer_class = mailer
end
def mailer_class
- if mailer = read_inheritable_attribute(:mailer_class)
+ if mailer = self._mailer_class
mailer
else
tests determine_default_mailer(name)
@@ -65,6 +67,7 @@ module ActionMailer
end
included do
+ class_attribute :_mailer_class
setup :initialize_test_deliveries
setup :set_expected_mail
end
diff --git a/actionmailer/lib/action_mailer/tmail_compat.rb b/actionmailer/lib/action_mailer/tmail_compat.rb
index 26962f972f..1b2cdcfb27 100644
--- a/actionmailer/lib/action_mailer/tmail_compat.rb
+++ b/actionmailer/lib/action_mailer/tmail_compat.rb
@@ -1,17 +1,19 @@
module Mail
class Message
-
+
def set_content_type(*args)
- ActiveSupport::Deprecation.warn('Message#set_content_type is deprecated, please just call ' <<
- 'Message#content_type with the same arguments', caller[0,2])
+ message = 'Message#set_content_type is deprecated, please just call ' <<
+ 'Message#content_type with the same arguments'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
content_type(*args)
end
-
+
alias :old_transfer_encoding :transfer_encoding
def transfer_encoding(value = nil)
if value
- ActiveSupport::Deprecation.warn('Message#transfer_encoding is deprecated, please call ' <<
- 'Message#content_transfer_encoding with the same arguments', caller[0,2])
+ message = 'Message#transfer_encoding is deprecated, ' <<
+ 'please call Message#content_transfer_encoding with the same arguments'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
content_transfer_encoding(value)
else
old_transfer_encoding
@@ -19,16 +21,17 @@ module Mail
end
def transfer_encoding=(value)
- ActiveSupport::Deprecation.warn('Message#transfer_encoding= is deprecated, please call ' <<
- 'Message#content_transfer_encoding= with the same arguments', caller[0,2])
+ message = 'Message#transfer_encoding= is deprecated, ' <<
+ 'please call Message#content_transfer_encoding= with the same arguments'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
self.content_transfer_encoding = value
end
def original_filename
- ActiveSupport::Deprecation.warn('Message#original_filename is deprecated, ' <<
- 'please call Message#filename', caller[0,2])
+ message = 'Message#original_filename is deprecated, please call Message#filename'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
filename
end
-
+
end
-end \ No newline at end of file
+end
diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb
index 805c89be1d..27eb6c2b9b 100644
--- a/actionmailer/lib/action_mailer/version.rb
+++ b/actionmailer/lib/action_mailer/version.rb
@@ -1,10 +1,10 @@
module ActionMailer
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/actionmailer/lib/rails/generators/mailer/USAGE b/actionmailer/lib/rails/generators/mailer/USAGE
index a08d459739..448ddbd5df 100644
--- a/actionmailer/lib/rails/generators/mailer/USAGE
+++ b/actionmailer/lib/rails/generators/mailer/USAGE
@@ -1,4 +1,5 @@
Description:
+============
Stubs out a new mailer and its views. Pass the mailer name, either
CamelCased or under_scored, and an optional list of emails as arguments.
@@ -6,10 +7,12 @@ Description:
engine and test framework generators.
Example:
- `rails generate mailer Notifications signup forgot_password invoice`
+========
+ rails generate mailer Notifications signup forgot_password invoice
creates a Notifications mailer class, views, test, and fixtures:
Mailer: app/mailers/notifications.rb
Views: app/views/notifications/signup.erb [...]
Test: test/functional/notifications_test.rb
Fixtures: test/fixtures/notifications/signup [...]
+
diff --git a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
index 21e5918ecb..370a508cad 100644
--- a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
+++ b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
@@ -1,3 +1,4 @@
+<% module_namespacing do -%>
class <%= class_name %> < ActionMailer::Base
default :from => "from@example.com"
<% for action in actions -%>
@@ -5,7 +6,7 @@ class <%= class_name %> < ActionMailer::Base
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
- # en.<%= file_name %>.<%= action %>.subject
+ # en.<%= file_path.gsub("/",".") %>.<%= action %>.subject
#
def <%= action %>
@greeting = "Hi"
@@ -14,3 +15,4 @@ class <%= class_name %> < ActionMailer::Base
end
<% end -%>
end
+<% end -%>
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
index ea15709b45..ce664bf301 100644
--- a/actionmailer/test/abstract_unit.rb
+++ b/actionmailer/test/abstract_unit.rb
@@ -11,11 +11,20 @@ ensure
$VERBOSE = old
end
-
require 'active_support/core_ext/kernel/reporting'
+
+require 'active_support/core_ext/string/encoding'
+if "ruby".encoding_aware?
+ # 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
+end
+
silence_warnings do
# These external dependencies have warnings :/
- require 'text/format'
require 'mail'
end
@@ -67,4 +76,6 @@ end
def restore_delivery_method
ActionMailer::Base.delivery_method = @old_delivery_method
-end \ No newline at end of file
+end
+
+ActiveSupport::Deprecation.silenced = true
diff --git a/actionmailer/test/old_base/asset_host_test.rb b/actionmailer/test/asset_host_test.rb
index cc13c8a4d7..b24eca5fbb 100644
--- a/actionmailer/test/old_base/asset_host_test.rb
+++ b/actionmailer/test/asset_host_test.rb
@@ -3,9 +3,9 @@ require 'action_controller'
class AssetHostMailer < ActionMailer::Base
def email_with_asset
- recipients 'test@localhost'
- subject "testing email containing asset path while asset_host is set"
- from "tester@example.com"
+ mail :to => 'test@localhost',
+ :subject => 'testing email containing asset path while asset_host is set',
+ :from => 'tester@example.com'
end
end
@@ -29,7 +29,7 @@ class AssetHostTest < Test::Unit::TestCase
assert_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip
end
- def test_asset_host_as_one_arguement_proc
+ def test_asset_host_as_one_argument_proc
AssetHostMailer.config.asset_host = Proc.new { |source|
if source.starts_with?('/images')
"http://images.example.com"
@@ -41,7 +41,7 @@ class AssetHostTest < Test::Unit::TestCase
assert_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip
end
- def test_asset_host_as_two_arguement_proc
+ def test_asset_host_as_two_argument_proc
ActionController::Base.config.asset_host = Proc.new {|source,request|
if request && request.ssl?
"https://www.example.com"
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
index fec0ecf477..6a7931da8c 100644
--- a/actionmailer/test/base_test.rb
+++ b/actionmailer/test/base_test.rb
@@ -7,9 +7,6 @@ require 'mailers/proc_mailer'
require 'mailers/asset_mailer'
class BaseTest < ActiveSupport::TestCase
- # TODO Add some tests for implicity layout render and url helpers
- # so we can get rid of old base tests altogether with old base.
-
def teardown
ActionMailer::Base.asset_host = nil
ActionMailer::Base.assets_dir = nil
@@ -35,21 +32,21 @@ class BaseTest < ActiveSupport::TestCase
end
test "mail() with bcc, cc, content_type, charset, mime_version, reply_to and date" do
- @time = Time.now.beginning_of_day.to_datetime
+ time = Time.now.beginning_of_day.to_datetime
email = BaseMailer.welcome(:bcc => 'bcc@test.lindsaar.net',
:cc => 'cc@test.lindsaar.net',
:content_type => 'multipart/mixed',
:charset => 'iso-8559-1',
:mime_version => '2.0',
:reply_to => 'reply-to@test.lindsaar.net',
- :date => @time)
+ :date => time)
assert_equal(['bcc@test.lindsaar.net'], email.bcc)
assert_equal(['cc@test.lindsaar.net'], email.cc)
assert_equal('multipart/mixed; charset=iso-8559-1', email.content_type)
assert_equal('iso-8559-1', email.charset)
assert_equal('2.0', email.mime_version)
assert_equal(['reply-to@test.lindsaar.net'], email.reply_to)
- assert_equal(@time, email.date)
+ assert_equal(time, email.date)
end
test "mail() renders the template using the method being processed" do
@@ -148,7 +145,7 @@ class BaseTest < ActiveSupport::TestCase
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
@@ -156,8 +153,8 @@ class BaseTest < ActiveSupport::TestCase
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("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
@@ -209,6 +206,12 @@ class BaseTest < ActiveSupport::TestCase
assert_equal "New Subject!", 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
@@ -413,7 +416,7 @@ class BaseTest < ActiveSupport::TestCase
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
@@ -447,7 +450,7 @@ class BaseTest < ActiveSupport::TestCase
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/"
@@ -456,7 +459,7 @@ class BaseTest < ActiveSupport::TestCase
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
ActionMailer::Base.config.asset_host = "global.com"
ActionMailer::Base.config.assets_dir = "global/"
@@ -469,12 +472,12 @@ class BaseTest < ActiveSupport::TestCase
end
# Before and After hooks
-
+
class MyObserver
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
@@ -493,7 +496,7 @@ class BaseTest < ActiveSupport::TestCase
MyInterceptor.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
yesterday = 1.day.ago
@@ -501,7 +504,7 @@ class BaseTest < ActiveSupport::TestCase
mail2 = ProcMailer.welcome
assert(mail1['X-Proc-Method'].to_s.to_i > mail2['X-Proc-Method'].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)
diff --git a/actionmailer/test/delivery_methods_test.rb b/actionmailer/test/delivery_methods_test.rb
index 22a7d19bc2..08f84dbf3b 100644
--- a/actionmailer/test/delivery_methods_test.rb
+++ b/actionmailer/test/delivery_methods_test.rb
@@ -128,7 +128,7 @@ class MailDeliveryTest < ActiveSupport::TestCase
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
@@ -160,7 +160,7 @@ class MailDeliveryTest < ActiveSupport::TestCase
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
@@ -168,5 +168,5 @@ class MailDeliveryTest < ActiveSupport::TestCase
DeliveryMailer.welcome.deliver
assert_equal(0, DeliveryMailer.deliveries.length)
end
-
+
end
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 0000000000..30466dd005
--- /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/i18n_test_mailer/mail_with_i18n_subject.erb b/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb
new file mode 100644
index 0000000000..f5340283f1
--- /dev/null
+++ b/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb
@@ -0,0 +1,4 @@
+Hello there,
+
+Mr. <%= @recipient %>. Be greeted, new member!
+
diff --git a/actionmailer/test/fixtures/raw_email10 b/actionmailer/test/fixtures/raw_email10
index b1fc2b2617..edad5ccff1 100644
--- a/actionmailer/test/fixtures/raw_email10
+++ b/actionmailer/test/fixtures/raw_email10
@@ -15,6 +15,6 @@ Content-Type: text/plain; charset=X-UNKNOWN
Test test. Hi. Waving. m
----------------------------------------------------------------
-Sent via Bell Mobility's Text Messaging service.
+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_email2 b/actionmailer/test/fixtures/raw_email2
index 3999fcc877..9f87bb2a98 100644
--- a/actionmailer/test/fixtures/raw_email2
+++ b/actionmailer/test/fixtures/raw_email2
@@ -32,7 +32,7 @@ To: xxxxx xxxx <xxxxx@xxxxxxxxx.com>
Subject: Fwd: Signed email causes file attachments
In-Reply-To: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@mac.com>
Mime-Version: 1.0
-Content-Type: multipart/mixed;
+Content-Type: multipart/mixed;
boundary="----=_Part_5028_7368284.1115579351471"
References: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@mac.com>
diff --git a/actionmailer/test/fixtures/raw_email3 b/actionmailer/test/fixtures/raw_email3
index 771a96350d..3a0927490a 100644
--- a/actionmailer/test/fixtures/raw_email3
+++ b/actionmailer/test/fixtures/raw_email3
@@ -31,7 +31,7 @@ Reply-To: Test Tester <xxxx@xxxx.com>
To: xxxx@xxxx.com, xxxx@xxxx.com
Subject: Another PDF
Mime-Version: 1.0
-Content-Type: multipart/mixed;
+Content-Type: multipart/mixed;
boundary="----=_Part_2192_32400445.1115745999735"
X-Virus-Scanned: amavisd-new at textdrive.com
diff --git a/actionmailer/test/fixtures/raw_email5 b/actionmailer/test/fixtures/raw_email5
index 151c631471..bbe31bcdc5 100644
--- a/actionmailer/test/fixtures/raw_email5
+++ b/actionmailer/test/fixtures/raw_email5
@@ -14,6 +14,6 @@ Importance: normal
Test test. Hi. Waving. m
----------------------------------------------------------------
-Sent via Bell Mobility's Text Messaging service.
+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
index 93289c4f92..8e37bd7392 100644
--- a/actionmailer/test/fixtures/raw_email6
+++ b/actionmailer/test/fixtures/raw_email6
@@ -15,6 +15,6 @@ Content-Type: text/plain; charset=us-ascii
Test test. Hi. Waving. m
----------------------------------------------------------------
-Sent via Bell Mobility's Text Messaging service.
+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_email8 b/actionmailer/test/fixtures/raw_email8
index 2382dfdf34..79996365b3 100644
--- a/actionmailer/test/fixtures/raw_email8
+++ b/actionmailer/test/fixtures/raw_email8
@@ -8,7 +8,7 @@ To: xxxxx xxxx <xxxxx@xxxxxxxxx.com>
Subject: Fwd: Signed email causes file attachments
In-Reply-To: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@mac.com>
Mime-Version: 1.0
-Content-Type: multipart/mixed;
+Content-Type: multipart/mixed;
boundary="----=_Part_5028_7368284.1115579351471"
References: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@mac.com>
diff --git a/actionmailer/test/fixtures/raw_email9 b/actionmailer/test/fixtures/raw_email9
index 8b9b1eaa04..02ea0b05c5 100644
--- a/actionmailer/test/fixtures/raw_email9
+++ b/actionmailer/test/fixtures/raw_email9
@@ -10,19 +10,19 @@ Date: Wed, 23 Feb 2005 18:20:17 -0400
From: "xxx xxx" <xxx@xxx.xxx>
Message-ID: <4D6AA7EB.6490534@xxx.xxx>
To: xxx@xxx.com
-Subject: Stop adware/spyware once and for all.
+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:
+You are infected with:
Ad Ware and Spy Ware
-Get your free scan and removal download now,
-before it gets any worse.
+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)
+no more? (you will still be infected)
http://xxx.xxx.info/discon/?xxx@xxx.com
diff --git a/actionmailer/test/fixtures/templates/signed_up.erb b/actionmailer/test/fixtures/templates/signed_up.erb
index a85d5fa442..7afe1f651c 100644
--- a/actionmailer/test/fixtures/templates/signed_up.erb
+++ b/actionmailer/test/fixtures/templates/signed_up.erb
@@ -1,3 +1,3 @@
-Hello there,
+Hello there,
Mr. <%= @recipient %> \ 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
index 847d065c37..8dcf9746cc 100644
--- a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml
+++ b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml
@@ -1,6 +1,6 @@
-%p Hello there,
+%p Hello there,
-%p
+%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
index 847d065c37..8dcf9746cc 100644
--- a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml
+++ b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml
@@ -1,6 +1,6 @@
-%p Hello there,
+%p Hello there,
-%p
+%p
Mr.
= @recipient
from haml \ 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
index a85d5fa442..7afe1f651c 100644
--- a/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
+++ b/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
@@ -1,3 +1,3 @@
-Hello there,
+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
index 4c5806d30d..6e7875cff5 100644
--- a/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb
+++ b/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb
@@ -1,4 +1,4 @@
-Hello there,
+Hello there,
Mr. <%= @recipient %>. Please see our greeting at <%= @welcome_url %> <%= welcome_url %>
diff --git a/actionmailer/test/i18n_with_controller_test.rb b/actionmailer/test/i18n_with_controller_test.rb
new file mode 100644
index 0000000000..7040ae6f8d
--- /dev/null
+++ b/actionmailer/test/i18n_with_controller_test.rb
@@ -0,0 +1,46 @@
+require 'abstract_unit'
+require 'action_controller'
+
+class I18nTestMailer < ActionMailer::Base
+ configure do |c|
+ c.assets_dir = ''
+ end
+
+ def mail_with_i18n_subject(recipient)
+ @recipient = recipient
+ I18n.locale = :de
+ mail(:to => recipient, :subject => "#{I18n.t :email_subject} #{recipient}",
+ :from => "system@loudthinking.com", :date => Time.local(2004, 12, 12))
+ end
+end
+
+class TestController < ActionController::Base
+ def send_mail
+ I18nTestMailer.mail_with_i18n_subject("test@localhost").deliver
+ render :text => 'Mail sent'
+ end
+end
+
+class ActionMailerI18nWithControllerTest < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new
+ Routes.draw do
+ match ':controller(/:action(/:id))'
+ end
+
+ def app
+ Routes
+ end
+
+ def setup
+ I18n.backend.store_translations('de', :email_subject => '[Signed up] Welcome')
+ end
+
+ def teardown
+ I18n.locale = :en
+ end
+
+ def test_send_mail
+ get '/test/send_mail'
+ assert_equal "Mail sent", @response.body
+ end
+end
diff --git a/actionmailer/test/mail_helper_test.rb b/actionmailer/test/mail_helper_test.rb
index 7cc0804323..17e9c82045 100644
--- a/actionmailer/test/mail_helper_test.rb
+++ b/actionmailer/test/mail_helper_test.rb
@@ -14,6 +14,14 @@ class HelperMailer < ActionMailer::Base
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_mailer
mail_with_defaults do |format|
format.html { render(:inline => "<%= mailer.message.subject %>") }
@@ -50,5 +58,10 @@ class MailerHelperTest < ActionMailer::TestCase
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
end
diff --git a/actionmailer/test/old_base/mail_layout_test.rb b/actionmailer/test/mail_layout_test.rb
index 2c2daa0f28..def8da81b8 100644
--- a/actionmailer/test/old_base/mail_layout_test.rb
+++ b/actionmailer/test/mail_layout_test.rb
@@ -1,53 +1,45 @@
require 'abstract_unit'
class AutoLayoutMailer < ActionMailer::Base
+ default :to => 'test@localhost',
+ :subject => "You have a mail",
+ :from => "tester@example.com"
def hello
- recipients 'test@localhost'
- subject "You have a mail"
- from "tester@example.com"
+ mail()
end
def spam
- recipients 'test@localhost'
- subject "You have a mail"
- from "tester@example.com"
-
@world = "Earth"
- body render(:inline => "Hello, <%= @world %>", :layout => 'spam')
+ mail(:body => render(:inline => "Hello, <%= @world %>", :layout => 'spam'))
end
def nolayout
- recipients 'test@localhost'
- subject "You have a mail"
- from "tester@example.com"
-
@world = "Earth"
- body render(:inline => "Hello, <%= @world %>", :layout => false)
+ mail(:body => render(:inline => "Hello, <%= @world %>", :layout => false))
end
def multipart(type = nil)
- recipients 'test@localhost'
- subject "You have a mail"
- from "tester@example.com"
-
- content_type(type) if type
+ 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@localhost',
+ :subject => "You have a mail",
+ :from => "tester@example.com"
+
def signup
- recipients 'test@localhost'
- subject "You have a mail"
- from "tester@example.com"
+ mail()
end
def logout
- recipients 'test@localhost'
- subject "You have a mail"
- from "tester@example.com"
+ mail()
end
end
@@ -91,19 +83,6 @@ class LayoutMailerTest < Test::Unit::TestCase
assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s
end
- def test_should_fix_multipart_layout
- mail = AutoLayoutMailer.multipart("text/plain")
- 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_layout_given_to_render
mail = AutoLayoutMailer.spam
assert_equal "Spammer layout Hello, Earth", mail.body.to_s.strip
diff --git a/actionmailer/test/mailers/base_mailer.rb b/actionmailer/test/mailers/base_mailer.rb
index 2c6de36ccf..9416bc718e 100644
--- a/actionmailer/test/mailers/base_mailer.rb
+++ b/actionmailer/test/mailers/base_mailer.rb
@@ -111,4 +111,8 @@ class BaseMailer < ActionMailer::Base
format.html { render :layout => layout_name }
end
end
+
+ def email_with_translations
+ mail :body => render("email_with_translations.html")
+ end
end
diff --git a/actionmailer/test/mailers/proc_mailer.rb b/actionmailer/test/mailers/proc_mailer.rb
index 6a79cd71fc..43916e1421 100644
--- a/actionmailer/test/mailers/proc_mailer.rb
+++ b/actionmailer/test/mailers/proc_mailer.rb
@@ -6,11 +6,11 @@ class ProcMailer < ActionMailer::Base
def welcome
mail
end
-
+
private
-
+
def give_a_greeting
"Thanks for signing up this afternoon"
end
-
+
end
diff --git a/actionmailer/test/old_base/adv_attr_test.rb b/actionmailer/test/old_base/adv_attr_test.rb
index f22d733bc5..c5a6b6d88b 100644
--- a/actionmailer/test/old_base/adv_attr_test.rb
+++ b/actionmailer/test/old_base/adv_attr_test.rb
@@ -11,9 +11,14 @@ class AdvAttrTest < ActiveSupport::TestCase
end
def setup
+ ActiveSupport::Deprecation.silenced = true
@person = Person.new
end
+ def teardown
+ ActiveSupport::Deprecation.silenced = false
+ end
+
def test_adv_attr
assert_nil @person.name
@person.name 'Bob'
diff --git a/actionmailer/test/old_base/mail_render_test.rb b/actionmailer/test/old_base/mail_render_test.rb
index 08951833a5..3a1d3184f4 100644
--- a/actionmailer/test/old_base/mail_render_test.rb
+++ b/actionmailer/test/old_base/mail_render_test.rb
@@ -19,18 +19,6 @@ class RenderMailer < ActionMailer::Base
body render(:file => "templates/signed_up")
end
- def rxml_template
- recipients 'test@localhost'
- subject "rendering rxml template"
- from "tester@example.com"
- end
-
- def included_subtemplate
- recipients 'test@localhost'
- subject "Including another template in the one being rendered"
- from "tester@example.com"
- end
-
def no_instance_variable
recipients 'test@localhost'
subject "No Instance Variable"
@@ -41,11 +29,6 @@ class RenderMailer < ActionMailer::Base
end
end
- def initialize_defaults(method_name)
- super
- mailer_name "test_mailer"
- end
-
def multipart_alternative
recipients 'test@localhost'
subject 'multipart/alternative'
@@ -97,11 +80,13 @@ class RenderHelperTest < Test::Unit::TestCase
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries.clear
+ ActiveSupport::Deprecation.silenced = true
@recipient = 'test@localhost'
end
def teardown
+ ActiveSupport::Deprecation.silenced = false
restore_delivery_method
end
@@ -112,38 +97,19 @@ class RenderHelperTest < Test::Unit::TestCase
def test_file_template
mail = RenderMailer.file_template
- assert_equal "Hello there, \n\nMr. test@localhost", mail.body.to_s.strip
- end
-
- def test_rxml_template
- mail = RenderMailer.rxml_template.deliver
- assert_equal %(<?xml version="1.0" encoding="UTF-8"?>\n<test/>), mail.body.to_s.strip
- end
-
- def test_included_subtemplate
- mail = RenderMailer.included_subtemplate.deliver
- assert_equal "Hey Ho, let's go!", mail.body.to_s.strip
+ assert_equal "Hello there,\n\nMr. test@localhost", mail.body.to_s.strip
end
def test_no_instance_variable
mail = RenderMailer.no_instance_variable.deliver
assert_equal "Look, subject.nil? is true!", mail.body.to_s.strip
end
-
- def test_legacy_multipart_alternative
- mail = RenderMailer.multipart_alternative.deliver
- assert_equal(2, mail.parts.size)
- assert_equal("multipart/alternative", mail.mime_type)
- assert_equal("text/plain", mail.parts[0].mime_type)
- assert_equal("foo: bar", mail.parts[0].body.encoded)
- assert_equal("text/html", mail.parts[1].mime_type)
- assert_equal("<strong>foo</strong> bar", mail.parts[1].body.encoded)
- end
end
class FirstSecondHelperTest < Test::Unit::TestCase
def setup
set_delivery_method :test
+ ActiveSupport::Deprecation.silenced = true
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries.clear
@@ -151,6 +117,7 @@ class FirstSecondHelperTest < Test::Unit::TestCase
end
def teardown
+ ActiveSupport::Deprecation.silenced = false
restore_delivery_method
end
diff --git a/actionmailer/test/old_base/mail_service_test.rb b/actionmailer/test/old_base/mail_service_test.rb
index 831adf3e32..0b5b0b2da3 100644
--- a/actionmailer/test/old_base/mail_service_test.rb
+++ b/actionmailer/test/old_base/mail_service_test.rb
@@ -106,7 +106,7 @@ class TestMailer < ActionMailer::Base
cc "Foo áëô îü <extended@example.net>"
bcc "Foo áëô îü <extended@example.net>"
charset "UTF-8"
-
+
body "åœö blah"
end
@@ -328,21 +328,20 @@ class ActionMailerTest < Test::Unit::TestCase
mail
end
- # Replacing logger work around for mocha bug. Should be fixed in mocha 0.3.3
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.deliveries.clear
+ ActiveSupport::Deprecation.silenced = true
- @original_logger = TestMailer.logger
@recipient = 'test@localhost'
TestMailer.delivery_method = :test
end
def teardown
- TestMailer.logger = @original_logger
+ ActiveSupport::Deprecation.silenced = false
restore_delivery_method
end
@@ -359,7 +358,7 @@ class ActionMailerTest < Test::Unit::TestCase
assert_equal "text/plain", created.parts[0].parts[0].mime_type
assert_equal "text/html", created.parts[0].parts[1].mime_type
assert_equal "application/octet-stream", created.parts[1].mime_type
-
+
end
def test_nested_parts_with_body
@@ -392,14 +391,14 @@ class ActionMailerTest < Test::Unit::TestCase
expected = new_mail
expected.to = @recipient
expected.subject = "[Signed up] Welcome #{@recipient}"
- expected.body = "Hello there, \n\nMr. #{@recipient}"
+ expected.body = "Hello there,\n\nMr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.now
created = nil
assert_nothing_raised { created = TestMailer.signed_up(@recipient) }
assert_not_nil created
-
+
expected.message_id = '<123@456>'
created.message_id = '<123@456>'
@@ -420,7 +419,7 @@ class ActionMailerTest < Test::Unit::TestCase
expected = new_mail
expected.to = @recipient
expected.subject = "[Signed up] Welcome #{@recipient}"
- expected.body = "Hello there, \n\nMr. #{@recipient}"
+ expected.body = "Hello there,\n\nMr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
@@ -503,7 +502,7 @@ class ActionMailerTest < Test::Unit::TestCase
delivered = ActionMailer::Base.deliveries.first
expected.message_id = '<123@456>'
delivered.message_id = '<123@456>'
-
+
assert_equal expected.encoded, delivered.encoded
end
@@ -546,10 +545,10 @@ class ActionMailerTest < Test::Unit::TestCase
created = TestMailer.different_reply_to @recipient
end
assert_not_nil created
-
+
expected.message_id = '<123@456>'
created.message_id = '<123@456>'
-
+
assert_equal expected.encoded, created.encoded
assert_nothing_raised do
@@ -558,10 +557,10 @@ class ActionMailerTest < Test::Unit::TestCase
delivered = ActionMailer::Base.deliveries.first
assert_not_nil delivered
-
+
expected.message_id = '<123@456>'
delivered.message_id = '<123@456>'
-
+
assert_equal expected.encoded, delivered.encoded
end
@@ -581,7 +580,7 @@ class ActionMailerTest < Test::Unit::TestCase
created = TestMailer.iso_charset @recipient
end
assert_not_nil created
-
+
expected.message_id = '<123@456>'
created.message_id = '<123@456>'
@@ -596,7 +595,7 @@ class ActionMailerTest < Test::Unit::TestCase
expected.message_id = '<123@456>'
delivered.message_id = '<123@456>'
-
+
assert_equal expected.encoded, delivered.encoded
end
@@ -631,7 +630,7 @@ class ActionMailerTest < Test::Unit::TestCase
expected.message_id = '<123@456>'
delivered.message_id = '<123@456>'
-
+
assert_equal expected.encoded, delivered.encoded
end
@@ -761,10 +760,10 @@ EOF
delivered = ActionMailer::Base.deliveries.first
assert_not_nil delivered
-
+
expected.message_id = '<123@456>'
delivered.message_id = '<123@456>'
-
+
assert_equal expected.encoded, delivered.encoded
end
@@ -887,7 +886,7 @@ EOF
assert_equal "iso-8859-1", mail.parts[1].charset
assert_equal "image/jpeg", mail.parts[2].mime_type
-
+
assert_equal "attachment", mail.parts[2][:content_disposition].disposition_type
assert_equal "foo.jpg", mail.parts[2][:content_disposition].filename
assert_equal "foo.jpg", mail.parts[2][:content_type].filename
@@ -1005,7 +1004,7 @@ EOF
attachment = mail.attachments.last
expected = "01 Quien Te Dij\212at. Pitbull.mp3"
-
+
if expected.respond_to?(:force_encoding)
result = attachment.filename.dup
expected.force_encoding(Encoding::ASCII_8BIT)
@@ -1096,111 +1095,3 @@ EOF
TestMailer.smtp_settings.merge!(:enable_starttls_auto => true)
end
end
-
-class InheritableTemplateRootTest < ActiveSupport::TestCase
- def test_attr
- expected = File.expand_path("#{File.dirname(__FILE__)}/../fixtures/path.with.dots")
- assert_equal expected, FunkyPathMailer.template_root.to_s
-
- sub = Class.new(FunkyPathMailer)
- assert_deprecated do
- sub.template_root = 'test/path'
- end
-
- assert_equal File.expand_path('test/path'), sub.template_root.to_s
- assert_equal expected, FunkyPathMailer.template_root.to_s
- end
-end
-
-class MethodNamingTest < ActiveSupport::TestCase
- include ActionMailer::TestHelper
-
- class TestMailer < ActionMailer::Base
- def send
- body 'foo'
- end
- end
-
- def setup
- set_delivery_method :test
- ActionMailer::Base.perform_deliveries = true
- ActionMailer::Base.deliveries.clear
- end
-
- def teardown
- restore_delivery_method
- end
-
- def test_send_method
- assert_nothing_raised do
- assert_emails 1 do
- assert_deprecated do
- TestMailer.deliver_send
- end
- end
- end
- end
-end
-class RespondToTest < Test::Unit::TestCase
- class RespondToMailer < ActionMailer::Base; end
-
- def setup
- set_delivery_method :test
- end
-
- def teardown
- restore_delivery_method
- end
-
- def test_should_respond_to_new
- assert_respond_to RespondToMailer, :new
- end
-
- def test_should_respond_to_create_with_template_suffix
- assert_respond_to RespondToMailer, :create_any_old_template
- end
-
- def test_should_respond_to_deliver_with_template_suffix
- assert_respond_to RespondToMailer, :deliver_any_old_template
- end
-
- def test_should_not_respond_to_new_with_template_suffix
- assert !RespondToMailer.respond_to?(:new_any_old_template)
- end
-
- def test_should_not_respond_to_create_with_template_suffix_unless_it_is_separated_by_an_underscore
- assert !RespondToMailer.respond_to?(:createany_old_template)
- end
-
- def test_should_not_respond_to_deliver_with_template_suffix_unless_it_is_separated_by_an_underscore
- assert !RespondToMailer.respond_to?(:deliverany_old_template)
- end
-
- def test_should_not_respond_to_create_with_template_suffix_if_it_begins_with_a_uppercase_letter
- assert !RespondToMailer.respond_to?(:create_Any_old_template)
- end
-
- def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_uppercase_letter
- assert !RespondToMailer.respond_to?(:deliver_Any_old_template)
- end
-
- def test_should_not_respond_to_create_with_template_suffix_if_it_begins_with_a_digit
- assert !RespondToMailer.respond_to?(:create_1_template)
- end
-
- def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_digit
- assert !RespondToMailer.respond_to?(:deliver_1_template)
- end
-
- def test_should_not_respond_to_method_where_deliver_is_not_a_suffix
- assert !RespondToMailer.respond_to?(:foo_deliver_template)
- end
-
- def test_should_still_raise_exception_with_expected_message_when_calling_an_undefined_method
- error = assert_raise NoMethodError do
- RespondToMailer.not_a_method
- end
-
- assert_match(/method.*not_a_method/, error.message)
- end
-end
diff --git a/actionmailer/test/old_base/tmail_compat_test.rb b/actionmailer/test/old_base/tmail_compat_test.rb
index 255205de84..51558c2bfa 100644
--- a/actionmailer/test/old_base/tmail_compat_test.rb
+++ b/actionmailer/test/old_base/tmail_compat_test.rb
@@ -1,6 +1,14 @@
require 'abstract_unit'
class TmailCompatTest < ActiveSupport::TestCase
+ def setup
+ @silence = ActiveSupport::Deprecation.silenced
+ ActiveSupport::Deprecation.silenced = false
+ end
+
+ def teardown
+ ActiveSupport::Deprecation.silenced = @silence
+ end
def test_set_content_type_raises_deprecation_warning
mail = Mail.new
@@ -31,5 +39,4 @@ class TmailCompatTest < ActiveSupport::TestCase
end
assert_equal mail.content_transfer_encoding, "base64"
end
-
end
diff --git a/actionmailer/test/test_helper_test.rb b/actionmailer/test/test_helper_test.rb
index 8ff604c2c7..dd62164176 100644
--- a/actionmailer/test/test_helper_test.rb
+++ b/actionmailer/test/test_helper_test.rb
@@ -2,11 +2,10 @@ require 'abstract_unit'
class TestHelperMailer < ActionMailer::Base
def test
- recipients "test@example.com"
- from "tester@example.com"
-
@world = "Earth"
- render(:inline => "Hello, <%= @world %>")
+ mail :body => render(:inline => "Hello, <%= @world %>"),
+ :to => "test@example.com",
+ :from => "tester@example.com"
end
end
@@ -32,7 +31,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
self.class.determine_default_mailer("NotAMailerTest")
end
end
-
+
def test_charset_is_utf_8
assert_equal "UTF-8", charset
end
@@ -44,14 +43,14 @@ class TestHelperMailerTest < ActionMailer::TestCase
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
@@ -59,20 +58,20 @@ class TestHelperMailerTest < ActionMailer::TestCase
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
@@ -80,17 +79,17 @@ class TestHelperMailerTest < ActionMailer::TestCase
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
@@ -98,17 +97,17 @@ class TestHelperMailerTest < ActionMailer::TestCase
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
diff --git a/actionmailer/test/old_base/url_test.rb b/actionmailer/test/url_test.rb
index b6496bfe1b..0536e83098 100644
--- a/actionmailer/test/old_base/url_test.rb
+++ b/actionmailer/test/url_test.rb
@@ -18,13 +18,10 @@ class UrlTestMailer < ActionMailer::Base
end
def signed_up_with_url(recipient)
- @recipients = recipient
- @subject = "[Signed up] Welcome #{recipient}"
- @from = "system@loudthinking.com"
- @sent_on = Time.local(2004, 12, 12)
-
@recipient = recipient
@welcome_url = url_for :host => "example.com", :controller => "welcome", :action => "greeting"
+ mail(:to => recipient, :subject => "[Signed up] Welcome #{recipient}",
+ :from => "system@loudthinking.com", :date => Time.local(2004, 12, 12))
end
end
@@ -47,6 +44,7 @@ class ActionMailerUrlTest < ActionMailer::TestCase
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries.clear
+ ActiveSupport::Deprecation.silenced = false
@recipient = 'test@localhost'
end
@@ -58,19 +56,18 @@ class ActionMailerUrlTest < ActionMailer::TestCase
def test_signed_up_with_url
UrlTestMailer.delivery_method = :test
- assert_deprecated do
- AppRoutes.draw do |map|
- map.connect ':controller/:action/:id'
- map.welcome 'welcome', :controller=>"foo", :action=>"bar"
- end
+ AppRoutes.draw do
+ match ':controller(/:action(/:id))'
+ match '/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.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@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) }
@@ -83,7 +80,7 @@ class ActionMailerUrlTest < ActionMailer::TestCase
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@456>'
assert_equal expected.encoded, delivered.encoded
end
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 81abb8b5f1..5ab92c8cfc 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,4 +1,74 @@
-*Rails 3.0.0 [release candidate] (July 26th, 2010)*
+*Rails 3.1.0 (unreleased)*
+
+* Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. [Prem Sichanugrist, fxn]
+
+* URL parameters which return false for to_param now appear in the query string (previously they were removed) [Andrew White]
+
+* URL parameters which return nil for to_param are now removed from the query string [Andrew White]
+
+* ActionDispatch::MiddlewareStack now uses composition over inheritance. It is
+no longer an array which means there may be methods missing that were not
+tested.
+
+* Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). [Jakub Kuźma, Igor Wiedler]
+
+* HTML5 button_tag helper. [Rizwan Reza]
+
+* Template lookup now searches further up in the inheritance chain. [Artemave]
+
+* Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. [Piotr Sarnacki]
+
+* url_for and named url helpers now accept :subdomain and :domain as options, [Josh Kalderimis]
+
+* The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). [Josh Kalderimis]
+
+* Added config.action_controller.include_all_helpers. By default 'helper :all' is done in ActionController::Base, which includes all the helpers by default. Setting include_all_helpers to false will result in including only application_helper and helper corresponding to controller (like foo_helper for foo_controller). [Piotr Sarnacki]
+
+* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data hash of options:
+
+ tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
+ # => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
+
+ Keys are dasherized. Values are JSON-encoded, except for strings and symbols. [Stephen Celis]
+
+* Added render :once. You can pass either a string or an array of strings and Rails will ensure they each of them are rendered just once. [José Valim]
+
+* Deprecate old template handler API. The new API simply requires a template handler to respond to call. [José Valim]
+
+* :rhtml and :rxml were finally removed as template handlers. [José Valim]
+
+* Moved etag responsibility from ActionDispatch::Response to the middleware stack. [José Valim]
+
+* Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept 4 arguments and requires #destroy_session instead of simply #destroy. [José Valim]
+
+* file_field automatically adds :multipart => true to the enclosing form. [Santiago Pastorino]
+
+* Renames csrf_meta_tag -> csrf_meta_tags, and aliases csrf_meta_tag for backwards compatibility. [fxn]
+
+* Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. [Yehuda Katz, Carl Lerche]
+
+
+*Rails 3.0.2 (unreleased)*
+
+* The helper number_to_currency accepts a new :negative_format option to be able to configure how to render negative amounts. [Don Wilson]
+
+
+*Rails 3.0.1 (October 15, 2010)*
+
+* No Changes, just a version bump.
+
+
+*Rails 3.0.0 (August 29, 2010)*
+
+* password_field renders with nil value by default making the use of passwords secure by default, if you want to render you should do for instance f.password_field(:password, :value => @user.password) [Santiago Pastorino]
+
+* Symbols and strings in routes should yield the same behavior. Note this may break existing apps that were using symbols with the new routes API. [José Valim]
+
+* Add clear_helpers as a way to clean up all helpers added to this controller, maintaining just the helper with the same name as the controller. [José Valim]
+
+* Support routing constraints in functional tests. [Andrew White]
+
+* Add a header that tells Internet Explorer (all versions) to use the best available standards support. [Yehuda Katz]
* Allow stylesheet/javascript extensions to be changed through railties. [Josh Kalderimis]
@@ -26,16 +96,13 @@
resources :comments
end
end
-
+
You can now use comment_path for /comments/1 instead of post_comment_path for /posts/1/comments/1.
* Add support for multi-subdomain session by setting cookie host in session cookie so you can share session between www.example.com, example.com and user.example.com. #4818 [Guillermo Álvarez]
* Removed textilize, textilize_without_paragraph and markdown helpers. [Santiago Pastorino]
-
-*Rails 3.0.0 [beta 4] (June 8th, 2010)*
-
* Remove middleware laziness [José Valim]
* Make session stores rely on request.cookie_jar and change set_session semantics to return the cookie value instead of a boolean. [José Valim]
@@ -52,9 +119,6 @@
* Changed translate helper so that it doesn’t mark every translation as safe HTML. Only keys with a "_html" suffix and keys named "html" are considered to be safe HTML. All other translations are left untouched. [Craig Davey]
-
-*Rails 3.0.0 [beta 3] (April 13th, 2010)*
-
* New option :as added to form_for allows to change the object name. The old <% form_for :client, @post %> becomes <% form_for @post, :as => :client %> [spastorino]
* Removed verify method in controllers. [JV]
@@ -89,9 +153,6 @@
"HEAD" and #request_method returns "GET" in HEAD requests). This
is for compatibility with Rack::Request [YK]
-
-*Rails 3.0.0 [beta 2] (April 1st, 2010)*
-
* #concat is now deprecated in favor of using <%= %> helpers [YK]
* Block helpers now return Strings, so you can use <%= form_for @foo do |f| %>.
@@ -110,7 +171,7 @@
* ActionDispatch::Request#content_type returns a String to be compatible with
Rack::Request. Use #content_mime_type for the Mime::Type instance [YK]
-* Updated Prototype to 1.6.1 and Scriptaculous to 1.8.3 [ML]
+* Updated Prototype to 1.6.1 and Scriptaculous to 1.8.3 [ML]
* Change the preferred way that URL helpers are included into a class[YK & CL]
@@ -120,9 +181,6 @@
# for just url_for
include Rails.application.router.url_for
-
-*Rails 3.0.0 [beta 1] (February 4, 2010)*
-
* Fixed that PrototypeHelper#update_page should return html_safe [DHH]
* Fixed that much of DateHelper wouldn't return html_safe? strings [DHH]
diff --git a/actionpack/MIT-LICENSE b/actionpack/MIT-LICENSE
index a345a2419d..7ad1051066 100644
--- a/actionpack/MIT-LICENSE
+++ b/actionpack/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index b297ceb0e2..3661d27d51 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -102,10 +102,10 @@ A short rundown of some of the major features:
class WeblogController < ActionController::Base
# filters as methods
before_filter :authenticate, :cache, :audit
-
+
# filter as a proc
after_filter { |c| c.response.body = Gzip::compress(c.response.body) }
-
+
# class filter
after_filter LocalizeFilter
@@ -262,7 +262,7 @@ methods:
layout "weblog/layout"
def index
- @posts = Post.find(:all)
+ @posts = Post.all
end
def show
@@ -323,7 +323,7 @@ The latest version of Action Pack can be installed with Rubygems:
Source code can be downloaded as part of the Rails project on GitHub
-* http://github.com/rails/rails/tree/master/actionpack/
+* https://github.com/rails/rails/tree/master/actionpack/
== License
diff --git a/actionpack/RUNNING_UNIT_TESTS b/actionpack/RUNNING_UNIT_TESTS
index 95a8bc7497..1e3ba7abe7 100644
--- a/actionpack/RUNNING_UNIT_TESTS
+++ b/actionpack/RUNNING_UNIT_TESTS
@@ -1,22 +1,25 @@
== 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
+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
-If you only want to run a single test suite, or don't want to bother with Rake,
-you can do so with something like:
+To run a single test suite
- ruby -Itest test/controller/base_tests.rb
+ rake test TEST=path/to/test.rb
-== Dependency on ActiveRecord and database setup
+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/controller/active_record/ directory depend on having
-activerecord and sqlite installed. If ActiveRecord is not in
+activerecord and sqlite installed. If Active Record is not in
actionpack/../activerecord directory, or the sqlite rubygem is not installed,
these tests are skipped.
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 4af8ea167a..9030db9f7a 100644..100755
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -1,8 +1,5 @@
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
-require 'rake'
+#!/usr/bin/env rake
require 'rake/testtask'
-require 'rdoc/task'
require 'rake/packagetask'
require 'rake/gempackagetask'
@@ -21,7 +18,8 @@ Rake::TestTask.new(:test_action_pack) do |t|
# this will not happen automatically and the tests (as a whole) will error
t.test_files = Dir.glob('test/{abstract,controller,dispatch,template}/**/*_test.rb').sort
- # t.warning = true
+ t.warning = true
+ t.verbose = true
end
namespace :test do
@@ -36,24 +34,6 @@ Rake::TestTask.new(:test_active_record_integration) do |t|
t.test_files = Dir.glob("test/activerecord/*_test.rb")
end
-# Genereate the RDoc documentation
-
-RDoc::Task.new { |rdoc|
- rdoc.rdoc_dir = 'doc'
- rdoc.title = "Action Pack -- On rails from request to response"
- rdoc.options << '--charset' << 'utf-8'
- rdoc.options << '-f' << 'horo'
- rdoc.options << '--main' << 'README.rdoc'
- if ENV['DOC_FILES']
- rdoc.rdoc_files.include(ENV['DOC_FILES'].split(/,\s*/))
- else
- rdoc.rdoc_files.include('README.rdoc', 'RUNNING_UNIT_TESTS', 'CHANGELOG')
- rdoc.rdoc_files.include(Dir['lib/**/*.rb'] -
- Dir['lib/*/vendor/**/*.rb'])
- rdoc.rdoc_files.exclude('lib/actionpack.rb')
- end
-}
-
spec = eval(File.read('actionpack.gemspec'))
Rake::GemPackageTask.new(spec) do |p|
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index 99deff234c..f6bc5e0d37 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -19,13 +19,14 @@ Gem::Specification.new do |s|
s.has_rdoc = true
- s.add_dependency('activesupport', version)
- s.add_dependency('activemodel', version)
- s.add_dependency('builder', '~> 2.1.2')
- s.add_dependency('i18n', '~> 0.4.1')
- s.add_dependency('rack', '~> 1.2.1')
- s.add_dependency('rack-test', '~> 0.5.4')
- s.add_dependency('rack-mount', '~> 0.6.9')
- s.add_dependency('tzinfo', '~> 0.3.22')
- s.add_dependency('erubis', '~> 2.6.6')
+ s.add_dependency('activesupport', version)
+ s.add_dependency('activemodel', version)
+ s.add_dependency('rack-cache', '~> 1.0.0')
+ s.add_dependency('builder', '~> 3.0.0')
+ s.add_dependency('i18n', '~> 0.5.0')
+ s.add_dependency('rack', '~> 1.2.1')
+ s.add_dependency('rack-test', '~> 0.5.7')
+ s.add_dependency('rack-mount', '~> 0.6.13')
+ s.add_dependency('tzinfo', '~> 0.3.23')
+ s.add_dependency('erubis', '~> 2.6.6')
end
diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb
index c565c940a1..cc5878c88e 100644
--- a/actionpack/lib/abstract_controller.rb
+++ b/actionpack/lib/abstract_controller.rb
@@ -2,6 +2,7 @@ activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
require 'action_pack'
+require 'active_support/concern'
require 'active_support/ruby/shim'
require 'active_support/dependencies/autoload'
require 'active_support/core_ext/class/attribute'
@@ -23,4 +24,5 @@ module AbstractController
autoload :Translation
autoload :AssetPaths
autoload :ViewPaths
+ autoload :UrlFor
end
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index db0a6736e0..c384fd0978 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -6,9 +6,14 @@ module AbstractController
class Error < StandardError; end
class ActionNotFound < StandardError; 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
@@ -26,23 +31,21 @@ module AbstractController
# 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 we
- # are removing those methods on classes declared as abstract
- # (ActionController::Metal and ActionController::Base are defined
- # as abstract)
+ # 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 to an empty Array. Defaults to an
- # empty Array. This can be modified by other modules or subclasses
+ # The list of hidden actions to an empty array. Defaults to an
+ # empty array. This can be modified by other modules or subclasses
# to specify particular actions as hidden.
#
# ==== Returns
- # Array[String]:: An array of method names that should not be
- # considered actions.
+ # * <tt>array</tt> - An array of method names that should not be considered actions.
def hidden_actions
[]
end
@@ -54,18 +57,17 @@ module AbstractController
# itself. Finally, #hidden_actions are removed.
#
# ==== Returns
- # Array[String]:: A list of all methods that should be considered
- # actions.
+ # * <tt>array</tt> - A list 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).map { |m| m.to_s }.to_set -
+ methods = (public_instance_methods(true) -
# Except for public instance methods of Base and its ancestors
- internal_methods.map { |m| m.to_s } +
+ internal_methods +
# Be sure to include shadowed public instance methods of this class
- public_instance_methods(false).map { |m| m.to_s } -
+ public_instance_methods(false)).uniq.map { |x| x.to_s } -
# And always exclude explicitly hidden actions
- hidden_actions
+ hidden_actions.to_a
# Clear out AS callback method pollution
methods.reject { |method| method =~ /_one_time_conditions/ }
@@ -84,7 +86,7 @@ module AbstractController
# controller_name.
#
# ==== Returns
- # String
+ # * <tt>string</tt>
def controller_path
@controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
end
@@ -104,12 +106,12 @@ module AbstractController
# ActionNotFound error is raised.
#
# ==== Returns
- # self
+ # * <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}"
+ raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
end
@_response_body = nil
@@ -133,10 +135,10 @@ module AbstractController
# can be considered an action.
#
# ==== Parameters
- # name<String>:: The name of an action to be tested
+ # * <tt>name</tt> - The name of an action to be tested
#
# ==== Returns
- # TrueClass, FalseClass
+ # * <tt>TrueClass</tt>, <tt>FalseClass</tt>
def action_method?(name)
self.class.action_methods.include?(name)
end
@@ -180,11 +182,11 @@ module AbstractController
# returns nil, an ActionNotFound exception will be raised.
#
# ==== Parameters
- # action_name<String>:: An action name to find a method name for
+ # * <tt>action_name</tt> - An action name to find a method name for
#
# ==== Returns
- # String:: The name of the method that handles the action
- # nil:: No method name could be found. Raise ActionNotFound.
+ # * <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) then action_name
elsif respond_to?(:action_missing, true) then "_handle_action_missing"
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 67efeb7063..1943ca4436 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -13,8 +13,8 @@ module AbstractController
# Override AbstractController::Base's process_action to run the
# process_action callbacks around the normal behavior.
- def process_action(method_name)
- run_callbacks(:process_action, method_name) do
+ def process_action(method_name, *args)
+ run_callbacks(:process_action, action_name) do
super
end
end
@@ -28,9 +28,8 @@ module AbstractController
# a Rails process.
#
# ==== Options
- # :only<#to_s>:: The callback should be run only for this action
- # :except<#to_s>:: The callback should be run for all actions
- # except this action
+ # * <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)
if only = options[:only]
only = Array(only).map {|o| "action_name == '#{o}'"}.join(" || ")
@@ -45,7 +44,7 @@ module AbstractController
# Skip before, after, and around filters matching any of the names
#
# ==== Parameters
- # *names<Object>:: A list of valid names that could be used for
+ # * <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
@@ -60,13 +59,13 @@ module AbstractController
# the normalization across several methods that use it.
#
# ==== Parameters
- # callbacks<Array[*Object, Hash]>:: A list of callbacks, with an optional
+ # * <tt>callbacks</tt> - An array of callbacks, with an optional
# options hash as the last parameter.
- # block<Proc>:: A proc that should be added to the callbacks.
+ # * <tt>block</tt> - A proc that should be added to the callbacks.
#
# ==== Block Parameters
- # name<Symbol>:: The callback to be added
- # options<Hash>:: A list of options to be used when adding the callback
+ # * <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)
options = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
_normalize_callback_options(options)
@@ -84,6 +83,7 @@ module AbstractController
# for details on the allowed parameters.
def #{filter}_filter(*names, &blk)
_insert_callbacks(names, blk) do |name, options|
+ options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after}
set_callback(:process_action, :#{filter}, name, options)
end
end
@@ -92,6 +92,7 @@ module AbstractController
# for details on the allowed parameters.
def prepend_#{filter}_filter(*names, &blk)
_insert_callbacks(names, blk) do |name, options|
+ options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after}
set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true))
end
end
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index 4374b439d0..20f8601a8e 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -9,6 +9,9 @@ module AbstractController
included do
class_attribute :_helpers
self._helpers = Module.new
+
+ class_attribute :_helper_methods
+ self._helper_methods = Array.new
end
module ClassMethods
@@ -40,10 +43,13 @@ module AbstractController
# <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
#
# ==== Parameters
- # meths<Array[#to_s]>:: The name of a method on the controller
+ # * <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.each do |meth|
+ meths.flatten!
+ self._helper_methods += meths
+
+ meths.each do |meth|
_helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
def #{meth}(*args, &blk)
controller.send(%(#{meth}), *args, &blk)
@@ -55,8 +61,8 @@ module AbstractController
# The +helper+ class method can take a series of helper module names, a block, or both.
#
# ==== Parameters
- # *args<Array[Module, Symbol, String, :all]>
- # block<Block>:: A block defining helper methods
+ # * <tt>*args</tt> - Module, Symbol, String, :all
+ # * <tt>block</tt> - A block defining helper methods
#
# ==== Examples
# When the argument is a module it will be included directly in the template class.
@@ -95,12 +101,23 @@ module AbstractController
_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
+
private
# Makes all the (instance) methods in the helper module available to templates
# rendered through this controller.
#
# ==== Parameters
- # mod<Module>:: The module to include into the current helper module
+ # * <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 }
@@ -118,10 +135,10 @@ module AbstractController
# are returned.
#
# ==== Parameters
- # args<Array[String, Symbol, Module]>:: A list of helpers
+ # * <tt>args</tt> - An array of helpers
#
# ==== Returns
- # Array[Module]:: A normalized list of modules for the list of
+ # * <tt>Array</tt> - A normalized list of modules for the list of
# helpers provided.
def modules_for_helpers(args)
args.flatten.map! do |arg|
diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb
index 5cd7a90ab5..4ee54474cc 100644
--- a/actionpack/lib/abstract_controller/layouts.rb
+++ b/actionpack/lib/abstract_controller/layouts.rb
@@ -114,11 +114,13 @@ module AbstractController
#
# class WeblogController < ActionController::Base
# layout proc{ |controller| controller.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
#
# If no directory is specified for the template name, the template will by default be looked for in <tt>app/views/layouts/</tt>.
# Otherwise, it will be looked up relative to the template root.
@@ -183,7 +185,7 @@ module AbstractController
# layout.
#
# ==== Returns
- # Boolean:: True if the action has a layout, false otherwise.
+ # * <tt> Boolean</tt> - True if the action has a layout, false otherwise.
def action_has_layout?
return unless super
@@ -209,11 +211,11 @@ module AbstractController
# true:: raise an ArgumentError
#
# ==== Parameters
- # layout<String, Symbol, false)>:: The layout to use.
+ # * <tt>String, Symbol, false</tt> - The layout to use.
#
# ==== Options (conditions)
- # :only<#to_s, Array[#to_s]>:: A list of actions to apply this layout to.
- # :except<#to_s, Array[#to_s]>:: Apply this layout to all actions but this one
+ # * :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?
@@ -228,18 +230,15 @@ module AbstractController
# value of this method.
#
# ==== Returns
- # String:: A template name
+ # * <tt>String</tt> - A template name
def _implied_layout_name
controller_path
end
- # Takes the specified layout and creates a _layout method to be called
- # by _default_layout
+ # Creates a _layout method to be called by _default_layout .
#
- # If there is no explicit layout specified:
- # If a layout is found in the view paths with the controller's
- # name, return that string. Otherwise, use the superclass'
- # layout (which might also be implied)
+ # 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
remove_possible_method(:_layout)
@@ -266,11 +265,11 @@ module AbstractController
raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil"
when nil
if name
- _prefix = "layouts" unless _implied_layout_name =~ /\blayouts/
+ _prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def _layout
- if template_exists?("#{_implied_layout_name}", #{_prefix.inspect})
+ if template_exists?("#{_implied_layout_name}", #{_prefixes.inspect})
"#{_implied_layout_name}"
else
super
@@ -313,8 +312,8 @@ module AbstractController
# the name type.
#
# ==== Parameters
- # name<String|TrueClass|FalseClass|Symbol>:: The name of the template
- # details<Hash{Symbol => Object}>:: A list of details to restrict
+ # * <tt>name</tt> - The name of the template
+ # * <tt>details</tt> - A list of details to restrict
# the lookup to. By default, layout lookup is limited to the
# formats specified for the current request.
def _layout_for_option(name)
@@ -333,20 +332,19 @@ module AbstractController
# Optionally raises an exception if the layout could not be found.
#
# ==== Parameters
- # details<Hash>:: A list of details to restrict the search by. This
+ # * <tt>details</tt> - A list of details to restrict the search by. This
# might include details like the format or locale of the template.
- # require_layout<Boolean>:: If this is true, raise an ArgumentError
+ # * <tt>require_logout</tt> - If this is true, raise an ArgumentError
# with details about the fact that the exception could not be
# found (defaults to false)
#
# ==== Returns
- # Template:: The template object for the default layout (or nil)
+ # * <tt>template</tt> - The template object for the default layout (or nil)
def _default_layout(require_layout = false)
begin
layout_name = _layout if action_has_layout?
rescue NameError => e
- raise NoMethodError,
- "You specified #{@_layout.inspect} as the layout, but no such method was found"
+ raise e, "Could not render layout: #{e.message}"
end
if require_layout && action_has_layout? && !layout_name
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 0000000000..dec1e9d6d9
--- /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) }
+ 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
index b81d5954eb..691310d5d2 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -12,16 +12,16 @@ module AbstractController
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
# it will trigger the lookup_context and consequently expire the cache.
- # TODO Add some deprecation warnings to remove I18n.locale from controllers
class I18nProxy < ::I18n::Config #:nodoc:
- attr_reader :i18n_config, :lookup_context
+ attr_reader :original_config, :lookup_context
- def initialize(i18n_config, lookup_context)
- @i18n_config, @lookup_context = i18n_config, lookup_context
+ def initialize(original_config, lookup_context)
+ original_config = original_config.original_config if original_config.respond_to?(:original_config)
+ @original_config, @lookup_context = original_config, lookup_context
end
def locale
- @i18n_config.locale
+ @original_config.locale
end
def locale=(value)
@@ -47,19 +47,34 @@ module AbstractController
@view_context_class ||= begin
controller = self
Class.new(ActionView::Base) do
+ if controller.respond_to?(:_routes) && controller._routes
+ include controller._routes.url_helpers
+ include controller._routes.mounted_helpers
+ end
+
if controller.respond_to?(:_helpers)
include controller._helpers
- if controller.respond_to?(:_routes)
- include controller._routes.url_helpers
- end
-
# TODO: Fix RJS to not require this
self.helpers = controller._helpers
end
end
end
end
+
+ def parent_prefixes
+ @parent_prefixes ||= begin
+ parent_controller = superclass
+ prefixes = []
+
+ until parent_controller.abstract?
+ prefixes << parent_controller.controller_path
+ parent_controller = parent_controller.superclass
+ end
+
+ prefixes
+ end
+ end
end
attr_writer :view_context_class
@@ -98,7 +113,7 @@ module AbstractController
def render_to_string(*args, &block)
options = _normalize_args(*args, &block)
_normalize_options(options)
- render_to_body(options)
+ render_to_body(options).tap { self.response_body = nil }
end
# Raw rendering of a template to a Rack-compatible body.
@@ -114,12 +129,15 @@ module AbstractController
view_context.render(options)
end
- # The prefix used in render "foo" shortcuts.
- def _prefix
- controller_path
+ # The prefixes used in render "foo" shortcuts.
+ def _prefixes
+ @_prefixes ||= begin
+ parent_prefixes = self.class.parent_prefixes
+ parent_prefixes.dup.unshift(controller_path)
+ end
end
- private
+ private
# This method should return a hash with assigns.
# You can overwrite this configuration per controller.
@@ -128,7 +146,7 @@ module AbstractController
hash = {}
variables = instance_variable_names
variables -= protected_instance_variables if respond_to?(:protected_instance_variables)
- variables.each { |name| hash[name.to_s[1..-1]] = instance_variable_get(name) }
+ variables.each { |name| hash[name.to_s[1, name.length]] = instance_variable_get(name) }
hash
end
@@ -138,13 +156,13 @@ module AbstractController
case action
when NilClass
when Hash
- options, action = action, nil
+ options = action
when String, Symbol
action = action.to_s
key = action.include?(?/) ? :file : :action
options[key] = action
else
- options.merge!(:partial => action)
+ options[:partial] = action
end
options
@@ -155,8 +173,8 @@ module AbstractController
options[:partial] = action_name
end
- if (options.keys & [:partial, :file, :template]).empty?
- options[:prefix] ||= _prefix
+ if (options.keys & [:partial, :file, :template, :once]).empty?
+ options[:prefixes] ||= _prefixes
end
options[:template] ||= (options[:action] || action_name).to_s
diff --git a/actionpack/lib/abstract_controller/url_for.rb b/actionpack/lib/abstract_controller/url_for.rb
new file mode 100644
index 0000000000..e5d5bef6b4
--- /dev/null
+++ b/actionpack/lib/abstract_controller/url_for.rb
@@ -0,0 +1,27 @@
+module AbstractController
+ 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
index b552a649d1..cea0f5ad1e 100644
--- a/actionpack/lib/abstract_controller/view_paths.rb
+++ b/actionpack/lib/abstract_controller/view_paths.rb
@@ -34,9 +34,9 @@ module AbstractController
# Append a path to the list of view paths for this controller.
#
# ==== Parameters
- # path<String, ViewPath>:: If a String is provided, it gets converted into
- # the default view path. You may also provide a custom view path
- # (see ActionView::ViewPathSet for more information)
+ # * <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.dup + Array(path)
end
@@ -44,9 +44,9 @@ module AbstractController
# Prepend a path to the list of view paths for this controller.
#
# ==== Parameters
- # path<String, ViewPath>:: If a String is provided, it gets converted into
- # the default view path. You may also provide a custom view path
- # (see ActionView::ViewPathSet for more information)
+ # * <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 = Array(path) + view_paths.dup
end
@@ -59,8 +59,8 @@ module AbstractController
# Set the view paths.
#
# ==== Parameters
- # paths<ViewPathSet, Object>:: If a ViewPathSet is provided, use that;
- # otherwise, process the parameter into a ViewPathSet.
+ # * <tt>paths</tt> - If a PathSet is provided, use that;
+ # otherwise, process the parameter into a PathSet.
def view_paths=(paths)
self._view_paths = ActionView::Base.process_view_paths(paths)
self._view_paths.freeze
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index ca0e5d6ff6..5b81cd39f4 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -34,7 +34,6 @@ module ActionController
autoload :UrlFor
end
- autoload :Dispatcher, 'action_controller/deprecated/dispatcher'
autoload :Integration, 'action_controller/deprecated/integration_test'
autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
@@ -73,4 +72,5 @@ require 'active_support/core_ext/load_error'
require 'active_support/core_ext/module/attr_internal'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/name_error'
+require 'active_support/core_ext/uri'
require 'active_support/inflector'
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 9dfffced75..81c0698fb8 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -1,6 +1,171 @@
require "action_controller/log_subscriber"
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 of 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 allows 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!
+ #
+ # Other options for session storage:
+ #
+ # * ActiveRecord::SessionStore - Sessions are stored in your database, which works better than PStore with multiple app servers and,
+ # unlike CookieStore, hides your session contents from the user. To use ActiveRecord::SessionStore, set
+ #
+ # MyApplication::Application.config.session_store :active_record_store
+ #
+ # in your <tt>config/initializers/session_store.rb</tt> and run <tt>script/rails g session_migration</tt>.
+ #
+ # == Responses
+ #
+ # Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
+ # 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. Especially 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
+ # 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 a 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.
+ #
+ # 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!
@@ -58,13 +223,6 @@ module ActionController
# Rails 2.x compatibility
include ActionController::Compatibility
- def self.inherited(klass)
- super
- klass.helper :all
- end
-
ActiveSupport.run_load_hooks(:action_controller, self)
end
end
-
-require "action_controller/deprecated/base"
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index 4105f9e14f..14137f2886 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -3,7 +3,7 @@ require 'uri'
require 'set'
module ActionController #:nodoc:
- # Caching is a cheap way of speeding up slow applications by keeping the result of
+ # \Caching is a cheap way of speeding up slow applications by keeping the result of
# calculations, renderings, and database calls around for subsequent requests.
# Action Controller affords you three approaches in varying levels of granularity:
# Page, Action, Fragment.
@@ -14,7 +14,7 @@ module ActionController #:nodoc:
# Note: To turn off all caching and sweeping, set
# config.action_controller.perform_caching = false.
#
- # == Caching stores
+ # == \Caching stores
#
# All the caching stores from ActiveSupport::Cache are available to be used as backends
# for Action Controller caching. This setting only affects action and fragment caching
diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb
index 546f043c58..2c8a6e4d4d 100644
--- a/actionpack/lib/action_controller/caching/actions.rb
+++ b/actionpack/lib/action_controller/caching/actions.rb
@@ -4,53 +4,58 @@ module ActionController #:nodoc:
module Caching
# Action caching is similar to page caching by the fact that the entire
# output of the response is cached, but unlike page caching, every
- # request still goes through the Action Pack. The key benefit
- # of this is that filters are run before the cache is served, which
- # allows for authentication and other restrictions on whether someone
- # is allowed to see the cache. Example:
+ # request still goes through Action Pack. The key benefit of this is
+ # that filters run before the cache is served, which allows for
+ # authentication and other restrictions on whether someone is allowed
+ # to execute such action. Example:
#
# class ListsController < ApplicationController
# before_filter :authenticate, :except => :public
+ #
# caches_page :public
- # caches_action :index, :show, :feed
+ # caches_action :index, :show
# end
#
- # In this example, the public action doesn't require authentication,
- # so it's possible to use the faster page caching method. But both
- # the show and feed action are to be shielded behind the authenticate
- # filter, so we need to implement those as action caches.
- #
- # Action caching internally uses the fragment caching and an around
- # filter to do the job. The fragment cache is named according to both
- # the current host and the path. So a page that is accessed at
- # http://david.somewhere.com/lists/show/1 will result in a fragment named
- # "david.somewhere.com/lists/show/1". This allows the cacher to
- # differentiate between "david.somewhere.com/lists/" and
- # "jamis.somewhere.com/lists/" -- which is a helpful way of assisting
+ # In this example, the +public+ action doesn't require authentication
+ # so it's possible to use the faster page caching. On the other hand
+ # +index+ and +show+ require authentication. They can still be cached,
+ # but we need action caching for them.
+ #
+ # Action caching uses fragment caching internally and an around
+ # filter to do the job. The fragment cache is named according to
+ # the host and path of the request. A page that is accessed at
+ # <tt>http://david.example.com/lists/show/1</tt> will result in a fragment named
+ # <tt>david.example.com/lists/show/1</tt>. This allows the cacher to
+ # differentiate between <tt>david.example.com/lists/</tt> and
+ # <tt>jamis.example.com/lists/</tt> -- which is a helpful way of assisting
# the subdomain-as-account-key pattern.
#
# Different representations of the same resource, e.g.
- # <tt>http://david.somewhere.com/lists</tt> and
- # <tt>http://david.somewhere.com/lists.xml</tt>
+ # <tt>http://david.example.com/lists</tt> and
+ # <tt>http://david.example.com/lists.xml</tt>
# are treated like separate requests and so are cached separately.
# Keep in mind when expiring an action cache that
# <tt>:action => 'lists'</tt> is not the same as
# <tt>:action => 'list', :format => :xml</tt>.
#
# You can set modify the default action cache path by passing a
- # :cache_path option. This will be passed directly to
- # ActionCachePath.path_for. This is handy for actions with multiple
- # possible routes that should be cached differently. If a block is
- # given, it is called with the current controller instance.
+ # <tt>:cache_path</tt> option. This will be passed directly to
+ # <tt>ActionCachePath.path_for</tt>. This is handy for actions with
+ # multiple possible routes that should be cached differently. If a
+ # block is given, it is called with the current controller instance.
+ #
+ # And you can also use <tt>:if</tt> (or <tt>:unless</tt>) to pass a
+ # proc that specifies when the action should be cached.
#
- # And you can also use :if (or :unless) to pass a Proc that
- # specifies when the action should be cached.
+ # Finally, if you are using memcached, you can also pass <tt>:expires_in</tt>.
#
- # Finally, if you are using memcached, you can also pass :expires_in.
+ # The following example depicts some of the points made above:
#
# class ListsController < ApplicationController
# before_filter :authenticate, :except => :public
- # caches_page :public
+ #
+ # caches_page :public
+ #
# caches_action :index, :if => proc do |c|
# !c.request.format.json? # cache if is not a JSON request
# end
@@ -58,19 +63,28 @@ module ActionController #:nodoc:
# caches_action :show, :cache_path => { :project => 1 },
# :expires_in => 1.hour
#
- # caches_action :feed, :cache_path => proc do |controller|
- # if controller.params[:user_id]
- # controller.send(:user_list_url,
- # controller.params[:user_id], controller.params[:id])
+ # caches_action :feed, :cache_path => proc do |c|
+ # if c.params[:user_id]
+ # c.send(:user_list_url,
+ # c.params[:user_id], c.params[:id])
# else
- # controller.send(:list_url, controller.params[:id])
+ # c.send(:list_url, c.params[:id])
# end
# end
# end
#
- # If you pass :layout => false, it will only cache your action
- # content. It is useful when your layout has dynamic information.
+ # If you pass <tt>:layout => false</tt>, it will only cache your action
+ # content. That's useful when your layout has dynamic information.
+ #
+ # Warning: If the format of the request is determined by the Accept HTTP
+ # header the Content-Type of the cached response could be wrong because
+ # no information about the MIME type is stored in the cache key. So, if
+ # you first ask for MIME type M in the Accept header, a cache entry is
+ # created, and then perform a second request to the same resource asking
+ # for a different MIME type, you'd get the content cached for M.
#
+ # The <tt>:format</tt> parameter is taken into account though. The safest
+ # way to cache by MIME type is to pass the format in the route.
module Actions
extend ActiveSupport::Concern
@@ -89,12 +103,14 @@ module ActionController #:nodoc:
end
def _save_fragment(name, options)
- return unless caching_allowed?
-
content = response_body
content = content.join if content.is_a?(Array)
- write_fragment(name, content, options)
+ if caching_allowed?
+ write_fragment(name, content, options)
+ else
+ content
+ end
end
protected
@@ -144,7 +160,7 @@ module ActionController #:nodoc:
attr_reader :path, :extension
# If +infer_extension+ is true, the cache path extension is looked up from the request's
- # path & format. This is desirable when reading and writing the cache, but not when
+ # path and format. This is desirable when reading and writing the cache, but not when
# expiring the cache - expire_action should expire the same files regardless of the
# request format.
def initialize(controller, options = {}, infer_extension = true)
@@ -161,7 +177,7 @@ module ActionController #:nodoc:
def normalize!(path)
path << 'index' if path[-1] == ?/
path << ".#{extension}" if extension and !path.ends_with?(extension)
- URI.unescape(path)
+ URI.parser.unescape(path)
end
end
end
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
index 460273dac1..0be04b70a1 100644
--- a/actionpack/lib/action_controller/caching/fragments.rb
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -1,52 +1,72 @@
module ActionController #:nodoc:
module Caching
- # Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is useful when
- # certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple
- # parties. The caching is done using the cache helper available in the Action View. A template with caching might look something like:
+ # Fragment caching is used for caching various blocks within
+ # views without caching the entire action as a whole. This is
+ # useful when certain elements of an action change frequently or
+ # depend on complicated state while other parts rarely change or
+ # can be shared amongst multiple parties. The caching is done using
+ # the <tt>cache</tt> helper available in the Action View. A
+ # template with fragment caching might look like:
#
# <b>Hello <%= @name %></b>
+ #
# <% cache do %>
# All the topics in the system:
# <%= render :partial => "topic", :collection => Topic.find(:all) %>
# <% end %>
#
- # This cache will bind to the name of the action that called it, so if this code was part of the view for the topics/list action, you would
- # be able to invalidate it using <tt>expire_fragment(:controller => "topics", :action => "list")</tt>.
+ # This cache will bind the name of the action that called it, so if
+ # this code was part of the view for the topics/list action, you
+ # would be able to invalidate it using:
+ #
+ # expire_fragment(:controller => "topics", :action => "list")
#
- # This default behavior is of limited use if you need to cache multiple fragments per action or if the action itself is cached using
- # <tt>caches_action</tt>, so we also have the option to qualify the name of the cached fragment with something like:
+ # This default behavior is limited if you need to cache multiple
+ # fragments per action or if the action itself is cached using
+ # <tt>caches_action</tt>. To remedy this, there is an option to
+ # qualify the name of the cached fragment by using the
+ # <tt>:action_suffix</tt> option:
#
# <% cache(:action => "list", :action_suffix => "all_topics") do %>
#
- # That would result in a name such as "/topics/list/all_topics", avoiding conflicts with the action cache and with any fragments that use a
- # different suffix. Note that the URL doesn't have to really exist or be callable - the url_for system is just used to generate unique
- # cache names that we can refer to when we need to expire the cache.
+ # That would result in a name such as
+ # <tt>/topics/list/all_topics</tt>, avoiding conflicts with the
+ # action cache and with any fragments that use a different suffix.
+ # Note that the URL doesn't have to really exist or be callable
+ # - the url_for system is just used to generate unique cache names
+ # that we can refer to when we need to expire the cache.
#
# The expiration call for this example is:
#
- # expire_fragment(:controller => "topics", :action => "list", :action_suffix => "all_topics")
+ # expire_fragment(:controller => "topics",
+ # :action => "list",
+ # :action_suffix => "all_topics")
module Fragments
- # Given a key (as described in <tt>expire_fragment</tt>), returns a key suitable for use in reading,
- # writing, or expiring a cached fragment. If the key is a hash, the generated key is the return
- # value of url_for on that hash (without the protocol). All keys are prefixed with "views/" and uses
+ # Given a key (as described in <tt>expire_fragment</tt>), returns
+ # a key suitable for use in reading, writing, or expiring a
+ # cached fragment. If the key is a hash, the generated key is the
+ # return value of url_for on that hash (without the protocol).
+ # All keys are prefixed with <tt>views/</tt> and uses
# ActiveSupport::Cache.expand_cache_key for the expansion.
def fragment_cache_key(key)
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
end
- # Writes <tt>content</tt> to the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats)
+ # Writes <tt>content</tt> to the location signified by
+ # <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats).
def write_fragment(key, content, options = nil)
return content unless cache_configured?
key = fragment_cache_key(key)
instrument_fragment_cache :write_fragment, key do
- content = content.html_safe.to_str if content.respond_to?(:html_safe)
+ content = content.to_str
cache_store.write(key, content, options)
end
content
end
- # Reads a cached fragment from the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats)
+ # Reads a cached fragment from the location signified by <tt>key</tt>
+ # (see <tt>expire_fragment</tt> for acceptable formats).
def read_fragment(key, options = nil)
return unless cache_configured?
@@ -57,7 +77,8 @@ module ActionController #:nodoc:
end
end
- # Check if a cached fragment from the location signified by <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats)
+ # Check if a cached fragment from the location signified by
+ # <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats)
def fragment_exist?(key, options = nil)
return unless cache_configured?
key = fragment_cache_key(key)
@@ -70,8 +91,9 @@ module ActionController #:nodoc:
# Removes fragments from the cache.
#
# +key+ can take one of three forms:
+ #
# * String - This would normally take the form of a path, like
- # <tt>"pages/45/notes"</tt>.
+ # <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
diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb
index 4f7a5d3f55..8c583c7ce0 100644
--- a/actionpack/lib/action_controller/caching/pages.rb
+++ b/actionpack/lib/action_controller/caching/pages.rb
@@ -1,5 +1,4 @@
require 'fileutils'
-require 'uri'
require 'active_support/core_ext/class/attribute_accessors'
module ActionController #:nodoc:
@@ -71,9 +70,9 @@ module ActionController #:nodoc:
# Manually cache the +content+ in the key determined by +path+. Example:
# cache_page "I'm the cached content", "/lists/show"
- def cache_page(content, path)
+ def cache_page(content, path, extension = nil)
return unless perform_caching
- path = page_cache_path(path)
+ path = page_cache_path(path, extension)
instrument_page_cache :write_page, path do
FileUtils.makedirs(File.dirname(path))
@@ -98,14 +97,16 @@ module ActionController #:nodoc:
end
private
- def page_cache_file(path)
- name = (path.empty? || path == "/") ? "/index" : URI.unescape(path.chomp('/'))
- name << page_cache_extension unless (name.split('/').last || name).include? '.'
+ def page_cache_file(path, extension)
+ name = (path.empty? || path == "/") ? "/index" : URI.parser.unescape(path.chomp('/'))
+ unless (name.split('/').last || name).include? '.'
+ name << (extension || self.page_cache_extension)
+ end
return name
end
- def page_cache_path(path)
- page_cache_directory + page_cache_file(path)
+ def page_cache_path(path, extension = nil)
+ page_cache_directory.to_s + page_cache_file(path, extension)
end
def instrument_page_cache(name, path)
@@ -135,7 +136,7 @@ module ActionController #:nodoc:
# If no options are provided, the requested url is used. Example:
# cache_page "I'm the cached content", :controller => "lists", :action => "show"
def cache_page(content = nil, options = nil)
- return unless self.class.perform_caching && caching_allowed
+ return unless self.class.perform_caching && caching_allowed?
path = case options
when Hash
@@ -146,13 +147,13 @@ module ActionController #:nodoc:
request.path
end
- self.class.cache_page(content || response.body, path)
+ if (type = Mime::LOOKUP[self.content_type]) && (type_symbol = type.symbol).present?
+ extension = ".#{type_symbol}"
+ end
+
+ self.class.cache_page(content || response.body, path, extension)
end
- private
- def caching_allowed
- request.get? && response.status.to_i == 200
- end
end
end
end
diff --git a/actionpack/lib/action_controller/deprecated.rb b/actionpack/lib/action_controller/deprecated.rb
index 9f2de57033..aa0cfc9395 100644
--- a/actionpack/lib/action_controller/deprecated.rb
+++ b/actionpack/lib/action_controller/deprecated.rb
@@ -1,3 +1,3 @@
ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request
ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response
-ActionController::Routing = ActionDispatch::Routing
+ActionController::Routing = ActionDispatch::Routing \ No newline at end of file
diff --git a/actionpack/lib/action_controller/deprecated/base.rb b/actionpack/lib/action_controller/deprecated/base.rb
deleted file mode 100644
index 3975afcaf0..0000000000
--- a/actionpack/lib/action_controller/deprecated/base.rb
+++ /dev/null
@@ -1,133 +0,0 @@
-module ActionController
- class Base
- # Deprecated methods. Wrap them in a module so they can be overwritten by plugins
- # (like the verify method.)
- module DeprecatedBehavior #:nodoc:
- def relative_url_root
- ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root is ineffective. " <<
- "Please stop using it.", caller
- end
-
- def relative_url_root=
- ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root= is ineffective. " <<
- "Please stop using it.", caller
- end
-
- def consider_all_requests_local
- ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local is deprecated, " <<
- "use Rails.application.config.consider_all_requests_local instead", caller
- Rails.application.config.consider_all_requests_local
- end
-
- def consider_all_requests_local=(value)
- ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local= is deprecated. " <<
- "Please configure it on your application with config.consider_all_requests_local=", caller
- Rails.application.config.consider_all_requests_local = value
- end
-
- def allow_concurrency
- ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency is deprecated, " <<
- "use Rails.application.config.allow_concurrency instead", caller
- Rails.application.config.allow_concurrency
- end
-
- def allow_concurrency=(value)
- ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency= is deprecated. " <<
- "Please configure it on your application with config.allow_concurrency=", caller
- Rails.application.config.allow_concurrency = value
- end
-
- def ip_spoofing_check=(value)
- ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check= is deprecated. " <<
- "Please configure it on your application with config.action_dispatch.ip_spoofing_check=", caller
- Rails.application.config.action_dispatch.ip_spoofing_check = value
- end
-
- def ip_spoofing_check
- ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check is deprecated. " <<
- "Configuring ip_spoofing_check on the application configures a middleware.", caller
- Rails.application.config.action_dispatch.ip_spoofing_check
- end
-
- def cookie_verifier_secret=(value)
- ActiveSupport::Deprecation.warn "ActionController::Base.cookie_verifier_secret= is deprecated. " <<
- "Please configure it on your application with config.secret_token=", caller
- end
-
- def cookie_verifier_secret
- ActiveSupport::Deprecation.warn "ActionController::Base.cookie_verifier_secret is deprecated.", caller
- end
-
- def trusted_proxies=(value)
- ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies= is deprecated. " <<
- "Please configure it on your application with config.action_dispatch.trusted_proxies=", caller
- Rails.application.config.action_dispatch.ip_spoofing_check = value
- end
-
- def trusted_proxies
- ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies is deprecated. " <<
- "Configuring trusted_proxies on the application configures a middleware.", caller
- Rails.application.config.action_dispatch.ip_spoofing_check = value
- end
-
- def session(*args)
- ActiveSupport::Deprecation.warn(
- "Disabling sessions for a single controller has been deprecated. " +
- "Sessions are now lazy loaded. So if you don't access them, " +
- "consider them off. You can still modify the session cookie " +
- "options with request.session_options.", caller)
- end
-
- def session=(value)
- ActiveSupport::Deprecation.warn "ActionController::Base.session= is deprecated. " <<
- "Please configure it on your application with config.session_store :cookie_store, :key => '....'", caller
- if value.delete(:disabled)
- Rails.application.config.session_store :disabled
- else
- store = Rails.application.config.session_store
- Rails.application.config.session_store store, value
- end
- end
-
- # Controls the resource action separator
- def resource_action_separator
- @resource_action_separator ||= "/"
- end
-
- def resource_action_separator=(val)
- ActiveSupport::Deprecation.warn "ActionController::Base.resource_action_separator is deprecated and only " \
- "works with the deprecated router DSL."
- @resource_action_separator = val
- end
-
- def use_accept_header
- ActiveSupport::Deprecation.warn "ActionController::Base.use_accept_header doesn't do anything anymore. " \
- "The accept header is always taken into account."
- end
-
- def use_accept_header=(val)
- use_accept_header
- end
-
- # This method has been moved to ActionDispatch::Request.filter_parameters
- def filter_parameter_logging(*args, &block)
- ActiveSupport::Deprecation.warn("Setting filter_parameter_logging in ActionController is deprecated and has no longer effect, please set 'config.filter_parameters' in config/application.rb instead", caller)
- filter = Rails.application.config.filter_parameters
- filter.concat(args)
- filter << block if block
- filter
- end
-
- # This was moved to a plugin
- def verify(*args)
- ActiveSupport::Deprecation.warn "verify was removed from Rails and is now available as a plugin. " <<
- "Please install it with `rails plugin install git://github.com/rails/verification.git`.", caller
- end
- end
-
- extend DeprecatedBehavior
-
- delegate :consider_all_requests_local, :consider_all_requests_local=,
- :allow_concurrency, :allow_concurrency=, :to => :"self.class"
- end
-end
diff --git a/actionpack/lib/action_controller/deprecated/dispatcher.rb b/actionpack/lib/action_controller/deprecated/dispatcher.rb
deleted file mode 100644
index 8c21e375dd..0000000000
--- a/actionpack/lib/action_controller/deprecated/dispatcher.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-module ActionController
- class Dispatcher
- class << self
- def before_dispatch(*args, &block)
- ActiveSupport::Deprecation.warn "ActionController::Dispatcher.before_dispatch is deprecated. " <<
- "Please use ActionDispatch::Callbacks.before instead.", caller
- ActionDispatch::Callbacks.before(*args, &block)
- end
-
- def after_dispatch(*args, &block)
- ActiveSupport::Deprecation.warn "ActionController::Dispatcher.after_dispatch is deprecated. " <<
- "Please use ActionDispatch::Callbacks.after instead.", caller
- ActionDispatch::Callbacks.after(*args, &block)
- end
-
- def to_prepare(*args, &block)
- ActiveSupport::Deprecation.warn "ActionController::Dispatcher.to_prepare is deprecated. " <<
- "Please use config.to_prepare instead", caller
- ActionDispatch::Callbacks.after(*args, &block)
- end
-
- def new
- ActiveSupport::Deprecation.warn "ActionController::Dispatcher.new is deprecated, use Rails.application instead."
- Rails.application
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index ece270b3ce..3fae697cc3 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -16,7 +16,11 @@ module ActionController
payload = event.payload
additions = ActionController::Base.log_process_action(payload)
- message = "Completed #{payload[:status]} #{Rack::Utils::HTTP_STATUS_CODES[payload[:status]]} in %.0fms" % event.duration
+ status = payload[:status]
+ if status.nil? && payload[:exception].present?
+ status = Rack::Utils.status_code(ActionDispatch::ShowExceptions.rescue_responses[payload[:exception].first]) rescue nil
+ end
+ message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in %.0fms" % event.duration
message << " (#{additions.join(" | ")})" unless additions.blank?
info(message)
@@ -42,7 +46,7 @@ module ActionController
def #{method}(event)
key_or_path = event.payload[:key] || event.payload[:path]
human_name = #{method.to_s.humanize.inspect}
- info("\#{human_name} \#{key_or_path} (%.1fms)" % event.duration)
+ info("\#{human_name} \#{key_or_path} \#{"(%.1fms)" % event.duration}")
end
METHOD
end
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 2281c500c5..e5db31061b 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -12,7 +12,7 @@ module ActionController
#
class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
- def initialize(klass, *args)
+ 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)
@@ -36,35 +36,88 @@ module ActionController
action = action.to_s
raise "MiddlewareStack#build requires an app" unless app
- reverse.inject(app) do |a, middleware|
+ middlewares.reverse.inject(app) do |a, middleware|
middleware.valid?(action) ?
middleware.build(a) : a
end
end
end
- # ActionController::Metal provides a way to get a valid Rack application from a controller.
+ # <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
+ # valid Rack interface without the additional niceties provided by
+ # <tt>ActionController::Base</tt>.
+ #
+ # A sample metal controller might look like this:
+ #
+ # class HelloController < ActionController::Metal
+ # def index
+ # self.response_body = "Hello World!"
+ # end
+ # end
+ #
+ # And then to route requests to your metal controller, you would add
+ # something like this to <tt>config/routes.rb</tt>:
+ #
+ # match 'hello', :to => HelloController.action(:index)
+ #
+ # The +action+ method returns a valid Rack application for the \Rails
+ # router to dispatch to.
+ #
+ # == Rendering Helpers
+ #
+ # <tt>ActionController::Metal</tt> by default provides no utilities for rendering
+ # views, partials, or other responses aside from explicitly calling of
+ # <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
+ # add the render helpers you're used to having in a normal controller, you
+ # can do the following:
+ #
+ # class HelloController < ActionController::Metal
+ # include ActionController::Rendering
+ # append_view_path "#{Rails.root}/app/views"
+ #
+ # def index
+ # render "hello/index"
+ # end
+ # end
+ #
+ # == Redirection Helpers
+ #
+ # To add redirection helpers to your metal controller, do the following:
+ #
+ # class HelloController < ActionController::Metal
+ # include ActionController::Redirecting
+ # include Rails.application.routes.url_helpers
+ #
+ # def index
+ # redirect_to root_url
+ # end
+ # end
+ #
+ # == Other Helpers
+ #
+ # You can refer to the modules included in <tt>ActionController::Base</tt> to see
+ # other features you can bring into your metal controller.
#
- # In AbstractController, dispatching is triggered directly by calling #process on a new controller.
- # ActionController::Metal provides an #action method that returns a valid Rack application for a
- # given action. Other rack builders, such as Rack::Builder, Rack::URLMap, and the Rails router,
- # can dispatch directly to the action returned by FooController.action(:index).
class Metal < AbstractController::Base
abstract!
- attr_internal :env
+ attr_internal_writer :env
+
+ def env
+ @_env ||= {}
+ end
# Returns the last part of the controller's name, underscored, without the ending
- # "Controller". For instance, MyApp::MyPostsController would return "my_posts" for
- # controller_name
+ # <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
+ # Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well.
#
# ==== Returns
- # String
+ # * <tt>string</tt>
def self.controller_name
@controller_name ||= self.name.demodulize.sub(/Controller$/, '').underscore
end
- # Delegates to the class' #controller_name
+ # Delegates to the class' <tt>controller_name</tt>
def controller_name
self.class.controller_name
end
@@ -81,6 +134,9 @@ module ActionController
def initialize(*)
@_headers = {"Content-Type" => "text/html"}
@_status = 200
+ @_request = nil
+ @_response = nil
+ @_routes = nil
super
end
@@ -112,6 +168,11 @@ module ActionController
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
@@ -121,12 +182,11 @@ module ActionController
end
def response_body=(val)
- body = val.respond_to?(:each) ? val : [val]
+ body = val.nil? ? nil : (val.respond_to?(:each) ? val : [val])
super body
end
- # :api: private
- def dispatch(name, request)
+ def dispatch(name, request) #:nodoc:
@_request = request
@_env = request.env
@_env['action_controller.instance'] = self
@@ -134,8 +194,7 @@ module ActionController
to_a
end
- # :api: private
- def to_a
+ def to_a #:nodoc:
response ? response.to_a : [status, headers, response_body]
end
@@ -147,8 +206,8 @@ module ActionController
super
end
- def self.use(*args)
- middleware_stack.use(*args)
+ def self.use(*args, &block)
+ middleware_stack.use(*args, &block)
end
def self.middleware
@@ -164,10 +223,10 @@ module ActionController
# for the same action.
#
# ==== Parameters
- # action<#to_s>:: An action name
+ # * <tt>action</tt> - An action name
#
# ==== Returns
- # Proc:: A rack application
+ # * <tt>proc</tt> - A rack application
def self.action(name, klass = ActionDispatch::Request)
middleware_stack.build(name.to_s) do |env|
new.dispatch(name, klass.new(env))
diff --git a/actionpack/lib/action_controller/metal/compatibility.rb b/actionpack/lib/action_controller/metal/compatibility.rb
index d49465fa0b..006b9fd456 100644
--- a/actionpack/lib/action_controller/metal/compatibility.rb
+++ b/actionpack/lib/action_controller/metal/compatibility.rb
@@ -5,9 +5,6 @@ module ActionController
class ::ActionController::ActionControllerError < StandardError #:nodoc:
end
- module ClassMethods
- end
-
# Temporary hax
included do
::ActionController::UnknownAction = ::AbstractController::ActionNotFound
@@ -39,12 +36,6 @@ module ActionController
def assign_shortcuts(*) end
def _normalize_options(options)
- if options[:action] && options[:action].to_s.include?(?/)
- ActiveSupport::Deprecation.warn "Giving a path to render :action is deprecated. " <<
- "Please use render :template instead", caller
- options[:template] = options.delete(:action)
- end
-
options[:text] = nil if options.delete(:nothing) == true
options[:text] = " " if options.key?(:text) && options[:text].nil?
super
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index 61e7ece90d..a5e37172c9 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -6,7 +6,7 @@ module ActionController
include Head
# Sets the etag, last_modified, or both on the response and renders a
- # "304 Not Modified" response if the request is already fresh.
+ # <tt>304 Not Modified</tt> response if the request is already fresh.
#
# Parameters:
# * <tt>:etag</tt>
@@ -17,11 +17,11 @@ module ActionController
#
# def show
# @article = Article.find(params[:id])
- # fresh_when(:etag => @article, :last_modified => @article.created_at.utc, :public => true)
+ # 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 "304 Not Modified" response if there's a match.
+ # If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
#
def fresh_when(options)
options.assert_valid_keys(:etag, :last_modified, :public)
@@ -36,7 +36,7 @@ module ActionController
# 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 "304 Not Modified" is sent.
+ # 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>
@@ -48,7 +48,7 @@ module ActionController
# def show
# @article = Article.find(params[:id])
#
- # if stale?(:etag => @article, :last_modified => @article.created_at.utc)
+ # if stale?(:etag => @article, :last_modified => @article.created_at)
# @statistics = @article.really_expensive_call
# respond_to do |format|
# # all the supported formats
@@ -60,13 +60,13 @@ module ActionController
!request.fresh?(response)
end
- # Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a "private" instruction, so that
- # intermediate caches shouldn't cache the response.
+ # Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a <tt>private</tt> instruction, so that
+ # intermediate caches must not cache the response.
#
# Examples:
# expires_in 20.minutes
# expires_in 3.hours, :public => true
- # expires in 3.hours, 'max-stale' => 5.hours, :public => true
+ # expires_in 3.hours, 'max-stale' => 5.hours, :public => true
#
# This method will overwrite an existing Cache-Control header.
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
@@ -77,7 +77,7 @@ module ActionController
response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
end
- # Sets a HTTP 1.1 Cache-Control header of "no-cache" so no caching should occur by the browser or
+ # 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 #:doc:
response.cache_control.replace(:no_cache => true)
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index a5c9910d68..8abcad55a2 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -2,8 +2,6 @@ module ActionController
module Head
extend ActiveSupport::Concern
- include ActionController::UrlFor
-
# 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
@@ -22,13 +20,13 @@ module ActionController
location = options.delete(:location)
options.each do |key, value|
- headers[key.to_s.dasherize.split(/-/).map { |v| v.capitalize }.join("-")] = value.to_s
+ 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
- self.content_type = Mime[formats.first]
+ self.content_type = Mime[formats.first] if formats
self.response_body = " "
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
index e0bc47318a..91a88ab68a 100644
--- a/actionpack/lib/action_controller/metal/helpers.rb
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -2,21 +2,21 @@ require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/class/attribute'
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
+ # 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 in the Rails framework, creating custom helpers to
+ # In addition to using the standard template helpers provided, creating custom helpers to
# extract complicated logic or reusable functionality is strongly encouraged. By default, the controller will
# include a helper whose name matches that of the controller, e.g., <tt>MyController</tt> will automatically
# include <tt>MyHelper</tt>.
#
- # Additional helpers can be specified using the +helper+ class method in <tt>ActionController::Base</tt> or any
+ # Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
# controller which inherits from it.
#
# ==== Examples
- # The +to_s+ method from the Time class can be wrapped in a helper method to display a custom message if
- # the Time object is blank:
+ # 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="&nbsp;")
@@ -53,30 +53,20 @@ module ActionController
include AbstractController::Helpers
included do
- config_accessor :helpers_path
+ config_accessor :helpers_path, :include_all_helpers
self.helpers_path ||= []
+ self.include_all_helpers = true
end
module ClassMethods
- def helpers_dir
- ActiveSupport::Deprecation.warn "helpers_dir is deprecated, use helpers_path instead", caller
- self.helpers_path
- end
-
- def helpers_dir=(value)
- ActiveSupport::Deprecation.warn "helpers_dir= is deprecated, use helpers_path= instead", caller
- self.helpers_path = Array.wrap(value)
- end
-
# 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:
- # helper_attr :name
# attr_accessor :name
+ # helper_attr :name
#
# ==== Parameters
- # *attrs<Array[String, Symbol]>:: Names of attributes to be converted
- # into helpers.
+ # * <tt>attrs</tt> - Names of attributes to be converted into helpers.
def helper_attr(*attrs)
attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
end
@@ -88,25 +78,28 @@ module ActionController
private
# Overwrite modules_for_helpers to accept :all as argument, which loads
- # all helpers in helpers_dir.
+ # all helpers in helpers_path.
#
# ==== Parameters
- # args<Array[String, Symbol, Module, all]>:: A list of helpers
+ # * <tt>args</tt> - A list of helpers
#
# ==== Returns
- # Array[Module]:: A normalized list of modules for the list of
- # helpers provided.
+ # * <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
- # Extract helper names from files in app/helpers/**/*_helper.rb
+ # Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
def all_application_helpers
+ all_helpers_from_path(helpers_path)
+ end
+
+ def all_helpers_from_path(path)
helpers = []
- Array.wrap(helpers_path).each do |path|
- extract = /^#{Regexp.quote(path.to_s)}\/?(.*)_helper.rb$/
- helpers += Dir["#{path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
+ Array.wrap(path).each do |_path|
+ extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
+ helpers += Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
end
helpers.sort!
helpers.uniq!
diff --git a/actionpack/lib/action_controller/metal/hide_actions.rb b/actionpack/lib/action_controller/metal/hide_actions.rb
index 32d7a96701..b55c4643be 100644
--- a/actionpack/lib/action_controller/metal/hide_actions.rb
+++ b/actionpack/lib/action_controller/metal/hide_actions.rb
@@ -1,8 +1,7 @@
require 'active_support/core_ext/class/attribute'
module ActionController
- # ActionController::HideActions adds the ability to prevent public methods on a controller
- # to be called as actions.
+ # Adds the ability to prevent public methods on a controller to be called as actions.
module HideActions
extend ActiveSupport::Concern
@@ -23,7 +22,7 @@ module ActionController
# Sets all of the actions passed in as hidden actions.
#
# ==== Parameters
- # *args<#to_s>:: A list of actions
+ # * <tt>args</tt> - A list of actions
def hide_action(*args)
self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
end
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index b0eb24a4a8..39c804d707 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -3,9 +3,9 @@ require 'active_support/core_ext/object/blank'
module ActionController
module HttpAuthentication
- # Makes it dead easy to do HTTP Basic authentication.
+ # Makes it dead easy to do HTTP \Basic and \Digest authentication.
#
- # Simple Basic example:
+ # === Simple \Basic example
#
# class PostsController < ApplicationController
# USER_NAME, PASSWORD = "dhh", "secret"
@@ -29,7 +29,9 @@ module ActionController
# end
#
#
- # Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
+ # === 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
@@ -69,7 +71,7 @@ module ActionController
# assert_equal 200, status
# end
#
- # Simple Digest example:
+ # === Simple \Digest example
#
# require 'digest/md5'
# class PostsController < ApplicationController
@@ -95,18 +97,20 @@ module ActionController
# end
# end
#
- # NOTE: 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.
+ # === Notes
#
- # 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:
+ # 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.
#
- # RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
+ # 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 Basic
extend self
@@ -210,7 +214,7 @@ module ActionController
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 }.inject([]) {|a, v| a << "#{v[0]}='#{v[1]}'" }.join(', ')
+ "Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
end
def decode_credentials_header(request)
@@ -218,11 +222,10 @@ module ActionController
end
def decode_credentials(header)
- header.to_s.gsub(/^Digest\s+/,'').split(',').inject({}) do |hash, pair|
+ Hash[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
key, value = pair.split('=', 2)
- hash[key.strip.to_sym] = value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')
- hash
- end
+ [key.strip.to_sym, value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')]
+ end]
end
def authentication_header(controller, realm)
@@ -392,11 +395,11 @@ module ActionController
end
end
- # If token Authorization header is present, call the login procedure with
+ # 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
+ # login_procedure - Proc to call if a token is present. The Proc should
# take 2 arguments:
# authenticate(controller) { |token, options| ... }
#
@@ -404,7 +407,7 @@ module ActionController
# Returns nil if no token is found.
def authenticate(controller, &login_procedure)
token, options = token_and_options(controller.request)
- if !token.blank?
+ unless token.blank?
login_procedure.call(token, options)
end
end
@@ -414,20 +417,19 @@ module ActionController
# Authorization: Token token="abc", nonce="def"
# Then the returned token is "abc", and the options is {:nonce => "def"}
#
- # request - ActionController::Request instance with the current headers.
+ # 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)
if header = request.authorization.to_s[/^Token (.*)/]
- values = $1.split(',').
- inject({}) do |memo, value|
- value.strip! # remove any spaces between commas and values
- key, value = value.split(/\=\"?/) # split key=value pairs
- value.chomp!('"') # chomp trailing " in value
- value.gsub!(/\\\"/, '"') # unescape remaining quotes
- memo.update(key => value)
- end
+ values = Hash[$1.split(',').map do |value|
+ value.strip! # remove any spaces between commas and values
+ key, value = value.split(/\=\"?/) # split key=value pairs
+ value.chomp!('"') # chomp trailing " in value
+ value.gsub!(/\\\"/, '"') # unescape remaining quotes
+ [key, value]
+ end]
[values.delete("token"), values.with_indifferent_access]
end
end
@@ -439,9 +441,8 @@ module ActionController
#
# Returns String.
def encode_credentials(token, options = {})
- values = ["token=#{token.to_s.inspect}"]
- options.each do |key, value|
- values << "#{key}=#{value.to_s.inspect}"
+ values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
+ "#{key}=#{value.to_s.inspect}"
end
"Token #{values * ", "}"
end
diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb
index 282dcf66b3..cfa7004048 100644
--- a/actionpack/lib/action_controller/metal/implicit_render.rb
+++ b/actionpack/lib/action_controller/metal/implicit_render.rb
@@ -12,10 +12,10 @@ module ActionController
def method_for_action(action_name)
super || begin
- if template_exists?(action_name.to_s, _prefix)
+ if template_exists?(action_name.to_s, _prefixes)
"default_render"
end
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index b08d9a8434..dc3ea939e6 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -78,7 +78,7 @@ module ActionController
yield
end
- # Everytime after an action is processed, this method is invoked
+ # 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:
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index c6d4c6d936..a2e06fe0a6 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -63,13 +63,13 @@ module ActionController #:nodoc:
# might look something like this:
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
# end
#
# Here's the same action, with web-service support baked in:
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
#
# respond_to do |format|
# format.html
@@ -155,7 +155,7 @@ module ActionController #:nodoc:
# Respond to also allows you to specify a common block for different formats by using any:
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
#
# respond_to do |format|
# format.html
@@ -178,7 +178,7 @@ module ActionController #:nodoc:
# respond_to :html, :xml, :json
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
# respond_with(@person)
# end
# end
@@ -208,8 +208,8 @@ module ActionController #:nodoc:
# It also accepts a block to be given. It's used to overwrite a default
# response:
#
- # def destroy
- # @user = User.find(params[:id])
+ # def create
+ # @user = User.new(params[:user])
# flash[:notice] = "User was successfully created." if @user.save
#
# respond_with(@user) do |format|
@@ -227,7 +227,7 @@ module ActionController #:nodoc:
"controller responds to in the class level" if self.class.mimes_for_respond_to.empty?
if response = retrieve_response_from_mimes(&block)
- options = resources.extract_options!
+ options = resources.size == 1 ? {} : resources.extract_options!
options.merge!(:default_response => response)
(options.delete(:responder) || self.class.responder).call(self, resources, options)
end
@@ -258,9 +258,8 @@ module ActionController #:nodoc:
# nil if :not_acceptable was sent to the client.
#
def retrieve_response_from_mimes(mimes=nil, &block)
- collector = Collector.new { default_render }
mimes ||= collect_mimes_from_class_level
- mimes.each { |mime| collector.send(mime) }
+ collector = Collector.new(mimes) { default_render }
block.call(collector) if block_given?
if format = request.negotiate_mime(collector.order)
@@ -277,8 +276,9 @@ module ActionController #:nodoc:
include AbstractController::Collector
attr_accessor :order
- def initialize(&block)
+ def initialize(mimes, &block)
@order, @responses, @default_response = [], {}, block
+ mimes.each { |mime| send(mime) }
end
def any(*args, &block)
@@ -291,7 +291,7 @@ module ActionController #:nodoc:
alias :all :any
def custom(mime_type, &block)
- mime_type = mime_type.is_a?(Mime::Type) ? mime_type : Mime::Type.lookup(mime_type.to_s)
+ mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type)
@order << mime_type
@responses[mime_type] ||= block
end
diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb
index b5f1d23ef0..55c650df6c 100644
--- a/actionpack/lib/action_controller/metal/redirecting.rb
+++ b/actionpack/lib/action_controller/metal/redirecting.rb
@@ -20,6 +20,7 @@ module ActionController
# * <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>) - 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>
#
@@ -30,6 +31,7 @@ module ActionController
# 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 Moved" header unless otherwise specified.
#
@@ -39,6 +41,9 @@ module ActionController
# 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.
+ #
# It is also possible to assign a flash message as part of the redirection. There are two special accessors for commonly used the flash names
# +alert+ and +notice+ as well as a general purpose +flash+ bucket.
#
@@ -48,8 +53,7 @@ module ActionController
# redirect_to post_url(@post), :status => 301, :flash => { :updated_post_id => @post.id }
# redirect_to { :action=>'atom' }, :alert => "Something serious happened"
#
- # When using <tt>redirect_to :back</tt>, if there is no referrer,
- # RedirectBackError will be raised. You may specify some fallback
+ # When using <tt>redirect_to :back</tt>, if there is no referrer, RedirectBackError will be raised. You may specify some fallback
# behavior for this case by rescuing RedirectBackError.
def redirect_to(options = {}, response_status = {}) #:doc:
raise ActionControllerError.new("Cannot redirect to nil!") if options.nil?
@@ -83,6 +87,8 @@ module ActionController
when :back
raise RedirectBackError unless refer = request.headers["Referer"]
refer
+ when Proc
+ _compute_redirect_to_location options.call
else
url_for(options)
end.gsub(/[\r\n]/, '')
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index 0be07cd1fc..38711c8462 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -2,6 +2,7 @@ require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/object/blank'
module ActionController
+ # See <tt>Renderers.add</tt>
def self.add_renderer(key, &block)
Renderers.add(key, &block)
end
@@ -15,30 +16,12 @@ module ActionController
end
module ClassMethods
- def _write_render_options
- renderers = _renderers.map do |name, value|
- <<-RUBY_EVAL
- if options.key?(:#{name})
- _process_options(options)
- return _render_option_#{name}(options.delete(:#{name}), options)
- end
- RUBY_EVAL
- end
-
- class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- def _handle_render_options(options)
- #{renderers.join}
- end
- RUBY_EVAL
- end
-
def use_renderers(*args)
new = _renderers.dup
args.each do |key|
new[key] = RENDERERS[key]
end
self._renderers = new.freeze
- _write_render_options
end
alias use_renderer use_renderers
end
@@ -47,31 +30,69 @@ module ActionController
_handle_render_options(options) || super
end
+ def _handle_render_options(options)
+ _renderers.each do |name, value|
+ if options.key?(name.to_sym)
+ _process_options(options)
+ return send("_render_option_#{name}", options.delete(name.to_sym), options)
+ end
+ end
+ nil
+ end
+
+ # Hash of available renderers, mapping a renderer name to its proc.
+ # Default keys are :json, :js, :xml and :update.
RENDERERS = {}
+
+ # Adds a new renderer to call within controller actions.
+ # A renderer is invoked by passing its name as an option to
+ # <tt>AbstractController::Rendering#render</tt>. To create a renderer
+ # pass it a name and a block. The block takes two arguments, the first
+ # is the value paired with its key and the second is the remaining
+ # hash of options passed to +render+.
+ #
+ # === Example
+ # Create a csv renderer:
+ #
+ # ActionController::Renderers.add :csv do |obj, options|
+ # filename = options[:filename] || 'data'
+ # str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
+ # send_data str, :type => Mime::CSV,
+ # :disposition => "attachment; filename=#{filename}.csv"
+ # end
+ #
+ # Note that we used Mime::CSV for the csv mime type as it comes with Rails.
+ # For a custom renderer, you'll need to register a mime type with
+ # <tt>Mime::Type.register</tt>.
+ #
+ # To use the csv renderer in a controller action:
+ #
+ # def show
+ # @csvable = Csvable.find(params[:id])
+ # respond_to do |format|
+ # format.html
+ # format.csv { render :csv => @csvable, :filename => @csvable.name }
+ # }
+ # end
+ # To use renderers and their mime types in more concise ways, see
+ # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
+ # <tt>ActionController::MimeResponds#respond_with</tt>
def self.add(key, &block)
define_method("_render_option_#{key}", &block)
RENDERERS[key] = block
- All._write_render_options
end
module All
extend ActiveSupport::Concern
include Renderers
- INCLUDED = []
included do
self._renderers = RENDERERS
- _write_render_options
- INCLUDED << self
- end
-
- def self._write_render_options
- INCLUDED.each(&:_write_render_options)
end
end
add :json do |json, options|
- json = ActiveSupport::JSON.encode(json, options) unless json.respond_to?(:to_str)
+ json = json.to_json(options) unless json.kind_of?(String)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
self.content_type ||= Mime::JSON
self.response_body = json
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 86bb810947..32d52c84c4 100644
--- a/actionpack/lib/action_controller/metal/rendering.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -2,12 +2,11 @@ module ActionController
module Rendering
extend ActiveSupport::Concern
- include ActionController::RackDelegation
include AbstractController::Rendering
# Before processing, set the request formats in current controller formats.
def process_action(*) #:nodoc:
- self.formats = request.formats.map { |x| x.to_sym }
+ self.formats = request.formats.map { |x| x.ref }
super
end
@@ -21,36 +20,35 @@ module ActionController
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
+ # 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
- if options[:status]
- options[:status] = Rack::Utils.status_code(options[:status])
- 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
- super
+ if options[:status]
+ options[:status] = Rack::Utils.status_code(options[:status])
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)
+ super
+ end
- self.status = status if status
- self.content_type = content_type if content_type
- self.headers["Location"] = url_for(location) if location
+ # 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)
- super
- end
+ 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
index b632e7aab6..1cd93a188c 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -4,45 +4,27 @@ module ActionController #:nodoc:
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
end
- # Protecting controller actions from CSRF attacks by ensuring that all forms are coming from the current
- # web application, not a forged link from another site, is done by embedding a token based on a random
- # string stored in the session (which an attacker wouldn't know) in all forms and Ajax requests generated
- # by Rails and then verifying the authenticity of that token in the controller. Only HTML/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 anyway.
+ # 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 then 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.
#
- # This is turned on with the <tt>protect_from_forgery</tt> method, which will check the token and raise an
- # ActionController::InvalidAuthenticityToken if it doesn't match what was expected. You can customize the
- # error message in production by editing public/422.html. A call to this method in ApplicationController is
- # generated by default in post-Rails 2.0 applications.
+ # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
+ # which will check the token and raise an ActionController::InvalidAuthenticityToken
+ # if it doesn't match what was expected. A call to this method is generated for new
+ # \Rails applications by default. You can customize the error message by editing
+ # public/422.html.
#
- # The token parameter is named <tt>authenticity_token</tt> by default. If you are generating an HTML form
- # manually (without the use of Rails' <tt>form_for</tt>, <tt>form_tag</tt> or other helpers), you have to
- # include a hidden field named like that and set its value to what is returned by
- # <tt>form_authenticity_token</tt>.
- #
- # Request forgery protection is disabled by default in test environment. If you are upgrading from Rails
- # 1.x, add this to config/environments/test.rb:
- #
- # # Disable request forgery protection in test environment
- # config.action_controller.allow_forgery_protection = false
- #
- # == Learn more about CSRF (Cross-Site Request Forgery) attacks
- #
- # Here are some resources:
- # * http://isc.sans.org/diary.html?storyid=1750
- # * http://en.wikipedia.org/wiki/Cross-site_request_forgery
- #
- # Keep in mind, this is NOT a silver-bullet, plug 'n' play, warm security blanket for your rails application.
- # There are a few guidelines you should follow:
- #
- # * Keep your GET requests safe and idempotent. More reading material:
- # * http://www.xml.com/pub/a/2002/04/24/deviant.html
- # * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
- # * Make sure the session cookies that Rails creates are non-persistent. Check in Firefox and look
- # for "Expires: at end of session"
+ # 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
@@ -71,39 +53,42 @@ module ActionController #:nodoc:
# class FooController < ApplicationController
# protect_from_forgery :except => :index
#
- # # you can disable csrf protection on controller-by-controller basis:
- # skip_before_filter :verify_authenticity_token
- # end
+ # You can disable csrf protection on controller-by-controller basis:
+ #
+ # skip_before_filter :verify_authenticity_token
+ #
+ # It can also be disabled for specific controller actions:
+ #
+ # skip_before_filter :verify_authenticity_token, :except => [:create]
#
# Valid Options:
#
# * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call. Set which actions are verified.
def protect_from_forgery(options = {})
self.request_forgery_protection_token ||= :authenticity_token
- before_filter :verify_authenticity_token, options
+ prepend_before_filter :verify_authenticity_token, options
end
end
protected
-
- def protect_from_forgery(options = {})
- self.request_forgery_protection_token ||= :authenticity_token
- before_filter :verify_authenticity_token, options
- end
-
# The actual before_filter that is used. Modify this to change how you handle unverified requests.
def verify_authenticity_token
- verified_request? || raise(ActionController::InvalidAuthenticityToken)
+ verified_request? || handle_unverified_request
+ end
+
+ def handle_unverified_request
+ reset_session
end
# Returns true or false if a request is verified. Checks:
#
- # * is the format restricted? By default, only HTML requests are checked.
# * is it a GET request? Gets should be safe and idempotent
# * Does the form_authenticity_token match the given token value from the params?
+ # * Does the X-CSRF-Token header match the form_authenticity_token
def verified_request?
- !protect_against_forgery? || request.forgery_whitelisted? ||
- form_authenticity_token == params[request_forgery_protection_token]
+ !protect_against_forgery? || request.get? ||
+ form_authenticity_token == params[request_forgery_protection_token] ||
+ form_authenticity_token == request.headers['X-CSRF-Token']
end
# Sets the token value for the current session.
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index cb644dfd16..4b45413cf8 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -1,7 +1,7 @@
require 'active_support/json'
module ActionController #:nodoc:
- # Responder is responsible for exposing a resource to different mime requests,
+ # 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:
#
@@ -24,10 +24,10 @@ module ActionController #:nodoc:
#
# === Builtin HTTP verb semantics
#
- # The default Rails responder holds semantics for each HTTP verb. Depending on the
+ # 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
+ # Using \Rails default responder, a POST request for creating an object could
# be written as:
#
# def create
@@ -77,8 +77,6 @@ module ActionController #:nodoc:
#
# respond_with(@project, :manager, @task)
#
- # Check <code>polymorphic_url</code> documentation for more examples.
- #
class Responder
attr_reader :controller, :request, :format, :resource, :resources, :options
@@ -89,6 +87,8 @@ module ActionController #:nodoc:
def initialize(controller, resources, options={})
@controller = controller
+ @request = @controller.request
+ @format = @controller.formats.first
@resource = resources.last
@resources = resources
@options = options
@@ -99,14 +99,6 @@ module ActionController #:nodoc:
delegate :head, :render, :redirect_to, :to => :controller
delegate :get?, :post?, :put?, :delete?, :to => :request
- def request
- @request ||= @controller.request
- end
-
- def format
- @format ||= @controller.formats.first
- end
-
# 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)
@@ -121,7 +113,7 @@ module ActionController #:nodoc:
# Main entry point for responder responsible to dispatch to the proper format.
#
def respond
- method = :"to_#{format}"
+ method = "to_#{format}"
respond_to?(method) ? send(method) : to_format
end
@@ -146,7 +138,7 @@ module ActionController #:nodoc:
protected
- # This is the common behavior for "navigation" requests, like :html, :iphone and so forth.
+ # This is the common behavior for formats associated with browsing, like :html, :iphone and so forth.
def navigation_behavior(error)
if get?
raise error
@@ -157,7 +149,7 @@ module ActionController #:nodoc:
end
end
- # This is the common behavior for "API" requests, like :xml and :json.
+ # This is the common behavior for formats associated with APIs, such as :xml and :json.
def api_behavior(error)
raise error unless resourceful?
@@ -167,6 +159,8 @@ module ActionController #:nodoc:
display resource.errors, :status => :unprocessable_entity
elsif post?
display resource, :status => :created, :location => api_location
+ elsif has_empty_resource_definition?
+ display empty_resource, :status => :ok
else
head :ok
end
@@ -175,7 +169,7 @@ module ActionController #:nodoc:
# Checks whether the resource responds to the current format or not.
#
def resourceful?
- resource.respond_to?(:"to_#{format}")
+ resource.respond_to?("to_#{format}")
end
# Returns the resource location by retrieving it from the options or
@@ -227,5 +221,23 @@ module ActionController #:nodoc:
def default_action
@action ||= ACTIONS_FOR_VERBS[request.request_method_symbol]
end
+
+ # Check whether resource needs a specific definition of empty resource to be valid
+ #
+ def has_empty_resource_definition?
+ respond_to?("empty_#{format}_resource")
+ end
+
+ # Delegate to proper empty resource method
+ #
+ def empty_resource
+ send("empty_#{format}_resource")
+ end
+
+ # Return a valid empty JSON resource
+ #
+ def empty_json_resource
+ "{}"
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb
index d75b46dace..312dc8eb3e 100644
--- a/actionpack/lib/action_controller/metal/streaming.rb
+++ b/actionpack/lib/action_controller/metal/streaming.rb
@@ -69,10 +69,6 @@ module ActionController #:nodoc:
options[:filename] ||= File.basename(path) unless options[:url_based_filename]
send_file_headers! options
- if options[:x_sendfile]
- ActiveSupport::Deprecation.warn(":x_sendfile is no longer needed in send_file", caller)
- end
-
self.status = options[:status] || 200
self.content_type = options[:content_type] if options.key?(:content_type)
self.response_body = File.open(path, "rb")
@@ -105,10 +101,6 @@ module ActionController #:nodoc:
# send_data image.data, :type => image.content_type, :disposition => 'inline'
#
# See +send_file+ for more information on HTTP Content-* headers and caching.
- #
- # <b>Tip:</b> if you want to stream large amounts of on-the-fly generated
- # data to the browser, then use <tt>render :text => proc { ... }</tt>
- # instead. See ActionController::Base#render for more information.
def send_data(data, options = {}) #:doc:
send_file_headers! options.dup
render options.slice(:status, :content_type).merge(:text => data)
@@ -121,10 +113,6 @@ module ActionController #:nodoc:
raise ArgumentError, ":#{arg} option required" if options[arg].nil?
end
- if options.key?(:length)
- ActiveSupport::Deprecation.warn("You do not need to provide the file's length", caller)
- end
-
disposition = options[:disposition]
disposition += %(; filename="#{options[:filename]}") if options[:filename]
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index 4b8c452d50..f4efeb33ba 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -14,18 +14,9 @@ module ActionController
cookies.write(@_response)
end
@_response.prepare!
- set_test_assigns
ret
end
- def set_test_assigns
- @assigns = {}
- (instance_variable_names - self.class.protected_instance_variables).each do |var|
- name, value = var[1..-1], instance_variable_get(var)
- @assigns[name] = value
- end
- end
-
# TODO : Rewrite tests using controller.headers= to use Rack env
def headers=(new_headers)
@_response ||= ActionDispatch::Response.new
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index a51fc5b8e4..6fc0cf1fb8 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -2,27 +2,25 @@ module ActionController
module UrlFor
extend ActiveSupport::Concern
- include ActionDispatch::Routing::UrlFor
+ include AbstractController::UrlFor
def url_options
- super.reverse_merge(
- :host => request.host_with_port,
+ @_url_options ||= super.reverse_merge(
+ :host => request.host,
+ :port => request.optional_port,
:protocol => request.protocol,
:_path_segments => request.symbolized_path_parameters
- ).merge(:script_name => request.script_name)
- end
-
- def _routes
- raise "In order to use #url_for, you must include routing helpers explicitly. " \
- "For instance, `include Rails.application.routes.url_helpers"
- end
+ ).freeze
- module ClassMethods
- def action_methods
- @action_methods ||= begin
- super - _routes.named_routes.helper_names
+ if _routes.equal?(env["action_dispatch.routes"])
+ @_url_options.dup.tap do |options|
+ options[:script_name] = request.script_name.dup
+ 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
index 2115b07b3e..437fec3dc6 100644
--- a/actionpack/lib/action_controller/middleware.rb
+++ b/actionpack/lib/action_controller/middleware.rb
@@ -31,7 +31,7 @@ module ActionController
super()
@_app = app
end
-
+
def index
call(env)
end
diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb
index cd2dfafbe6..f0c29825ba 100644
--- a/actionpack/lib/action_controller/railtie.rb
+++ b/actionpack/lib/action_controller/railtie.rb
@@ -2,35 +2,13 @@ require "rails"
require "action_controller"
require "action_dispatch/railtie"
require "action_view/railtie"
-require "active_support/deprecation/proxy_wrappers"
-require "active_support/deprecation"
+require "abstract_controller/railties/routes_helpers"
+require "action_controller/railties/paths"
module ActionController
class Railtie < Rails::Railtie
config.action_controller = ActiveSupport::OrderedOptions.new
- config.action_controller.singleton_class.tap do |d|
- d.send(:define_method, :session) do
- ActiveSupport::Deprecation.warn "config.action_controller.session has been deprecated. " <<
- "Please use Rails.application.config.session_store instead.", caller
- end
-
- d.send(:define_method, :session=) do |val|
- ActiveSupport::Deprecation.warn "config.action_controller.session= has been deprecated. " <<
- "Please use config.session_store(name, options) instead.", caller
- end
-
- d.send(:define_method, :session_store) do
- ActiveSupport::Deprecation.warn "config.action_controller.session_store has been deprecated. " <<
- "Please use Rails.application.config.session_store instead.", caller
- end
-
- d.send(:define_method, :session_store=) do |val|
- ActiveSupport::Deprecation.warn "config.action_controller.session_store= has been deprecated. " <<
- "Please use config.session_store(name, options) instead.", caller
- end
- end
-
initializer "action_controller.logger" do
ActiveSupport.on_load(:action_controller) { self.logger ||= Rails.logger }
end
@@ -43,24 +21,27 @@ module ActionController
paths = app.config.paths
options = app.config.action_controller
- options.assets_dir ||= paths.public.to_a.first
- options.javascripts_dir ||= paths.public.javascripts.to_a.first
- options.stylesheets_dir ||= paths.public.stylesheets.to_a.first
- options.page_cache_directory ||= paths.public.to_a.first
- options.helpers_path ||= paths.app.helpers.to_a
+ options.assets_dir ||= paths["public"].first
+ options.javascripts_dir ||= paths["public/javascripts"].first
+ options.stylesheets_dir ||= paths["public/stylesheets"].first
+ options.page_cache_directory ||= paths["public"].first
+
+ # make sure readers methods get compiled
+ options.asset_path ||= app.config.asset_path
+ options.asset_host ||= app.config.asset_host
ActiveSupport.on_load(:action_controller) do
- include app.routes.url_helpers
+ include app.routes.mounted_helpers
+ extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
+ extend ::ActionController::Railties::Paths.with(app)
options.each { |k,v| send("#{k}=", v) }
end
end
- initializer "action_controller.deprecated_routes" do |app|
- message = "ActionController::Routing::Routes is deprecated. " \
- "Instead, use Rails.application.routes"
-
- proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
- ActionController::Routing::Routes = proxy
+ 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 \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb
new file mode 100644
index 0000000000..dce3c2fe88
--- /dev/null
+++ b/actionpack/lib/action_controller/railties/paths.rb
@@ -0,0 +1,32 @@
+module ActionController
+ module Railties
+ module Paths
+ def self.with(app)
+ Module.new do
+ define_method(:inherited) do |klass|
+ super(klass)
+
+ if namespace = klass.parents.detect {|m| m.respond_to?(:_railtie) }
+ paths = namespace._railtie.paths["app/helpers"].existent
+ else
+ paths = app.config.helpers_paths
+ end
+
+ klass.helpers_path = paths
+ if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
+ klass.helper :all
+ end
+
+ if app.config.serve_static_assets && namespace
+ paths = namespace._railtie.config.paths
+
+ klass.config.assets_dir = paths["public"].first
+ klass.config.javascripts_dir = paths["public/javascripts"].first
+ klass.config.stylesheets_dir = paths["public/stylesheets"].first
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index e306697f4b..bc4f8bb9ce 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -1,6 +1,7 @@
require 'rack/session/abstract/id'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/class/attribute'
module ActionController
module TemplateAssertions
@@ -40,6 +41,13 @@ module ActionController
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.
#
# ==== Examples
@@ -127,7 +135,7 @@ module ActionController
class Result < ::Array #:nodoc:
def to_s() join '/' end
def self.new_escaped(strings)
- new strings.collect {|str| URI.unescape str}
+ new strings.collect {|str| uri_parser.unescape str}
end
end
@@ -164,9 +172,14 @@ module ActionController
end
def recycle!
+ write_cookies!
+ @env.delete('HTTP_COOKIE') if @cookies.blank?
+ @env.delete('action_dispatch.cookies')
+ @cookies = nil
@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 = nil
@env['action_dispatch.request.query_parameters'] = {}
@@ -186,20 +199,23 @@ module ActionController
end
end
- class TestSession < ActionDispatch::Session::AbstractStore::SessionHash #:nodoc:
- DEFAULT_OPTIONS = ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS
+ class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
+ DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
def initialize(session = {})
+ @env, @by = nil, nil
replace(session.stringify_keys)
@loaded = true
end
- def exists?; true; end
+ def exists?
+ true
+ 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 ActionController::IntegrationTest), which are more like
+ # integration tests (see ActionDispatch::IntegrationTest), which are more like
# "stories" that can involve multiple controllers and multiple actions (i.e. multiple
# different HTTP requests).
#
@@ -244,7 +260,7 @@ module ActionController
# 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
+ # (Earlier versions of \Rails required each functional test to subclass
# Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
#
# == Controller is automatically inferred
@@ -257,7 +273,7 @@ module ActionController
# tests WidgetController
# end
#
- # == Testing controller internals
+ # == \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:
@@ -265,7 +281,7 @@ module ActionController
# * 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.
+ # * cookies: \Cookies being sent to the user on this request.
#
# These collections can be used just like any other hash:
#
@@ -289,9 +305,13 @@ module ActionController
# and cookies, though. For sessions, you just do:
#
# @request.session[:key] = "value"
- # @request.cookies["key"] = "value"
+ # @request.cookies[:key] = "value"
+ #
+ # To clear the cookies for a test just clear the request's cookies hash:
+ #
+ # @request.cookies.clear
#
- # == Testing named routes
+ # == \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.
# Example:
@@ -311,14 +331,14 @@ module ActionController
def tests(controller_class)
self.controller_class = controller_class
end
-
+
def controller_class=(new_class)
prepare_controller_class(new_class) if new_class
- write_inheritable_attribute(:controller_class, new_class)
+ self._controller_class = new_class
end
def controller_class
- if current_controller_class = read_inheritable_attribute(:controller_class)
+ if current_controller_class = self._controller_class
current_controller_class
else
self.controller_class = determine_default_controller_class(name)
@@ -393,16 +413,18 @@ module ActionController
parameters ||= {}
@request.assign_parameters(@routes, @controller.class.name.underscore.sub(/_controller$/, ''), action.to_s, parameters)
- @request.session = ActionController::TestSession.new(session) unless session.nil?
+ @request.session = ActionController::TestSession.new(session) if session
@request.session["flash"] = @request.flash.update(flash || {})
@request.session["flash"].sweep
@controller.request = @request
@controller.params.merge!(parameters)
build_request_uri(action, parameters)
- Base.class_eval { include Testing }
+ @controller.class.class_eval { include Testing }
@controller.process_with_new_base_test(@request, @response)
+ @assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
@request.session.delete('flash') if @request.session['flash'].blank?
+ @request.cookies.merge!(@response.cookies)
@response
end
@@ -416,7 +438,7 @@ module ActionController
@request.env.delete('PATH_INFO')
- if @controller
+ if defined?(@controller) && @controller
@controller.request = @request
@controller.params = {}
end
@@ -430,6 +452,7 @@ module ActionController
included do
include ActionController::TemplateAssertions
include ActionDispatch::Assertions
+ class_attribute :_controller_class
setup :setup_controller_request_and_response
end
@@ -437,7 +460,7 @@ module ActionController
def build_request_uri(action, parameters)
unless @request.env["PATH_INFO"]
- options = @controller.__send__(:url_options).merge(parameters)
+ options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
options.update(
:only_path => true,
:action => action,
@@ -461,9 +484,11 @@ module ActionController
# The exception is stored in the exception accessor for further inspection.
module RaiseActionExceptions
def self.included(base)
- base.class_eval do
- attr_accessor :exception
- protected :exception, :exception=
+ unless base.method_defined?(:exception) && base.method_defined?(:exception=)
+ base.class_eval do
+ attr_accessor :exception
+ protected :exception, :exception=
+ end
end
end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
index b8d73c350d..7fa3aead82 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
@@ -48,7 +48,7 @@ EOF
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.
@@ -62,7 +62,7 @@ EOF
def find_all(conditions)
@root.find_all(conditions)
end
-
+
end
end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
index a874519978..22b3243104 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
@@ -1,7 +1,7 @@
require 'strscan'
module HTML #:nodoc:
-
+
class Conditions < Hash #:nodoc:
def initialize(hash)
super()
@@ -18,14 +18,14 @@ module HTML #:nodoc:
hash[k] = Conditions.new(v)
when :children
hash[k] = v = keys_to_symbols(v)
- v.each do |k,v2|
- case k
+ v.each do |key,value|
+ case key
when :count, :greater_than, :less_than
# keys are valid, and require no further processing
when :only
- v[k] = Conditions.new(v2)
+ v[key] = Conditions.new(value)
else
- raise "illegal key #{k.inspect} => #{v2.inspect}"
+ raise "illegal key #{key.inspect} => #{value.inspect}"
end
end
else
@@ -38,18 +38,14 @@ module HTML #:nodoc:
private
def keys_to_strings(hash)
- hash.keys.inject({}) do |h,k|
- h[k.to_s] = hash[k]
- h
- end
+ Hash[hash.keys.map {|k| [k.to_s, hash[k]]}]
end
def keys_to_symbols(hash)
- hash.keys.inject({}) do |h,k|
+ Hash[hash.keys.map do |k|
raise "illegal key #{k.inspect}" unless k.respond_to?(:to_sym)
- h[k.to_sym] = hash[k]
- h
- end
+ [k.to_sym, hash[k]]
+ end]
end
end
@@ -57,17 +53,17 @@ module HTML #:nodoc:
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
@@ -77,9 +73,7 @@ module HTML #:nodoc:
# Return a textual representation of the node.
def to_s
- s = ""
- @children.each { |child| s << child.to_s }
- s
+ @children.join()
end
# Return false (subclasses must override this to provide specific matching
@@ -92,7 +86,7 @@ module HTML #:nodoc:
# returns non +nil+. Returns the result of the #find call that succeeded.
def find(conditions)
conditions = validate_conditions(conditions)
- @children.each do |child|
+ @children.each do |child|
node = child.find(conditions)
return node if node
end
@@ -133,7 +127,7 @@ module HTML #:nodoc:
equivalent
end
-
+
class <<self
def parse(parent, line, pos, content, strict=true)
if content !~ /^<\S/
@@ -160,11 +154,11 @@ module HTML #:nodoc:
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(/[\w:-]+/)
name.downcase!
-
+
unless closing
scanner.skip(/\s*/)
attributes = {}
@@ -191,13 +185,13 @@ module HTML #:nodoc:
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})"
+ 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
@@ -212,9 +206,9 @@ module HTML #:nodoc:
# 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)
@@ -240,7 +234,7 @@ module HTML #:nodoc:
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)
@@ -268,7 +262,7 @@ module HTML #:nodoc:
content == node.content
end
end
-
+
# A CDATA node is simply a text node with a specialized way of displaying
# itself.
class CDATA < Text #:nodoc:
@@ -281,16 +275,16 @@ module HTML #:nodoc:
# 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.
@@ -344,7 +338,7 @@ module HTML #:nodoc:
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):
@@ -404,7 +398,7 @@ module HTML #:nodoc:
# 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" } }
+ # 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
@@ -439,7 +433,7 @@ module HTML #:nodoc:
# 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
@@ -457,13 +451,13 @@ module HTML #:nodoc:
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
@@ -489,24 +483,24 @@ module HTML #:nodoc:
self_index = siblings.index(self)
if conditions[:sibling]
- return false unless siblings.detect do |s|
+ 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|
+ 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|
+ return false unless siblings[0,self_index].detect do |s|
s != self && s.match(conditions[:after])
end
end
end
-
+
true
end
@@ -515,7 +509,7 @@ module HTML #:nodoc:
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)
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
index 51e0868995..09dd08898c 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
@@ -1,5 +1,5 @@
require 'set'
-require 'active_support/core_ext/class/inheritable_attributes'
+require 'active_support/core_ext/class/attribute'
module HTML
class Sanitizer
@@ -7,11 +7,11 @@ module HTML
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)
@@ -22,12 +22,12 @@ module HTML
end
result
end
-
+
def process_node(node, result, options)
result << node.to_s
end
end
-
+
class FullSanitizer < Sanitizer
def sanitize(text, options = {})
result = super
@@ -37,12 +37,12 @@ module HTML
# 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))
@@ -50,51 +50,51 @@ module HTML
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)
+ 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_inheritable_accessor attr, :instance_writer => false
+ 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 = /:|(&#0*58)|(&#x70)|(%|&#37;)3A/
-
+
# 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 &lt;font&gt;
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
+ 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
+ # 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
+ 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 keywords 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
+ 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
@@ -118,9 +118,9 @@ module HTML
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)
+ elsif shorthand_css_properties.include?(prop.split('-')[0].downcase)
unless val.split().any? do |keyword|
- !allowed_css_keywords.include?(keyword) &&
+ !allowed_css_keywords.include?(keyword) &&
keyword !~ /^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$/
end
clean << prop + ': ' + val + ';'
@@ -146,7 +146,7 @@ module HTML
else
options[:parent].unshift node.name
end
-
+
process_attributes_for node, options
options[:tags].include?(node.name) ? node : nil
@@ -154,7 +154,7 @@ module HTML
bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "&lt;")
end
end
-
+
def process_attributes_for(node, options)
return unless node.attributes
node.attributes.keys.each do |attr_name|
@@ -169,8 +169,8 @@ module HTML
end
def contains_bad_protocols?(attr_name, value)
- uri_attributes.include?(attr_name) &&
- (value =~ /(^[^\/:]*):|(&#0*58)|(&#x70)|(%|&#37;)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first))
+ uri_attributes.include?(attr_name) &&
+ (value =~ /(^[^\/:]*):|(&#0*58)|(&#x70)|(%|&#37;)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first.downcase))
end
end
end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb
index e2c49c284f..0fe2e6d1a6 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb
@@ -182,7 +182,7 @@ module HTML
# 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.
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
index 240dc1890f..c252e01cf5 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
@@ -1,7 +1,7 @@
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.
#
@@ -14,13 +14,13 @@ module HTML #:nodoc:
# 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! if text.encoding_aware?
@@ -42,7 +42,7 @@ module HTML #:nodoc:
update_current_line(scan_text)
end
end
-
+
private
# Treat the text at the current position as a tag, and scan it. Supports
@@ -69,13 +69,13 @@ module HTML #:nodoc:
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
@@ -103,5 +103,5 @@ module HTML #:nodoc:
text
end
end
-
+
end
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index aeec934be8..49971fc9f8 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -53,6 +53,7 @@ module ActionDispatch
autoload :Flash
autoload :Head
autoload :ParamsParser
+ autoload :Reloader
autoload :RemoteIp
autoload :Rescue
autoload :ShowExceptions
@@ -85,6 +86,7 @@ module ActionDispatch
autoload_under 'testing' do
autoload :Assertions
autoload :Integration
+ autoload :IntegrationTest, 'action_dispatch/testing/integration'
autoload :PerformanceTest
autoload :TestProcess
autoload :TestRequest
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index e9fdf75cc8..4f4cb96a74 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -39,10 +39,11 @@ module ActionDispatch
end
module Response
- attr_reader :cache_control
+ attr_reader :cache_control, :etag
+ alias :etag? :etag
def initialize(*)
- status, header, body = super
+ super
@cache_control = {}
@etag = self["ETag"]
@@ -50,8 +51,7 @@ module ActionDispatch
if cache_control = self["Cache-Control"]
cache_control.split(/,\s*/).each do |segment|
first, last = segment.split("=")
- last ||= true
- @cache_control[first.to_sym] = last
+ @cache_control[first.to_sym] = last || true
end
end
end
@@ -70,14 +70,6 @@ module ActionDispatch
headers['Last-Modified'] = utc_time.httpdate
end
- def etag
- @etag
- end
-
- def etag?
- @etag
- end
-
def etag=(etag)
key = ActiveSupport::Cache.expand_cache_key(etag)
@etag = self["ETag"] = %("#{Digest::MD5.hexdigest(key)}")
@@ -88,38 +80,19 @@ module ActionDispatch
def handle_conditional_get!
if etag? || last_modified? || !@cache_control.empty?
set_conditional_cache_control!
- elsif nonempty_ok_response?
- self.etag = body
-
- if request && request.etag_matches?(etag)
- self.status = 304
- self.body = []
- end
-
- set_conditional_cache_control!
- else
- headers["Cache-Control"] = "no-cache"
end
end
- def nonempty_ok_response?
- @status == 200 && string_body?
- end
-
- def string_body?
- !@blank && @body.respond_to?(:all?) && @body.all? { |part| part.is_a?(String) }
- end
-
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate"
def set_conditional_cache_control!
- control = @cache_control
-
return if self["Cache-Control"].present?
+ control = @cache_control
+
if control.empty?
headers["Cache-Control"] = DEFAULT_CACHE_CONTROL
- elsif @cache_control[:no_cache]
+ elsif control[:no_cache]
headers["Cache-Control"] = "no-cache"
else
extras = control[:extras]
diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb
index 1ab48ae04d..8dd1af7f3d 100644
--- a/actionpack/lib/action_dispatch/http/filter_parameters.rb
+++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb
@@ -5,10 +5,10 @@ require 'active_support/core_ext/object/duplicable'
module ActionDispatch
module Http
# Allows you to specify sensitive parameters which will be replaced from
- # the request log by looking in all subhashes of the param hash for keys
- # to filter. If a block is given, each key and value of the parameter
- # hash and all subhashes is passed to it, the value or key can be replaced
- # using String#replace or similar method.
+ # 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.
#
# Examples:
#
@@ -38,6 +38,11 @@ module ActionDispatch
@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
@@ -52,6 +57,14 @@ module ActionDispatch
@@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/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index 4082770b85..68ba1a81b5 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -32,23 +32,25 @@ module ActionDispatch
end
end
- # Returns the Mime type for the \format used in the request.
+ # 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 depending on the value of <tt>ActionController::Base.use_accept_header</tt>
+ # GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first
#
def format(view_path = [])
formats.first
end
+ BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
+
def formats
accept = @env['HTTP_ACCEPT']
@env["action_dispatch.request.formats"] ||=
if parameters[:format]
Array(Mime[parameters[:format]])
- elsif xhr? || (accept && accept !~ /,\s*\*\/\*/)
+ elsif xhr? || (accept && accept !~ BROWSER_LIKE_ACCEPTS)
accepts
else
[Mime::HTML]
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index c6fc582851..7c9ebe7c7b 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -80,6 +80,9 @@ module Mime
end
class << self
+
+ TRAILING_STAR_REGEXP = /(text|application)\/\*/
+
def lookup(string)
LOOKUP[string]
end
@@ -105,15 +108,28 @@ module Mime
def parse(accept_header)
if accept_header !~ /,/
- [Mime::Type.lookup(accept_header)]
+ if accept_header =~ TRAILING_STAR_REGEXP
+ parse_data_with_trailing_star($1)
+ else
+ [Mime::Type.lookup(accept_header)]
+ end
else
# keep track of creation order to keep the subsequent sort stable
- list = []
- accept_header.split(/,/).each_with_index do |header, index|
- params, q = header.split(/;\s*q=/)
- if params
- params.strip!
- list << AcceptItem.new(index, params, q) unless params.empty?
+ list, index = [], 0
+ accept_header.split(/,/).each do |header|
+ params, q = header.split(/;\s*q=/)
+ if params.present?
+ params.strip!
+
+ if params =~ TRAILING_STAR_REGEXP
+ parse_data_with_trailing_star($1).each do |m|
+ list << AcceptItem.new(index, m.to_s, q)
+ index += 1
+ end
+ else
+ list << AcceptItem.new(index, params, q)
+ index += 1
+ end
end
end
list.sort!
@@ -160,23 +176,51 @@ module Mime
list
end
end
+
+ # input: 'text'
+ # returned value: [Mime::JSON, Mime::XML, Mime::ICS, Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]
+ #
+ # input: 'application'
+ # returned value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]
+ 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.to_s.upcase
+ mime = Mime.const_get(symbol)
+ Mime.instance_eval { remove_const(symbol) }
+
+ SET.delete_if { |v| v.eql?(mime) }
+ LOOKUP.delete_if { |k,v| v.eql?(mime) }
+ EXTENSION_LOOKUP.delete_if { |k,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 || @string.to_sym
+ @symbol
+ end
+
+ def ref
+ to_sym || to_s
end
def ===(list)
@@ -186,11 +230,11 @@ module Mime
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
+ (@synonyms + [ self ]).any? do |synonym|
+ synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
end
end
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
index add8cab2ab..ef5d207b26 100644
--- a/actionpack/lib/action_dispatch/http/parameters.rb
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -15,14 +15,14 @@ module ActionDispatch
alias :params :parameters
def path_parameters=(parameters) #:nodoc:
- @env.delete("action_dispatch.request.symbolized_path_parameters")
+ @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
- @env["action_dispatch.request.symbolized_path_parameters"] ||= path_parameters.symbolize_keys
+ @symbolized_path_params ||= path_parameters.symbolize_keys
end
# Returns a hash with the \parameters used to form the \path of the request.
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 0000000000..b5c1435903
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/rack_cache.rb
@@ -0,0 +1,58 @@
+require "rack/cache"
+require "rack/cache/context"
+require "active_support/cache"
+
+module ActionDispatch
+ class RailsMetaStore < Rack::Cache::MetaStore
+ def self.resolve(uri)
+ new
+ end
+
+ # TODO: Finally deal with the RAILS_CACHE global
+ def initialize(store = RAILS_CACHE)
+ @store = store
+ end
+
+ def read(key)
+ @store.read(key) || []
+ end
+
+ def write(key, value)
+ @store.write(key, 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
index fd23b1df79..f07ac44f7a 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -2,8 +2,10 @@ require 'tempfile'
require 'stringio'
require 'strscan'
+require 'active_support/core_ext/module/deprecation'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/string/access'
+require 'active_support/inflector'
require 'action_dispatch/http/headers'
module ActionDispatch
@@ -15,6 +17,8 @@ module ActionDispatch
include ActionDispatch::Http::Upload
include ActionDispatch::Http::URL
+ LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze
+
%w[ AUTH_TYPE GATEWAY_INTERFACE
PATH_TRANSLATED REMOTE_HOST
REMOTE_IDENT REMOTE_USER REMOTE_ADDR
@@ -42,8 +46,24 @@ module ActionDispatch
@env.key?(key)
end
- HTTP_METHODS = %w(get head put post delete options)
- HTTP_METHOD_LOOKUP = HTTP_METHODS.inject({}) { |h, m| h[m] = h[m.upcase] = m.to_sym; h }
+ # 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 = Hash.new { |h, m| h[m] = m.underscore.to_sym if HTTP_METHODS.include?(m) }
# Returns the HTTP \method that the application should see.
# In the case where the \method was overridden by a middleware
@@ -52,11 +72,7 @@ module ActionDispatch
# the application should use), this \method returns the overridden
# value, not the original.
def request_method
- @request_method ||= begin
- method = env["REQUEST_METHOD"]
- HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
- method
- end
+ @request_method ||= check_method(env["REQUEST_METHOD"])
end
# Returns a symbol form of the #request_method
@@ -68,11 +84,7 @@ module ActionDispatch
# even if it was overridden by middleware. See #request_method for
# more information.
def method
- @method ||= begin
- method = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
- HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
- method
- end
+ @method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])
end
# Returns a symbol form of the #method
@@ -122,8 +134,9 @@ module ActionDispatch
end
def forgery_whitelisted?
- get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request?
+ get?
end
+ deprecate :forgery_whitelisted? => "it is just an alias for 'get?' now, update your code"
def media_type
content_mime_type.to_s
@@ -134,11 +147,11 @@ module ActionDispatch
super.to_i
end
- # Returns true if the request's "X-Requested-With" header contains
- # "XMLHttpRequest". (The Prototype Javascript library sends this header with
- # every Ajax request.)
+ # 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)
+ @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i
end
alias :xhr? :xml_http_request?
@@ -147,8 +160,16 @@ module ActionDispatch
end
# Which IP addresses are "trusted proxies" that can be stripped from
- # the right-hand-side of X-Forwarded-For
- TRUSTED_PROXIES = /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\./i
+ # the right-hand-side of X-Forwarded-For.
+ #
+ # http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces.
+ TRUSTED_PROXIES = %r{
+ ^127\.0\.0\.1$ | # localhost
+ ^(10 | # private IP 10.x.x.x
+ 172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255
+ 192\.168 # private IP 192.168.x.x
+ )\.
+ }x
# Determines originating IP address. REMOTE_ADDR is the standard
# but will fail if the user is behind a proxy. HTTP_CLIENT_IP and/or
@@ -197,7 +218,7 @@ module ActionDispatch
# TODO This should be broken apart into AD::Request::Session and probably
# be included by the session middleware.
def reset_session
- session.destroy if session
+ session.destroy if session && session.respond_to?(:destroy)
self.session = {}
@env['action_dispatch.request.flash_hash'] = nil
end
@@ -212,13 +233,13 @@ module ActionDispatch
# Override Rack's GET method to support indifferent access
def GET
- @env["action_dispatch.request.query_parameters"] ||= normalize_parameters(super)
+ @env["action_dispatch.request.query_parameters"] ||= (normalize_parameters(super) || {})
end
alias :query_parameters :GET
# Override Rack's POST method to support indifferent access
def POST
- @env["action_dispatch.request.request_parameters"] ||= normalize_parameters(super)
+ @env["action_dispatch.request.request_parameters"] ||= (normalize_parameters(super) || {})
end
alias :request_parameters :POST
@@ -231,5 +252,17 @@ module ActionDispatch
@env['X_HTTP_AUTHORIZATION'] ||
@env['REDIRECT_X_HTTP_AUTHORIZATION']
end
+
+ # True if the request came from localhost, 127.0.0.1.
+ def local?
+ LOCALHOST.any? { |local_ip| local_ip === remote_addr && local_ip === remote_ip }
+ 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
index 3b85a98576..8e03a7879f 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -4,27 +4,26 @@ require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/class/attribute_accessors'
module ActionDispatch # :nodoc:
- # Represents an HTTP response generated by a controller action. One can use
- # an ActionDispatch::Response object to retrieve the current state
- # of the response, or customize the response. An Response object can
- # either represent a "real" HTTP response (i.e. one that is meant to be sent
- # back to the web browser) or a test response (i.e. one that is generated
- # from integration tests). See CgiResponse and TestResponse, respectively.
+ # 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 implement detail, and
+ # \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
+ # 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).
+ # TestResponse (which are of course also of type \Response).
#
- # For example, the following demo integration "test" prints the body of the
+ # For example, the following demo integration test prints the body of the
# controller response to the console:
#
# class DemoControllerTest < ActionDispatch::IntegrationTest
@@ -45,8 +44,8 @@ module ActionDispatch # :nodoc:
@block = nil
@length = 0
- @status, @header = status, header
- self.body = body
+ @header = header
+ self.body, self.status = body, status
@cookie = []
@sending_file = false
@@ -133,7 +132,7 @@ module ActionDispatch # :nodoc:
# information.
attr_accessor :charset, :content_type
- CONTENT_TYPE = "Content-Type"
+ CONTENT_TYPE = "Content-Type"
cattr_accessor(:default_charset) { "utf-8" }
@@ -141,7 +140,6 @@ module ActionDispatch # :nodoc:
assign_default_content_type_and_charset!
handle_conditional_get!
self["Set-Cookie"] = self["Set-Cookie"].join("\n") if self["Set-Cookie"].respond_to?(:join)
- self["ETag"] = @_etag if @_etag
super
end
diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb
index 8ee4b81cdd..37effade4f 100644
--- a/actionpack/lib/action_dispatch/http/upload.rb
+++ b/actionpack/lib/action_dispatch/http/upload.rb
@@ -1,32 +1,34 @@
-require 'active_support/core_ext/object/blank'
-
module ActionDispatch
module Http
- module UploadedFile
- def self.extended(object)
- object.class_eval do
- attr_accessor :original_path, :content_type
- alias_method :local_path, :path if method_defined?(:path)
- end
+ class UploadedFile
+ attr_accessor :original_filename, :content_type, :tempfile, :headers
+
+ def initialize(hash)
+ @original_filename = hash[:filename]
+ @content_type = hash[:type]
+ @headers = hash[:head]
+ @tempfile = hash[:tempfile]
+ raise(ArgumentError, ':tempfile is required') unless @tempfile
end
- # Take the basename of the upload's original filename.
- # This handles the full Windows paths given by Internet Explorer
- # (and perhaps other broken user agents) without affecting
- # those which give the lone filename.
- # The Windows regexp is adapted from Perl's File::Basename.
- def original_filename
- unless defined? @original_filename
- @original_filename =
- unless original_path.blank?
- if original_path =~ /^(?:.*[:\\\/])?(.*)/m
- $1
- else
- File.basename original_path
- end
- end
- end
- @original_filename
+ def open
+ @tempfile.open
+ end
+
+ def path
+ @tempfile.path
+ end
+
+ def read(*args)
+ @tempfile.read(*args)
+ end
+
+ def rewind
+ @tempfile.rewind
+ end
+
+ def size
+ @tempfile.size
end
end
@@ -35,11 +37,7 @@ module ActionDispatch
# file upload hash with UploadedFile objects
def normalize_parameters(value)
if Hash === value && value.has_key?(:tempfile)
- upload = value[:tempfile]
- upload.extend(UploadedFile)
- upload.original_path = value[:filename]
- upload.content_type = value[:type]
- upload
+ UploadedFile.new(value)
else
super
end
@@ -47,4 +45,4 @@ module ActionDispatch
private :normalize_parameters
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index b64a83c62e..ac0fd9607d 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -1,6 +1,81 @@
module ActionDispatch
module Http
module URL
+ mattr_accessor :tld_length
+ self.tld_length = 1
+
+ class << self
+ def extract_domain(host, tld_length = @@tld_length)
+ return nil unless named_host?(host)
+ host.split('.').last(1 + tld_length).join('.')
+ end
+
+ def extract_subdomains(host, tld_length = @@tld_length)
+ return [] unless named_host?(host)
+ parts = host.split('.')
+ parts[0..-(tld_length+2)]
+ end
+
+ def extract_subdomain(host, tld_length = @@tld_length)
+ extract_subdomains(host, tld_length).join('.')
+ end
+
+ def url_for(options = {})
+ unless options[:host].present? || options[:only_path].present?
+ raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
+ end
+
+ rewritten_url = ""
+
+ unless options[:only_path]
+ unless options[:protocol] == false
+ rewritten_url << (options[:protocol] || "http")
+ rewritten_url << ":" unless rewritten_url.match(%r{:|//})
+ end
+ rewritten_url << "//" unless rewritten_url.match("//")
+ rewritten_url << rewrite_authentication(options)
+ rewritten_url << host_or_subdomain_and_domain(options)
+ rewritten_url << ":#{options.delete(:port)}" if options[:port]
+ end
+
+ path = options.delete(:path) || ''
+
+ params = options[:params] || {}
+ params.reject! {|k,v| v.to_param.nil? }
+
+ rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path)
+ rewritten_url << "?#{params.to_query}" unless params.empty?
+ rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor]
+ rewritten_url
+ end
+
+ private
+
+ def named_host?(host)
+ !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host))
+ end
+
+ def rewrite_authentication(options)
+ if options[:user] && options[:password]
+ "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@"
+ else
+ ""
+ end
+ end
+
+ def host_or_subdomain_and_domain(options)
+ return options[:host] unless options[:subdomain] || options[:domain]
+
+ tld_length = options[:tld_length] || @@tld_length
+
+ host = ""
+ host << (options[:subdomain] || extract_subdomain(options[:host], tld_length))
+ host << "."
+ host << (options[:domain] || extract_domain(options[:host], tld_length))
+ host
+ end
+ end
+
# Returns the complete URL used for this request.
def url
protocol + host_with_port + fullpath
@@ -8,12 +83,7 @@ module ActionDispatch
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
def protocol
- ssl? ? 'https://' : 'http://'
- end
-
- # Is this an SSL request?
- def ssl?
- @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https'
+ @protocol ||= ssl? ? 'https://' : 'http://'
end
# Returns the \host for this request, such as "example.com".
@@ -38,10 +108,12 @@ module ActionDispatch
# Returns the port number of this request as an integer.
def port
- if raw_host_with_port =~ /:(\d+)$/
- $1.to_i
- else
- standard_port
+ @port ||= begin
+ if raw_host_with_port =~ /:(\d+)$/
+ $1.to_i
+ else
+ standard_port
+ end
end
end
@@ -53,10 +125,21 @@ module ActionDispatch
end
end
- # Returns a \port suffix like ":8080" if the \port number of this request
+ # 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
- port == standard_port ? '' : ":#{port}"
+ standard_port? ? '' : ":#{port}"
end
def server_port
@@ -65,38 +148,25 @@ module ActionDispatch
# 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 = 1)
- return nil unless named_host?(host)
-
- host.split('.').last(1 + tld_length).join('.')
+ 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 = 1)
- return [] unless named_host?(host)
- parts = host.split('.')
- parts[0..-(tld_length+2)]
- end
-
- def subdomain(tld_length = 1)
- subdomains(tld_length).join('.')
- end
-
- # Returns the request URI, accounting for server idiosyncrasies.
- # WEBrick includes the full URL. IIS leaves REQUEST_URI blank.
- def request_uri
- ActiveSupport::Deprecation.warn "Using #request_uri is deprecated. Use fullpath instead.", caller
- fullpath
+ def subdomains(tld_length = @@tld_length)
+ ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
end
- private
-
- def named_host?(host)
- !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host))
+ # 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)
+ subdomains(tld_length)
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
index e4ae480bfb..1bb2ad7f67 100644
--- a/actionpack/lib/action_dispatch/middleware/callbacks.rb
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -1,30 +1,14 @@
+require 'active_support/core_ext/module/delegation'
+
module ActionDispatch
# Provide callbacks to be executed before and after the request dispatch.
- #
- # It also provides a to_prepare callback, which is performed in all requests
- # in development by only once in production and notification callback for async
- # operations.
- #
class Callbacks
include ActiveSupport::Callbacks
define_callbacks :call, :rescuable => true
- define_callbacks :prepare, :scope => :name
- # Add a preparation callback. Preparation callbacks are run before every
- # request in development mode, and before the first request in production mode.
- #
- # If a symbol with a block is given, the symbol is used as an identifier.
- # That allows to_prepare to be called again with the same identifier to
- # replace the existing callback. Passing an identifier is a suggested
- # practice if the code adding a preparation block may be reloaded.
- def self.to_prepare(*args, &block)
- if args.first.is_a?(Symbol) && block_given?
- define_method :"__#{args.first}", &block
- set_callback(:prepare, :"__#{args.first}")
- else
- set_callback(:prepare, *args, &block)
- end
+ class << self
+ delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
end
def self.before(*args, &block)
@@ -35,14 +19,13 @@ module ActionDispatch
set_callback(:call, :after, *args, &block)
end
- def initialize(app, prepare_each_request = false)
- @app, @prepare_each_request = app, prepare_each_request
- _run_prepare_callbacks
+ def initialize(app, unused = nil)
+ ActiveSupport::Deprecation.warn "Passing a second argument to ActionDispatch::Callbacks.new is deprecated." unless unused.nil?
+ @app = app
end
def call(env)
- _run_call_callbacks do
- _run_prepare_callbacks if @prepare_each_request
+ run_callbacks :call do
@app.call(env)
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index 4d33cd3b0c..7ac608f0a8 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -7,7 +7,7 @@ module ActionDispatch
end
end
- # Cookies are read and written through ActionController#cookies.
+ # \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
@@ -16,15 +16,31 @@ module ActionDispatch
# Examples for 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 a user from tampering with its value.
+ # # The cookie is signed by your app's <tt>config.secret_token</tt> value.
+ # # Rails generates this value by default when you create a new Rails app.
+ # 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 for reading:
#
# cookies[:user_name] # => "david"
# cookies.size # => 2
+ # cookies[:lat_lon] # => [47.68, -122.37]
#
# Example for deleting:
#
@@ -55,7 +71,7 @@ module ActionDispatch
# :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>: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
@@ -69,27 +85,36 @@ module ActionDispatch
class CookieJar < Hash #:nodoc:
- # This regular expression is used to split the levels of a domain
- # So www.example.co.uk gives:
- # $1 => www.
- # $2 => example
- # $3 => co.uk
- DOMAIN_REGEXP = /^(.*\.)*(.*)\.(...|...\...|....|..\...|..)$/
+ # 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.build(request)
secret = request.env[TOKEN_KEY]
- host = request.env["HTTP_HOST"]
+ host = request.host
+ secure = request.ssl?
- new(secret, host).tap do |hash|
+ new(secret, host, secure).tap do |hash|
hash.update(request.cookies)
end
end
- def initialize(secret = nil, host = nil)
+ def initialize(secret = nil, host = nil, secure = false)
@secret = secret
@set_cookies = {}
@delete_cookies = {}
@host = host
+ @secure = secure
super()
end
@@ -103,8 +128,17 @@ module ActionDispatch
options[:path] ||= "/"
if options[:domain] == :all
- @host =~ DOMAIN_REGEXP
- options[:domain] = ".#{$2}.#{$3}"
+ # if there is a provided tld length then we use it otherwise default domain regexp
+ domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
+
+ # if host is not ip and matches domain regexp
+ # (ip confirms to domain regexp so we explicitly check for ip)
+ options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
+ ".#{$&}"
+ end
+ elsif options[:domain].is_a? Array
+ # if host matches one of the supplied domains without a dot in front of it
+ options[:domain] = options[:domain].find {|domain| @host.include? domain[/^\.?(.*)$/, 1] }
end
end
@@ -174,9 +208,15 @@ module ActionDispatch
end
def write(headers)
- @set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) }
+ @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
+
+ private
+
+ def write_cookie?(cookie)
+ @secure || !cookie[:secure] || defined?(Rails.env) && Rails.env.development?
+ end
end
class PermanentCookieJar < CookieJar #:nodoc:
@@ -248,7 +288,7 @@ module ActionDispatch
"integrity hash for cookie session data. Use " +
"config.secret_token = \"some secret phrase of at " +
"least #{SECRET_MIN_LENGTH} characters\"" +
- "in config/application.rb"
+ "in config/initializers/secret_token.rb"
end
if secret.length < SECRET_MIN_LENGTH
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
index bfa30cf5af..21aeeb217a 100644
--- a/actionpack/lib/action_dispatch/middleware/flash.rb
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -10,13 +10,13 @@ module ActionDispatch
# 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] = "Successfully created"</tt> before redirecting to a display action that can
+ # 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. Example:
#
# class PostsController < ActionController::Base
# def create
# # save post
- # flash[:notice] = "Successfully created post"
+ # flash[:notice] = "Post successfully created"
# redirect_to posts_path(@post)
# end
#
@@ -30,6 +30,11 @@ module ActionDispatch
# <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.
#
diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb
new file mode 100644
index 0000000000..29289a76b4
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/reloader.rb
@@ -0,0 +1,76 @@
+module ActionDispatch
+ # ActionDispatch::Reloader provides prepare and cleanup callbacks,
+ # intended to assist with code reloading during development.
+ #
+ # Prepare callbacks are run before each request, and cleanup callbacks
+ # after each request. In this respect they are analogs of ActionDispatch::Callback's
+ # before and after callbacks. However, cleanup callbacks are not called until the
+ # request is fully complete -- that is, after #close has been called on
+ # the response body. This is important for streaming responses such as the
+ # following:
+ #
+ # self.response_body = lambda { |response, output|
+ # # code here which refers to application models
+ # }
+ #
+ # Cleanup callbacks will not be called until after the response_body lambda
+ # is evaluated, ensuring that it can refer to application models and other
+ # classes before they are unloaded.
+ #
+ # By default, ActionDispatch::Reloader is included in the middleware stack
+ # only in the development environment; specifically, when config.cache_classes
+ # is false. Callbacks may be registered even when it is not included in the
+ # middleware stack, but are executed only when +ActionDispatch::Reloader.prepare!+
+ # or +ActionDispatch::Reloader.cleanup!+ are called manually.
+ #
+ class Reloader
+ include ActiveSupport::Callbacks
+
+ define_callbacks :prepare, :scope => :name
+ define_callbacks :cleanup, :scope => :name
+
+ # Add a prepare callback. Prepare callbacks are run before each request, prior
+ # to ActionDispatch::Callback's before callbacks.
+ def self.to_prepare(*args, &block)
+ set_callback(:prepare, *args, &block)
+ end
+
+ # Add a cleanup callback. Cleanup callbacks are run after each request is
+ # complete (after #close is called on the response body).
+ def self.to_cleanup(*args, &block)
+ set_callback(:cleanup, *args, &block)
+ end
+
+ # Execute all prepare callbacks.
+ def self.prepare!
+ new(nil).run_callbacks :prepare
+ end
+
+ # Execute all cleanup callbacks.
+ def self.cleanup!
+ new(nil).run_callbacks :cleanup
+ end
+
+ def initialize(app)
+ @app = app
+ end
+
+ module CleanupOnClose
+ def close
+ super if defined?(super)
+ ensure
+ ActionDispatch::Reloader.cleanup!
+ end
+ end
+
+ def call(env)
+ run_callbacks :prepare
+ response = @app.call(env)
+ response[2].extend(CleanupOnClose)
+ response
+ rescue Exception
+ run_callbacks :cleanup
+ raise
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index dd82294644..64d3a87fd0 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -1,5 +1,6 @@
require 'rack/utils'
require 'rack/request'
+require 'rack/session/abstract/id'
require 'action_dispatch/middleware/cookies'
require 'active_support/core_ext/object/blank'
@@ -8,249 +9,76 @@ module ActionDispatch
class SessionRestoreError < StandardError #:nodoc:
end
- class AbstractStore
- ENV_SESSION_KEY = 'rack.session'.freeze
- ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze
-
- # thin wrapper around Hash that allows us to lazily
- # load session id into session_options
- class OptionsHash < Hash
- def initialize(by, env, default_options)
- @by = by
- @env = env
- @session_id_loaded = false
- merge!(default_options)
- end
-
- def [](key)
- if key == :id
- load_session_id! unless key?(:id) || has_session_id?
- end
- super
- end
-
- private
-
- def has_session_id?
- @session_id_loaded
- end
-
- def load_session_id!
- self[:id] = @by.send(:extract_session_id, @env)
- @session_id_loaded = true
- end
- end
-
- class SessionHash < Hash
- def initialize(by, env)
- super()
- @by = by
- @env = env
- @loaded = false
- end
-
- def [](key)
- load_for_read!
- super(key.to_s)
- end
-
- def has_key?(key)
- load_for_read!
- super(key.to_s)
- end
-
- def []=(key, value)
- load_for_write!
- super(key.to_s, value)
- end
-
- def clear
- load_for_write!
- super
- end
-
- def to_hash
- load_for_read!
- h = {}.replace(self)
- h.delete_if { |k,v| v.nil? }
- h
- end
-
- def update(hash)
- load_for_write!
- super(hash.stringify_keys)
- end
-
- def delete(key)
- load_for_write!
- super(key.to_s)
- end
-
- def inspect
- load_for_read!
- super
- end
-
- def exists?
- return @exists if instance_variable_defined?(:@exists)
- @exists = @by.send(:exists?, @env)
- end
-
- def loaded?
- @loaded
- end
-
- def destroy
- clear
- @by.send(:destroy, @env) if @by
- @env[ENV_SESSION_OPTIONS_KEY][:id] = nil if @env && @env[ENV_SESSION_OPTIONS_KEY]
- @loaded = false
- end
-
- private
-
- def load_for_read!
- load! if !loaded? && exists?
- end
-
- def load_for_write!
- load! unless loaded?
- end
-
- def load!
- id, session = @by.send(:load_session, @env)
- @env[ENV_SESSION_OPTIONS_KEY][:id] = id
- replace(session.stringify_keys)
- @loaded = true
- end
-
+ module DestroyableSession
+ def destroy
+ clear
+ options = @env[Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY] if @env
+ options ||= {}
+ @by.send(:destroy_session, @env, options[:id], options) if @by
+ options[:id] = nil
+ @loaded = false
end
+ end
- DEFAULT_OPTIONS = {
- :key => '_session_id',
- :path => '/',
- :domain => nil,
- :expire_after => nil,
- :secure => false,
- :httponly => true,
- :cookie_only => true
- }
+ ::Rack::Session::Abstract::SessionHash.send :include, DestroyableSession
+ module Compatibility
def initialize(app, options = {})
- @app = app
- @default_options = DEFAULT_OPTIONS.merge(options)
- @key = @default_options.delete(:key).freeze
- @cookie_only = @default_options.delete(:cookie_only)
- ensure_session_key!
+ options[:key] ||= '_session_id'
+ super
end
- def call(env)
- prepare!(env)
- response = @app.call(env)
-
- session_data = env[ENV_SESSION_KEY]
- options = env[ENV_SESSION_OPTIONS_KEY]
-
- if !session_data.is_a?(AbstractStore::SessionHash) || session_data.loaded? || options[:expire_after]
- session_data.send(:load!) if session_data.is_a?(AbstractStore::SessionHash) && !session_data.loaded?
-
- sid = options[:id] || generate_sid
- session_data = session_data.to_hash
-
- value = set_session(env, sid, session_data)
- return response unless value
-
- cookie = { :value => value }
- unless options[:expire_after].nil?
- cookie[:expires] = Time.now + options.delete(:expire_after)
- end
-
- request = ActionDispatch::Request.new(env)
- set_cookie(request, cookie.merge!(options))
- end
-
- response
+ def generate_sid
+ ActiveSupport::SecureRandom.hex(16)
end
- private
-
- def prepare!(env)
- env[ENV_SESSION_KEY] = SessionHash.new(self, env)
- env[ENV_SESSION_OPTIONS_KEY] = OptionsHash.new(self, env, @default_options)
- end
-
- def generate_sid
- ActiveSupport::SecureRandom.hex(16)
- end
-
- def set_cookie(request, options)
- if request.cookie_jar[@key] != options[:value] || !options[:expires].nil?
- request.cookie_jar[@key] = options
- end
- end
-
- def load_session(env)
- stale_session_check! do
- sid = current_session_id(env)
- sid, session = get_session(env, sid)
- [sid, session]
- end
- end
+ protected
- def extract_session_id(env)
- stale_session_check! do
- request = ActionDispatch::Request.new(env)
- sid = request.cookies[@key]
- sid ||= request.params[@key] unless @cookie_only
- sid
- end
- end
+ def initialize_sid
+ @default_options.delete(:sidbits)
+ @default_options.delete(:secure_random)
+ end
+ end
- def current_session_id(env)
- env[ENV_SESSION_OPTIONS_KEY][:id]
- end
+ module StaleSessionCheck
+ def load_session(env)
+ stale_session_check! { super }
+ end
- def ensure_session_key!
- if @key.blank?
- raise ArgumentError, 'A key is required to write a ' +
- 'cookie containing the session data. Use ' +
- 'config.session_store SESSION_STORE, { :key => ' +
- '"_myapp_session" } in config/application.rb'
- end
- 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 => const_error
- raise ActionDispatch::Session::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n"
- end
- retry
- else
- raise
+ 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 => const_error
+ raise ActionDispatch::Session::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n"
end
+ retry
+ else
+ raise
end
+ end
+ end
- def exists?(env)
- current_session_id(env).present?
- end
-
- def get_session(env, sid)
- raise '#get_session needs to be implemented.'
- end
+ class AbstractStore < Rack::Session::Abstract::ID
+ include Compatibility
+ include StaleSessionCheck
- def set_session(env, sid, session_data)
- raise '#set_session needs to be implemented and should return ' <<
- 'the value to be stored in the cookie (usually the sid)'
- end
+ def destroy_session(env, sid, options)
+ ActiveSupport::Deprecation.warn "Implementing #destroy in session stores is deprecated. " <<
+ "Please implement destroy_session(env, session_id, options) instead."
+ destroy(env)
+ end
- def destroy(env)
- raise '#destroy needs to be implemented.'
- end
+ def destroy(env)
+ raise '#destroy needs to be implemented.'
+ 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
index ca1494425f..9c9ccc62f5 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -1,5 +1,7 @@
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/object/blank'
+require 'action_dispatch/middleware/session/abstract_store'
+require 'rack/session/cookie'
module ActionDispatch
module Session
@@ -38,58 +40,32 @@ module ActionDispatch
# "rake secret" and set the key in config/initializers/secret_token.rb.
#
# Note that changing digest or secret invalidates all existing sessions!
- class CookieStore < AbstractStore
-
- def initialize(app, options = {})
- super(app, options.merge!(:cookie_only => true))
- freeze
- end
+ class CookieStore < Rack::Session::Cookie
+ include Compatibility
+ include StaleSessionCheck
private
- def load_session(env)
- data = unpacked_cookie_data(env)
- data = persistent_session_id!(data)
- [data["session_id"], data]
- end
-
- def extract_session_id(env)
- if data = unpacked_cookie_data(env)
- data["session_id"]
- else
- nil
- end
- end
-
- def unpacked_cookie_data(env)
- env["action_dispatch.request.unsigned_session_cookie"] ||= begin
- stale_session_check! do
- request = ActionDispatch::Request.new(env)
- if data = request.cookie_jar.signed[@key]
- data.stringify_keys!
- end
- data || {}
+ def unpacked_cookie_data(env)
+ env["action_dispatch.request.unsigned_session_cookie"] ||= begin
+ stale_session_check! do
+ request = ActionDispatch::Request.new(env)
+ if data = request.cookie_jar.signed[@key]
+ data.stringify_keys!
end
+ data || {}
end
end
+ end
- def set_cookie(request, options)
- request.cookie_jar.signed[@key] = options
- end
-
- def set_session(env, sid, session_data)
- persistent_session_id!(session_data, sid)
- end
-
- def destroy(env)
- # session data is stored on client; nothing to do here
- end
+ def set_session(env, sid, session_data, options)
+ persistent_session_id!(session_data, sid)
+ end
- def persistent_session_id!(data, sid=nil)
- data ||= {}
- data["session_id"] ||= sid || generate_sid
- data
- end
+ def set_cookie(env, session_id, cookie)
+ request = ActionDispatch::Request.new(env)
+ request.cookie_jar.signed[@key] = cookie
+ 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
index 28e3dbd732..4dd9a946c2 100644
--- a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
@@ -1,56 +1,17 @@
+require 'action_dispatch/middleware/session/abstract_store'
+require 'rack/session/memcache'
+
module ActionDispatch
module Session
- class MemCacheStore < AbstractStore
+ class MemCacheStore < Rack::Session::Memcache
+ include Compatibility
+ include StaleSessionCheck
+
def initialize(app, options = {})
require 'memcache'
-
- # Support old :expires option
options[:expire_after] ||= options[:expires]
-
- super
-
- @default_options = {
- :namespace => 'rack:session',
- :memcache_server => 'localhost:11211'
- }.merge(@default_options)
-
- @pool = options[:cache] || MemCache.new(@default_options[:memcache_server], @default_options)
- unless @pool.servers.any? { |s| s.alive? }
- raise "#{self} unable to find server during initialization."
- end
- @mutex = Mutex.new
-
super
end
-
- private
- def get_session(env, sid)
- sid ||= generate_sid
- begin
- session = @pool.get(sid) || {}
- rescue MemCache::MemCacheError, Errno::ECONNREFUSED
- session = {}
- end
- [sid, session]
- end
-
- def set_session(env, sid, session_data)
- options = env['rack.session.options']
- expiry = options[:expire_after] || 0
- @pool.set(sid, session_data, expiry)
- sid
- rescue MemCache::MemCacheError, Errno::ECONNREFUSED
- false
- end
-
- def destroy(env)
- if sid = current_session_id(env)
- @pool.delete(sid)
- end
- rescue MemCache::MemCacheError, Errno::ECONNREFUSED
- false
- end
-
end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index e095b51342..dbe3206808 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -6,8 +6,6 @@ module ActionDispatch
# This middleware rescues any exception returned by the application and renders
# nice exception pages if it's being rescued locally.
class ShowExceptions
- LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze
-
RESCUES_TEMPLATE_PATH = File.join(File.dirname(__FILE__), 'templates')
cattr_accessor :rescue_responses
@@ -45,28 +43,29 @@ module ActionDispatch
end
def call(env)
- status, headers, body = @app.call(env)
-
- # Only this middleware cares about RoutingError. So, let's just raise
- # it here.
- # TODO: refactor this middleware to handle the X-Cascade scenario without
- # having to raise an exception.
- if headers['X-Cascade'] == 'pass'
- raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}"
+ begin
+ status, headers, body = @app.call(env)
+ exception = nil
+
+ # Only this middleware cares about RoutingError. So, let's just raise
+ # it here.
+ if headers['X-Cascade'] == 'pass'
+ raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}"
+ end
+ rescue Exception => exception
+ raise exception if env['action_dispatch.show_exceptions'] == false
end
- [status, headers, body]
- rescue Exception => exception
- raise exception if env['action_dispatch.show_exceptions'] == false
- render_exception(env, exception)
+ exception ? render_exception(env, exception) : [status, headers, body]
end
private
def render_exception(env, exception)
log_error(exception)
+ exception = original_exception(exception)
request = Request.new(env)
- if @consider_all_requests_local || local_request?(request)
+ if @consider_all_requests_local || request.local?
rescue_action_locally(request, exception)
else
rescue_action_in_public(exception)
@@ -112,11 +111,6 @@ module ActionDispatch
end
end
- # True if the request came from localhost, 127.0.0.1.
- def local_request?(request)
- LOCALHOST.any? { |local_ip| local_ip === request.remote_addr && local_ip === request.remote_ip }
- end
-
def status_code(exception)
Rack::Utils.status_code(@@rescue_responses[exception.class.name])
end
@@ -134,7 +128,7 @@ module ActionDispatch
ActiveSupport::Deprecation.silence do
message = "\n#{exception.class} (#{exception.message}):\n"
- message << exception.annoted_source_code if exception.respond_to?(:annoted_source_code)
+ message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
message << " " << application_trace(exception).join("\n ")
logger.fatal("#{message}\n\n")
end
@@ -161,5 +155,17 @@ module ActionDispatch
def logger
defined?(Rails.logger) ? Rails.logger : Logger.new($stderr)
end
+
+ 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
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb
index 41078eced7..a4308f528c 100644
--- a/actionpack/lib/action_dispatch/middleware/stack.rb
+++ b/actionpack/lib/action_dispatch/middleware/stack.rb
@@ -1,17 +1,27 @@
require "active_support/inflector/methods"
+require "active_support/dependencies"
module ActionDispatch
- class MiddlewareStack < Array
+ class MiddlewareStack
class Middleware
- attr_reader :args, :block
+ attr_reader :args, :block, :name, :classcache
def initialize(klass_or_name, *args, &block)
- @ref = ActiveSupport::Dependencies::Reference.new(klass_or_name)
+ @klass = nil
+
+ if klass_or_name.respond_to?(:name)
+ @klass = klass_or_name
+ @name = @klass.name
+ else
+ @name = klass_or_name.to_s
+ end
+
+ @classcache = ActiveSupport::Dependencies::Reference
@args, @block = args, block
end
def klass
- @ref.get
+ @klass || classcache[@name]
end
def ==(middleware)
@@ -21,7 +31,7 @@ module ActionDispatch
when Class
klass == middleware
else
- normalize(@ref.name) == normalize(middleware)
+ normalize(@name) == normalize(middleware)
end
end
@@ -40,15 +50,39 @@ module ActionDispatch
end
end
- def initialize(*args, &block)
- super(*args)
- block.call(self) if block_given?
+ 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 initialize_copy(other)
+ self.middlewares = other.middlewares.dup
end
def insert(index, *args, &block)
index = assert_index(index, :before)
middleware = self.class::Middleware.new(*args, &block)
- super(index, middleware)
+ middlewares.insert(index, middleware)
end
alias_method :insert_before, :insert
@@ -63,26 +97,25 @@ module ActionDispatch
delete(target)
end
- def use(*args, &block)
- middleware = self.class::Middleware.new(*args, &block)
- push(middleware)
+ def delete(target)
+ middlewares.delete target
end
- def active
- ActiveSupport::Deprecation.warn "All middlewares in the chain are active since the laziness " <<
- "was removed from the middleware stack", caller
+ 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
- reverse.inject(app) { |a, e| e.build(a) }
+ middlewares.reverse.inject(app) { |a, e| e.build(a) }
end
protected
def assert_index(index, where)
- i = index.is_a?(Integer) ? index : self.index(index)
+ i = index.is_a?(Integer) ? index : middlewares.index(index)
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
i
end
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
index d7e88a54e4..c57f694c4d 100644
--- a/actionpack/lib/action_dispatch/middleware/static.rb
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -1,12 +1,47 @@
require 'rack/utils'
module ActionDispatch
+ class FileHandler
+ def initialize(at, root)
+ @at, @root = at.chomp('/'), root.chomp('/')
+ @compiled_at = @at.blank? ? nil : /^#{Regexp.escape(at)}/
+ @compiled_root = /^#{Regexp.escape(root)}/
+ @file_server = ::Rack::File.new(@root)
+ end
+
+ def match?(path)
+ path = path.dup
+ if !@compiled_at || path.sub!(@compiled_at, '')
+ full_path = path.empty? ? @root : File.join(@root, ::Rack::Utils.unescape(path))
+ paths = "#{full_path}#{ext}"
+
+ matches = Dir[paths]
+ match = matches.detect { |m| File.file?(m) }
+ if match
+ match.sub!(@compiled_root, '')
+ match
+ end
+ end
+ end
+
+ def call(env)
+ @file_server.call(env)
+ end
+
+ def ext
+ @ext ||= begin
+ ext = ::ActionController::Base.page_cache_extension
+ "{,#{ext},/index#{ext}}"
+ end
+ end
+ end
+
class Static
FILE_METHODS = %w(GET HEAD).freeze
- def initialize(app, root)
+ def initialize(app, roots)
@app = app
- @file_server = ::Rack::File.new(root)
+ @file_handlers = create_file_handlers(roots)
end
def call(env)
@@ -14,15 +49,10 @@ module ActionDispatch
method = env['REQUEST_METHOD']
if FILE_METHODS.include?(method)
- if file_exist?(path)
- return @file_server.call(env)
- else
- cached_path = directory_exist?(path) ? "#{path}/index" : path
- cached_path += ::ActionController::Base.page_cache_extension
-
- if file_exist?(cached_path)
- env['PATH_INFO'] = cached_path
- return @file_server.call(env)
+ @file_handlers.each do |file_handler|
+ if match = file_handler.match?(path)
+ env["PATH_INFO"] = match
+ return file_handler.call(env)
end
end
end
@@ -31,14 +61,12 @@ module ActionDispatch
end
private
- def file_exist?(path)
- full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path))
- File.file?(full_path) && File.readable?(full_path)
- end
+ def create_file_handlers(roots)
+ roots = { '' => roots } unless roots.is_a?(Hash)
- def directory_exist?(path)
- full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path))
- File.directory?(full_path) && File.readable?(full_path)
+ roots.map do |at, root|
+ FileHandler.new(at, root) if File.exist?(root)
+ end.compact
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
index e963b04524..97f7cf0bbe 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
@@ -14,7 +14,7 @@
def debug_hash(hash)
hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n")
- end
+ end unless self.class.method_defined?(:debug_hash)
%>
<h2 style="margin-top: 30px">Request</h2>
@@ -28,4 +28,4 @@
<h2 style="margin-top: 30px">Response</h2>
-<p><b>Headers</b>: <pre><%=h @response ? @response.headers.inspect.gsub(',', ",\n") : 'None' %></pre></p>
+<p><b>Headers</b>: <pre><%=h defined?(@response) ? @response.headers.inspect.gsub(',', ",\n") : 'None' %></pre></p>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
index d18b162a93..8771b5fd6d 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
@@ -12,14 +12,14 @@
<div id="traces">
<% names.each do |name| %>
<%
- show = "document.getElementById('#{name.gsub /\s/, '-'}').style.display='block';"
- hide = (names - [name]).collect {|hide_name| "document.getElementById('#{hide_name.gsub /\s/, '-'}').style.display='none';"}
+ show = "document.getElementById('#{name.gsub(/\s/, '-')}').style.display='block';"
+ hide = (names - [name]).collect {|hide_name| "document.getElementById('#{hide_name.gsub(/\s/, '-')}').style.display='none';"}
%>
<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' %>;">
+ <div id="<%= name.gsub(/\s/, '-') %>" style="display: <%= (name == "Application Trace") ? 'block' : 'none' %>;">
<pre><code><%=h trace.join "\n" %></code></pre>
</div>
<% end %>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
index bd6ffbab5d..50d8ca9484 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
@@ -6,5 +6,5 @@
</h1>
<pre><%=h @exception.message %></pre>
-<%= render :file => "rescues/_trace.erb" %>
-<%= render :file => "rescues/_request_and_response.erb" %>
+<%= render :template => "rescues/_trace" %>
+<%= render :template => "rescues/_request_and_response" %>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
index 02fa18211d..c658559be9 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
@@ -13,9 +13,5 @@
<p><%=h @exception.sub_template_message %></p>
-<% @real_exception = @exception
- @exception = @exception.original_exception || @exception %>
-<%= render :file => "rescues/_trace.erb" %>
-<% @exception = @real_exception %>
-
-<%= render :file => "rescues/_request_and_response.erb" %>
+<%= render :template => "rescues/_trace" %>
+<%= render :template => "rescues/_request_and_response" %>
diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb
index a3af37947a..0a3bd5fe40 100644
--- a/actionpack/lib/action_dispatch/railtie.rb
+++ b/actionpack/lib/action_dispatch/railtie.rb
@@ -8,10 +8,11 @@ module ActionDispatch
config.action_dispatch.ip_spoofing_check = true
config.action_dispatch.show_exceptions = true
config.action_dispatch.best_standards_support = true
+ config.action_dispatch.tld_length = 1
+ config.action_dispatch.rack_cache = {:metastore => "rails:/", :entitystore => "rails:/", :verbose => true}
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.execute_if_updated }
+ initializer "action_dispatch.configure" do |app|
+ ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
end
end
end
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
index 683dd72555..43fd93adf6 100644
--- a/actionpack/lib/action_dispatch/routing.rb
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -2,31 +2,11 @@ require 'active_support/core_ext/object/to_param'
require 'active_support/core_ext/regexp'
module ActionDispatch
- # = Routing
- #
# 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.
+ # mod_rewrite rules. Best of all, Rails' \Routing works with any web server.
# Routes are defined in <tt>config/routes.rb</tt>.
#
- # Consider the following route, which you will find commented out at the
- # bottom of your generated <tt>config/routes.rb</tt>:
- #
- # match ':controller(/:action(/:id(.:format)))'
- #
- # This route states that it expects requests to consist of a
- # <tt>:controller</tt> followed optionally by an <tt>:action</tt> that in
- # turn is followed optionally by an <tt>:id</tt>, which in turn is followed
- # optionally by a <tt>:format</tt>
- #
- # Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end
- # up with:
- #
- # params = { :controller => 'blog',
- # :action => 'edit',
- # :id => '22'
- # }
- #
# Think of creating routes as drawing a map for your requests. The map tells
# them where to go based on some predefined pattern:
#
@@ -43,6 +23,51 @@ module ActionDispatch
#
# 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
+ # app/controllers/admin 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>.
+ #
# == Named routes
#
# Routes can be named by passing an <tt>:as</tt> option,
@@ -131,11 +156,35 @@ module ActionDispatch
# Encoding regular expression modifiers are silently ignored. The
# match will always use the default encoding or ASCII.
#
+ # == Default route
+ #
+ # Consider the following route, which you will find commented out at the
+ # bottom of your generated <tt>config/routes.rb</tt>:
+ #
+ # match ':controller(/:action(/:id(.:format)))'
+ #
+ # This route states that it expects requests to consist of a
+ # <tt>:controller</tt> followed optionally by an <tt>:action</tt> that in
+ # turn is followed optionally by an <tt>:id</tt>, which in turn is followed
+ # optionally by a <tt>:format</tt>.
+ #
+ # Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end
+ # up with:
+ #
+ # params = { :controller => 'blog',
+ # :action => 'edit',
+ # :id => '22'
+ # }
+ #
+ # By not relying on default routes, you improve the security of your
+ # application since not all controller actions, which includes actions you
+ # might add at a later time, are exposed by default.
+ #
# == HTTP Methods
#
# Using the <tt>:via</tt> option when specifying a route allows you to restrict it to a specific HTTP method.
- # Possible values are <tt>:post</tt>, <tt>:get</tt>, <tt>:put</tt>, <tt>:delete</tt> and <tt>:any</tt>.
- # If your route needs to respond to more than one method you can use an array, e.g. <tt>[ :get, :post ]</tt>.
+ # Possible values are <tt>:post</tt>, <tt>:get</tt>, <tt>:put</tt>, <tt>:delete</tt> and <tt>:any</tt>.
+ # If your route needs to respond to more than one method you can use an array, e.g. <tt>[ :get, :post ]</tt>.
# The default value is <tt>:any</tt> which means that the route will respond to any of the HTTP methods.
#
# Examples:
@@ -144,7 +193,7 @@ module ActionDispatch
# match 'post/:id' => "posts#create_comment', :via => :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.
+ # URL will route to the <tt>show</tt> action.
#
# === HTTP helper methods
#
@@ -160,6 +209,20 @@ module ActionDispatch
# however 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.
#
+ # == External redirects
+ #
+ # You can redirect any path to another path using the redirect helper in your router:
+ #
+ # match "/stories" => redirect("/posts")
+ #
+ # == 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:
+ #
+ # match "/application.js" => Sprockets
+ #
# == Reloading routes
#
# You can reload routes if you feel you must:
@@ -208,13 +271,15 @@ module ActionDispatch
#
# == View a list of all your routes
#
- # Run <tt>rake routes</tt>.
+ # rake routes
+ #
+ # Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
#
module Routing
- autoload :DeprecatedMapper, 'action_dispatch/routing/deprecated_mapper'
autoload :Mapper, 'action_dispatch/routing/mapper'
autoload :Route, 'action_dispatch/routing/route'
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'
diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
deleted file mode 100644
index e04062ce8b..0000000000
--- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
+++ /dev/null
@@ -1,525 +0,0 @@
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/object/with_options'
-require 'active_support/core_ext/object/try'
-
-module ActionDispatch
- module Routing
- class RouteSet
- attr_accessor :controller_namespaces
-
- CONTROLLER_REGEXP = /[_a-zA-Z0-9]+/
-
- def controller_constraints
- @controller_constraints ||= begin
- namespaces = controller_namespaces + in_memory_controller_namespaces
- source = namespaces.map { |ns| "#{Regexp.escape(ns)}/#{CONTROLLER_REGEXP.source}" }
- source << CONTROLLER_REGEXP.source
- Regexp.compile(source.sort.reverse.join('|'))
- end
- end
-
- def in_memory_controller_namespaces
- namespaces = Set.new
- ActionController::Base.descendants.each do |klass|
- next if klass.anonymous?
- namespaces << klass.name.underscore.split('/')[0...-1].join('/')
- end
- namespaces.delete('')
- namespaces
- end
- end
-
- class DeprecatedMapper #:nodoc:
- def initialize(set) #:nodoc:
- ActiveSupport::Deprecation.warn "You are using the old router DSL which will be 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/"
- @set = set
- end
-
- def connect(path, options = {})
- options = options.dup
-
- if conditions = options.delete(:conditions)
- conditions = conditions.dup
- method = [conditions.delete(:method)].flatten.compact
- method.map! { |m|
- m = m.to_s.upcase
-
- if m == "HEAD"
- raise ArgumentError, "HTTP method HEAD is invalid in route conditions. Rails processes HEAD requests the same as GETs, returning just the response headers"
- end
-
- unless HTTP_METHODS.include?(m.downcase.to_sym)
- raise ArgumentError, "Invalid HTTP method specified in route conditions"
- end
-
- m
- }
-
- if method.length > 1
- method = Regexp.union(*method)
- elsif method.length == 1
- method = method.first
- else
- method = nil
- end
- end
-
- path_prefix = options.delete(:path_prefix)
- name_prefix = options.delete(:name_prefix)
- namespace = options.delete(:namespace)
-
- name = options.delete(:_name)
- name = "#{name_prefix}#{name}" if name_prefix
-
- requirements = options.delete(:requirements) || {}
- defaults = options.delete(:defaults) || {}
- options.each do |k, v|
- if v.is_a?(Regexp)
- if value = options.delete(k)
- requirements[k.to_sym] = value
- end
- else
- value = options.delete(k)
- defaults[k.to_sym] = value.is_a?(Symbol) ? value : value.to_param
- end
- end
-
- requirements.each do |_, requirement|
- if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
- raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
- end
- if requirement.multiline?
- raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
- end
- end
-
- requirements[:controller] ||= @set.controller_constraints
-
- if defaults[:controller]
- defaults[:action] ||= 'index'
- defaults[:controller] = defaults[:controller].to_s
- defaults[:controller] = "#{namespace}#{defaults[:controller]}" if namespace
- end
-
- if defaults[:action]
- defaults[:action] = defaults[:action].to_s
- end
-
- if path.is_a?(String)
- path = "#{path_prefix}/#{path}" if path_prefix
- path = path.gsub('.:format', '(.:format)')
- path = optionalize_trailing_dynamic_segments(path, requirements, defaults)
- glob = $1.to_sym if path =~ /\/\*(\w+)$/
- path = ::Rack::Mount::Utils.normalize_path(path)
-
- if glob && !defaults[glob].blank?
- raise ActionController::RoutingError, "paths cannot have non-empty default values"
- end
- end
-
- app = Routing::RouteSet::Dispatcher.new(:defaults => defaults, :glob => glob)
-
- conditions = {}
- conditions[:request_method] = method if method
- conditions[:path_info] = path if path
-
- @set.add_route(app, conditions, requirements, defaults, name)
- end
-
- def optionalize_trailing_dynamic_segments(path, requirements, defaults) #:nodoc:
- path = (path =~ /^\//) ? path.dup : "/#{path}"
- optional, segments = true, []
-
- required_segments = requirements.keys
- required_segments -= defaults.keys.compact
-
- old_segments = path.split('/')
- old_segments.shift
- length = old_segments.length
-
- old_segments.reverse.each_with_index do |segment, index|
- required_segments.each do |required|
- if segment =~ /#{required}/
- optional = false
- break
- end
- end
-
- if optional
- if segment == ":id" && segments.include?(":action")
- optional = false
- elsif segment == ":controller" || segment == ":action" || segment == ":id"
- # Ignore
- elsif !(segment =~ /^:\w+$/) &&
- !(segment =~ /^:\w+\(\.:format\)$/)
- optional = false
- elsif segment =~ /^:(\w+)$/
- if defaults.has_key?($1.to_sym)
- defaults.delete($1.to_sym) if defaults[$1.to_sym].nil?
- else
- optional = false
- end
- end
- end
-
- if optional && index < length - 1
- segments.unshift('(/', segment)
- segments.push(')')
- elsif optional
- segments.unshift('/(', segment)
- segments.push(')')
- else
- segments.unshift('/', segment)
- end
- end
-
- segments.join
- end
- private :optionalize_trailing_dynamic_segments
-
- # Creates a named route called "root" for matching the root level request.
- def root(options = {})
- if options.is_a?(Symbol)
- if source_route = @set.named_routes.routes[options]
- options = source_route.defaults.merge({ :conditions => source_route.conditions })
- end
- end
- named_route("root", '', options)
- end
-
- def named_route(name, path, options = {}) #:nodoc:
- options[:_name] = name
- connect(path, options)
- end
-
- def namespace(name, options = {}, &block)
- if options[:namespace]
- with_options({:path_prefix => "#{options.delete(:path_prefix)}/#{name}", :name_prefix => "#{options.delete(:name_prefix)}#{name}_", :namespace => "#{options.delete(:namespace)}#{name}/" }.merge(options), &block)
- else
- with_options({:path_prefix => name, :name_prefix => "#{name}_", :namespace => "#{name}/" }.merge(options), &block)
- end
- end
-
- def method_missing(route_name, *args, &proc) #:nodoc:
- super unless args.length >= 1 && proc.nil?
- named_route(route_name, *args)
- end
-
- INHERITABLE_OPTIONS = :namespace, :shallow
-
- class Resource #:nodoc:
- DEFAULT_ACTIONS = :index, :create, :new, :edit, :show, :update, :destroy
-
- attr_reader :collection_methods, :member_methods, :new_methods
- attr_reader :path_prefix, :name_prefix, :path_segment
- attr_reader :plural, :singular
- attr_reader :options, :defaults
-
- def initialize(entities, options, defaults)
- @plural ||= entities
- @singular ||= options[:singular] || plural.to_s.singularize
- @path_segment = options.delete(:as) || @plural
-
- @options = options
- @defaults = defaults
-
- arrange_actions
- add_default_actions
- set_allowed_actions
- set_prefixes
- end
-
- def controller
- @controller ||= "#{options[:namespace]}#{(options[:controller] || plural).to_s}"
- end
-
- def requirements(with_id = false)
- @requirements ||= @options[:requirements] || {}
- @id_requirement ||= { :id => @requirements.delete(:id) || /[^#{Routing::SEPARATORS.join}]+/ }
-
- with_id ? @requirements.merge(@id_requirement) : @requirements
- end
-
- def conditions
- @conditions ||= @options[:conditions] || {}
- end
-
- def path
- @path ||= "#{path_prefix}/#{path_segment}"
- end
-
- def new_path
- new_action = self.options[:path_names][:new] if self.options[:path_names]
- new_action ||= self.defaults[:path_names][:new]
- @new_path ||= "#{path}/#{new_action}"
- end
-
- def shallow_path_prefix
- @shallow_path_prefix ||= @options[:shallow] ? @options[:namespace].try(:sub, /\/$/, '') : path_prefix
- end
-
- def member_path
- @member_path ||= "#{shallow_path_prefix}/#{path_segment}/:id"
- end
-
- def nesting_path_prefix
- @nesting_path_prefix ||= "#{shallow_path_prefix}/#{path_segment}/:#{singular}_id"
- end
-
- def shallow_name_prefix
- @shallow_name_prefix ||= @options[:shallow] ? @options[:namespace].try(:gsub, /\//, '_') : name_prefix
- end
-
- def nesting_name_prefix
- "#{shallow_name_prefix}#{singular}_"
- end
-
- def action_separator
- @action_separator ||= ActionController::Base.resource_action_separator
- end
-
- def uncountable?
- @singular.to_s == @plural.to_s
- end
-
- def has_action?(action)
- !DEFAULT_ACTIONS.include?(action) || action_allowed?(action)
- end
-
- protected
- def arrange_actions
- @collection_methods = arrange_actions_by_methods(options.delete(:collection))
- @member_methods = arrange_actions_by_methods(options.delete(:member))
- @new_methods = arrange_actions_by_methods(options.delete(:new))
- end
-
- def add_default_actions
- add_default_action(member_methods, :get, :edit)
- add_default_action(new_methods, :get, :new)
- end
-
- def set_allowed_actions
- only, except = @options.values_at(:only, :except)
- @allowed_actions ||= {}
-
- if only == :all || except == :none
- only = nil
- except = []
- elsif only == :none || except == :all
- only = []
- except = nil
- end
-
- if only
- @allowed_actions[:only] = Array(only).map {|a| a.to_sym }
- elsif except
- @allowed_actions[:except] = Array(except).map {|a| a.to_sym }
- end
- end
-
- def action_allowed?(action)
- only, except = @allowed_actions.values_at(:only, :except)
- (!only || only.include?(action)) && (!except || !except.include?(action))
- end
-
- def set_prefixes
- @path_prefix = options.delete(:path_prefix)
- @name_prefix = options.delete(:name_prefix)
- end
-
- def arrange_actions_by_methods(actions)
- (actions || {}).inject({}) do |flipped_hash, (key, value)|
- (flipped_hash[value] ||= []) << key
- flipped_hash
- end
- end
-
- def add_default_action(collection, method, action)
- (collection[method] ||= []).unshift(action)
- end
- end
-
- class SingletonResource < Resource #:nodoc:
- def initialize(entity, options, defaults)
- @singular = @plural = entity
- options[:controller] ||= @singular.to_s.pluralize
- super
- end
-
- alias_method :shallow_path_prefix, :path_prefix
- alias_method :shallow_name_prefix, :name_prefix
- alias_method :member_path, :path
- alias_method :nesting_path_prefix, :path
- end
-
- def resources(*entities, &block)
- options = entities.extract_options!
- entities.each { |entity| map_resource(entity, options.dup, &block) }
- end
-
- def resource(*entities, &block)
- options = entities.extract_options!
- entities.each { |entity| map_singleton_resource(entity, options.dup, &block) }
- end
-
- private
- def map_resource(entities, options = {}, &block)
- resource = Resource.new(entities, options, :path_names => @set.resources_path_names)
-
- with_options :controller => resource.controller do |map|
- map_associations(resource, options)
-
- if block_given?
- with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
- end
-
- map_collection_actions(map, resource)
- map_default_collection_actions(map, resource)
- map_new_actions(map, resource)
- map_member_actions(map, resource)
- end
- end
-
- def map_singleton_resource(entities, options = {}, &block)
- resource = SingletonResource.new(entities, options, :path_names => @set.resources_path_names)
-
- with_options :controller => resource.controller do |map|
- map_associations(resource, options)
-
- if block_given?
- with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
- end
-
- map_collection_actions(map, resource)
- map_new_actions(map, resource)
- map_member_actions(map, resource)
- map_default_singleton_actions(map, resource)
- end
- end
-
- def map_associations(resource, options)
- map_has_many_associations(resource, options.delete(:has_many), options) if options[:has_many]
-
- path_prefix = "#{options.delete(:path_prefix)}#{resource.nesting_path_prefix}"
- name_prefix = "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}"
-
- Array(options[:has_one]).each do |association|
- resource(association, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => path_prefix, :name_prefix => name_prefix))
- end
- end
-
- def map_has_many_associations(resource, associations, options)
- case associations
- when Hash
- associations.each do |association,has_many|
- map_has_many_associations(resource, association, options.merge(:has_many => has_many))
- end
- when Array
- associations.each do |association|
- map_has_many_associations(resource, association, options)
- end
- when Symbol, String
- resources(associations, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :has_many => options[:has_many]))
- else
- end
- end
-
- def map_collection_actions(map, resource)
- resource.collection_methods.each do |method, actions|
- actions.each do |action|
- [method].flatten.each do |m|
- action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash)
- action_path ||= action
-
- map_resource_routes(map, resource, action, "#{resource.path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.name_prefix}#{resource.plural}", m)
- end
- end
- end
- end
-
- def map_default_collection_actions(map, resource)
- index_route_name = "#{resource.name_prefix}#{resource.plural}"
-
- if resource.uncountable?
- index_route_name << "_index"
- end
-
- map_resource_routes(map, resource, :index, resource.path, index_route_name)
- map_resource_routes(map, resource, :create, resource.path, index_route_name)
- end
-
- def map_default_singleton_actions(map, resource)
- map_resource_routes(map, resource, :create, resource.path, "#{resource.shallow_name_prefix}#{resource.singular}")
- end
-
- def map_new_actions(map, resource)
- resource.new_methods.each do |method, actions|
- actions.each do |action|
- route_path = resource.new_path
- route_name = "new_#{resource.name_prefix}#{resource.singular}"
-
- unless action == :new
- route_path = "#{route_path}#{resource.action_separator}#{action}"
- route_name = "#{action}_#{route_name}"
- end
-
- map_resource_routes(map, resource, action, route_path, route_name, method)
- end
- end
- end
-
- def map_member_actions(map, resource)
- resource.member_methods.each do |method, actions|
- actions.each do |action|
- [method].flatten.each do |m|
- action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash)
- action_path ||= @set.resources_path_names[action] || action
-
- map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m, { :force_id => true })
- end
- end
- end
-
- route_path = "#{resource.shallow_name_prefix}#{resource.singular}"
- map_resource_routes(map, resource, :show, resource.member_path, route_path)
- map_resource_routes(map, resource, :update, resource.member_path, route_path)
- map_resource_routes(map, resource, :destroy, resource.member_path, route_path)
- end
-
- def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil, resource_options = {} )
- if resource.has_action?(action)
- action_options = action_options_for(action, resource, method, resource_options)
- formatted_route_path = "#{route_path}.:format"
-
- if route_name && @set.named_routes[route_name.to_sym].nil?
- map.named_route(route_name, formatted_route_path, action_options)
- else
- map.connect(formatted_route_path, action_options)
- end
- end
- end
-
- def add_conditions_for(conditions, method)
- {:conditions => conditions.dup}.tap do |options|
- options[:conditions][:method] = method unless method == :any
- end
- end
-
- def action_options_for(action, resource, method = nil, resource_options = {})
- default_options = { :action => action.to_s }
- require_id = !resource.kind_of?(SingletonResource)
- force_id = resource_options[:force_id] && !resource.kind_of?(SingletonResource)
-
- case default_options[:action]
- when "index", "new"; default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements)
- when "create"; default_options.merge(add_conditions_for(resource.conditions, method || :post)).merge(resource.requirements)
- when "show", "edit"; default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements(require_id))
- when "update"; default_options.merge(add_conditions_for(resource.conditions, method || :put)).merge(resource.requirements(require_id))
- when "destroy"; default_options.merge(add_conditions_for(resource.conditions, method || :delete)).merge(resource.requirements(require_id))
- else default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements(force_id))
- end
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index c118c72440..14c424f24b 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,6 +1,8 @@
require 'erb'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/blank'
+require 'active_support/inflector'
+require 'action_dispatch/routing/redirection'
module ActionDispatch
module Routing
@@ -20,27 +22,37 @@ module ActionDispatch
@app, @constraints, @request = app, constraints, request
end
- def call(env)
+ def matches?(env)
req = @request.new(env)
@constraints.each { |constraint|
if constraint.respond_to?(:matches?) && !constraint.matches?(req)
- return [ 404, {'X-Cascade' => 'pass'}, [] ]
- elsif constraint.respond_to?(:call) && !constraint.call(req)
- return [ 404, {'X-Cascade' => 'pass'}, [] ]
+ return false
+ elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req))
+ return false
end
}
- @app.call(env)
+ return true
+ 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]
- def initialize(set, scope, args)
- @set, @scope = set, scope
- @path, @options = extract_path_and_options(args)
+ def initialize(set, scope, path, options)
+ @set, @scope = set, scope
+ @options = (@scope[:options] || {}).merge(options)
+ @path = normalize_path(path)
normalize_options!
end
@@ -49,28 +61,6 @@ module ActionDispatch
end
private
- def extract_path_and_options(args)
- options = args.extract_options!
-
- if using_to_shorthand?(args, options)
- path, to = options.find { |name, value| name.is_a?(String) }
- options.merge!(:to => to).delete(path) if path
- else
- path = args.first
- end
-
- if path.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.reverse_merge!(:controller => /.+?/)
- end
-
- [ normalize_path(path), options ]
- end
def normalize_options!
path_without_format = @path.sub(/\(\.:format\)$/, '')
@@ -78,15 +68,21 @@ module ActionDispatch
if using_match_shorthand?(path_without_format, @options)
to_shorthand = @options[:to].blank?
@options[:to] ||= path_without_format[1..-1].sub(%r{/([^/]*)$}, '#\1')
- @options[:as] ||= path_without_format[1..-1].gsub("/", "_")
end
@options.merge!(default_controller_and_action(to_shorthand))
- end
- # match "account" => "account#index"
- def using_to_shorthand?(args, options)
- args.empty? && options.present?
+ requirements.each do |name, requirement|
+ # segment_keys.include?(k.to_s) || k == :controller
+ next unless Regexp === requirement && !constraints[name]
+
+ if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
+ raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
+ end
+ if requirement.multiline?
+ raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
+ end
+ end
end
# match "account/overview"
@@ -95,8 +91,27 @@ module ActionDispatch
end
def normalize_path(path)
- raise ArgumentError, "path is required" if @scope[:path].blank? && path.blank?
- Mapper.normalize_path("#{@scope[:path]}/#{path}")
+ raise ArgumentError, "path is required" if path.blank?
+ path = Mapper.normalize_path(path)
+
+ if path.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.reverse_merge!(:controller => /.+?/)
+ end
+
+ if @options[:format] == false
+ @options.delete(:format)
+ path
+ elsif path.include?(":format") || path.end_with?('/') || path.match(/^\/?\*/)
+ path
+ else
+ "#{path}(.:format)"
+ end
end
def app
@@ -142,6 +157,10 @@ module ActionDispatch
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)
@@ -153,21 +172,21 @@ module ActionDispatch
raise ArgumentError, "missing :action"
end
- { :controller => controller, :action => action }.tap do |hash|
- hash.delete(:controller) if hash[:controller].blank?
- hash.delete(:action) if hash[:action].blank?
- end
+ hash = {}
+ hash[:controller] = controller unless controller.blank?
+ hash[:action] = action unless action.blank?
+ hash
end
end
def blocks
+ block = @scope[:blocks] || []
+
if @options[:constraints].present? && !@options[:constraints].is_a?(Hash)
- block = @options[:constraints]
- else
- block = nil
+ block << @options[:constraints]
end
- ((@scope[:blocks] || []) + [ block ]).compact
+ block
end
def constraints
@@ -176,8 +195,8 @@ module ActionDispatch
def request_method_condition
if via = @options[:via]
- via = Array(via).map { |m| m.to_s.upcase }
- { :request_method => Regexp.union(*via) }
+ list = Array(via).map { |m| m.to_s.dasherize.upcase }
+ { :request_method => list }
else
{ }
end
@@ -219,21 +238,165 @@ module ActionDispatch
path
end
- module Base
- def initialize(set) #:nodoc:
- @set = set
- end
+ def self.normalize_name(name)
+ normalize_path(name)[1..-1].gsub("/", "_")
+ 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 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 '/', options.reverse_merge(:as => :root)
end
- def match(*args)
- mapping = Mapping.new(@set, @scope, args).to_route
- @set.add_route(*mapping)
+ # Matches a url pattern to one or more routes. Any symbols in a pattern
+ # are interpreted as url query parameters and thus available as +params+
+ # in an action:
+ #
+ # # sets :controller, :action and :id in params
+ # match ':controller/:action/:id'
+ #
+ # Two of these symbols are special, +:controller+ maps to the controller
+ # and +:action+ to the controller's action. A pattern can also map
+ # wildcard segments (globs) to params:
+ #
+ # match 'songs/*category/:title' => 'songs#show'
+ #
+ # # 'songs/rock/classic/stairway-to-heaven' sets
+ # # params[:category] = 'rock/classic'
+ # # params[:title] = 'stairway-to-heaven'
+ #
+ # When a pattern points to an internal route, the route's +:action+ and
+ # +:controller+ should be set in options or hash shorthand. Examples:
+ #
+ # match 'photos/:id' => 'photos#show'
+ # match 'photos/:id', :to => 'photos#show'
+ # match 'photos/:id', :controller => 'photos', :action => 'show'
+ #
+ # A pattern can also point to a +Rack+ endpoint i.e. anything that
+ # responds to +call+:
+ #
+ # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon" }
+ # match 'photos/:id' => PhotoRackApp
+ # # Yes, controller actions are just rack endpoints
+ # match 'photos/:id' => PhotosController.action(:show)
+ #
+ # === Options
+ #
+ # Any options not seen here are passed on as params with the url.
+ #
+ # [:controller]
+ # The route's controller.
+ #
+ # [:action]
+ # The route's action.
+ #
+ # [:path]
+ # The path prefix for the routes.
+ #
+ # [:module]
+ # The namespace for :controller.
+ #
+ # match 'path' => 'c#a', :module => 'sekret', :controller => 'posts'
+ # #=> Sekret::PostsController
+ #
+ # See <tt>Scoping#namespace</tt> for its scope equivalent.
+ #
+ # [:as]
+ # The name used to generate routing helpers.
+ #
+ # [:via]
+ # Allowed HTTP verb(s) for route.
+ #
+ # match 'path' => 'c#a', :via => :get
+ # match 'path' => 'c#a', :via => [:get, :post]
+ #
+ # [:to]
+ # Points to a +Rack+ endpoint. Can be an object that responds to
+ # +call+ or a string representing a controller's action.
+ #
+ # match 'path', :to => 'controller#action'
+ # match 'path', :to => lambda { [200, {}, "Success!"] }
+ # match 'path', :to => RackApp
+ #
+ # [:on]
+ # Shorthand for wrapping routes in a specific RESTful context. Valid
+ # values are :member, :collection, and :new. Only use within
+ # <tt>resource(s)</tt> block. For example:
+ #
+ # resource :bar do
+ # match 'foo' => 'c#a', :on => :member, :via => [:get, :post]
+ # end
+ #
+ # Is equivalent to:
+ #
+ # resource :bar do
+ # member do
+ # match 'foo' => 'c#a', :via => [:get, :post]
+ # end
+ # end
+ #
+ # [:constraints]
+ # Constrains parameters with a hash of regular expressions or an
+ # object that responds to #matches?
+ #
+ # match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ }
+ #
+ # class Blacklist
+ # def matches?(request) request.remote_ip == '1.2.3.4' end
+ # end
+ # match 'path' => 'c#a', :constraints => Blacklist.new
+ #
+ # See <tt>Scoping#constraints</tt> for more examples with its scope
+ # equivalent.
+ #
+ # [:defaults]
+ # Sets defaults for parameters
+ #
+ # # Sets params[:format] to 'jpg' by default
+ # match 'path' => 'c#a', :defaults => { :format => 'jpg' }
+ #
+ # See <tt>Scoping#defaults</tt> for its scope equivalent.
+ #
+ # [:anchor]
+ # Boolean to anchor a #match 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' => 'c#a', :anchor => false
+ def match(path, options=nil)
+ mapping = Mapping.new(@set, @scope, path, options || {})
+ app, conditions, requirements, defaults, as, anchor = mapping.to_route
+ @set.add_route(app, conditions, requirements, defaults, as, anchor)
self
end
+ # Mount a Rack-based application to be used within the application.
+ #
+ # 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)
@@ -245,7 +408,11 @@ module ActionDispatch
raise "A rack application must be specified" unless path
- match(path, options.merge(:to => app, :anchor => false))
+ options[:as] ||= app_name(app)
+
+ match(path, options.merge(:to => app, :anchor => false, :format => false))
+
+ define_generate_prefix(app, options[:as])
self
end
@@ -253,55 +420,83 @@ module ActionDispatch
@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).gsub("/", "_")
+ 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.class_eval do
+ 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 <tt>Base#match</tt>.
+ #
+ # Example:
+ #
+ # 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 <tt>Base#match</tt>.
+ #
+ # Example:
+ #
+ # post 'bacon', :to => 'food#bacon'
def post(*args, &block)
map_method(:post, *args, &block)
end
+ # Define a route that only recognizes HTTP PUT.
+ # For supported arguments, see <tt>Base#match</tt>.
+ #
+ # Example:
+ #
+ # put 'bacon', :to => 'food#bacon'
def put(*args, &block)
map_method(:put, *args, &block)
end
+ # Define a route that only recognizes HTTP PUT.
+ # For supported arguments, see <tt>Base#match</tt>.
+ #
+ # Example:
+ #
+ # delete 'broccoli', :to => 'food#broccoli'
def delete(*args, &block)
map_method(:delete, *args, &block)
end
- def redirect(*args, &block)
- options = args.last.is_a?(Hash) ? args.pop : {}
-
- path = args.shift || block
- path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
- status = options[:status] || 301
-
- lambda do |env|
- req = Request.new(env)
-
- params = [req.symbolized_path_parameters]
- params << req if path_proc.arity > 1
-
- uri = URI.parse(path_proc.call(*params))
- uri.scheme ||= req.scheme
- uri.host ||= req.host
- uri.port ||= req.port unless req.port == 80
-
- body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
-
- headers = {
- 'Location' => uri.to_s,
- 'Content-Type' => 'text/html',
- 'Content-Length' => body.length.to_s
- }
-
- [ status, headers, [body] ]
- end
- end
-
private
def map_method(method, *args, &block)
options = args.extract_options!
@@ -312,28 +507,98 @@ module ActionDispatch
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 app/controllers/admin 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 Admin::PostsController, Rails will create:
+ #
+ # GET /admin/posts
+ # GET /admin/posts/new
+ # POST /admin/posts
+ # GET /admin/posts/1
+ # GET /admin/posts/1/edit
+ # PUT /admin/posts/1
+ # DELETE /admin/posts/1
+ #
+ # If you want to route /posts (without the prefix /admin) to
+ # Admin::PostsController, 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"
+ #
+ # 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
+ # PUT /admin/posts/1
+ # DELETE /admin/posts/1
module Scoping
- def initialize(*args) #:nodoc:
- @scope = {}
- super
- end
-
+ # 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 /rails/projects/2,
+ # rather than /accounts/rails/projects/2.
+ #
+ # === Options
+ #
+ # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
+ #
+ # === Examples
+ #
+ # # route /posts (without the prefix /admin) to Admin::PostsController
+ # 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!
options = options.dup
- if name_prefix = options.delete(:name_prefix)
- options[:as] ||= name_prefix
- ActiveSupport::Deprecation.warn ":name_prefix was deprecated in the new router syntax. Use :as instead.", caller
- end
-
- case args.first
- when String
- options[:path] = args.first
- when Symbol
- options[:controller] = args.first
- end
-
+ options[:path] = args.first if args.first.is_a?(String)
recover = {}
options[:constraints] ||= {}
@@ -365,10 +630,57 @@ module ActionDispatch
@scope[:blocks] = recover[:block]
end
- def controller(controller)
- scope(controller.to_sym) { yield }
+ # Scopes routes to a specific controller
+ #
+ # Example:
+ # 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) {:action=>"index", :controller=>"admin/posts"}
+ # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"}
+ # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"}
+ # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"}
+ # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"}
+ # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"}
+ # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"}
+ #
+ # === 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>.
+ #
+ # === Examples
+ #
+ # # accessible through /sekret/posts rather than /admin/posts
+ # namespace :admin, :path => "sekret" do
+ # resources :posts
+ # end
+ #
+ # # maps to Sekret::PostsController rather than Admin::PostsController
+ # 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,
@@ -376,95 +688,178 @@ module ActionDispatch
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
+ #
+ # === 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
- def match(*args)
- options = args.extract_options!
-
- options = (@scope[:options] || {}).merge(options)
-
- if @scope[:as] && !options[:as].blank?
- options[:as] = "#{@scope[:as]}_#{options[:as]}"
- elsif @scope[:as] && options[:as] == ""
- options[:as] = @scope[:as].to_s
- end
-
- args.push(options)
- super(*args)
- end
-
private
- def scope_options
+ def scope_options #:nodoc:
@scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym }
end
- def merge_path_scope(parent, child)
+ def merge_path_scope(parent, child) #:nodoc:
Mapper.normalize_path("#{parent}/#{child}")
end
- def merge_shallow_path_scope(parent, child)
+ def merge_shallow_path_scope(parent, child) #:nodoc:
Mapper.normalize_path("#{parent}/#{child}")
end
- def merge_as_scope(parent, child)
+ def merge_as_scope(parent, child) #:nodoc:
parent ? "#{parent}_#{child}" : child
end
- def merge_shallow_prefix_scope(parent, child)
+ def merge_shallow_prefix_scope(parent, child) #:nodoc:
parent ? "#{parent}_#{child}" : child
end
- def merge_module_scope(parent, child)
+ def merge_module_scope(parent, child) #:nodoc:
parent ? "#{parent}/#{child}" : child
end
- def merge_controller_scope(parent, child)
+ def merge_controller_scope(parent, child) #:nodoc:
child
end
- def merge_path_names_scope(parent, child)
+ def merge_path_names_scope(parent, child) #:nodoc:
merge_options_scope(parent, child)
end
- def merge_constraints_scope(parent, child)
+ def merge_constraints_scope(parent, child) #:nodoc:
merge_options_scope(parent, child)
end
- def merge_defaults_scope(parent, child)
+ def merge_defaults_scope(parent, child) #:nodoc:
merge_options_scope(parent, child)
end
- def merge_blocks_scope(parent, child)
+ def merge_blocks_scope(parent, child) #:nodoc:
merged = parent ? parent.dup : []
merged << child if child
merged
end
- def merge_options_scope(parent, child)
+ def merge_options_scope(parent, child) #:nodoc:
(parent || {}).except(*override_keys(child)).merge(child)
end
- def merge_shallow_scope(parent, child)
+ def merge_shallow_scope(parent, child) #:nodoc:
child ? true : false
end
- def override_keys(child)
+ 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
+ # app/controllers/admin 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]
- CANONICAL_ACTIONS = [:index, :create, :new, :show, :update, :destroy]
- RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except]
+ VALID_ON_OPTIONS = [:new, :collection, :member]
+ RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except]
+ CANONICAL_ACTIONS = %w(index create new show update destroy)
class Resource #:nodoc:
DEFAULT_ACTIONS = [:index, :create, :new, :show, :update, :destroy, :edit]
@@ -473,7 +868,7 @@ module ActionDispatch
def initialize(entities, options = {})
@name = entities.to_s
- @path = options.delete(:path) || @name
+ @path = (options.delete(:path) || @name).to_s
@controller = (options.delete(:controller) || @name).to_s
@as = options.delete(:as)
@options = options
@@ -498,18 +893,17 @@ module ActionDispatch
end
def plural
- name.to_s.pluralize
+ @plural ||= name.to_s
end
def singular
- name.to_s.singularize
+ @singular ||= name.to_s.singularize
end
- def member_name
- singular
- end
+ alias :member_name :singular
- # Checks for uncountable plurals, and appends "_index" if they're.
+ # Checks for uncountable plurals, and appends "_index" if the plural
+ # and singular form are the same.
def collection_name
singular == plural ? "#{plural}_index" : plural
end
@@ -518,9 +912,7 @@ module ActionDispatch
{ :controller => controller }
end
- def collection_scope
- path
- end
+ alias :collection_scope :path
def member_scope
"#{path}/:id"
@@ -540,33 +932,54 @@ module ActionDispatch
DEFAULT_ACTIONS = [:show, :create, :update, :destroy, :new, :edit]
def initialize(entities, options)
+ @as = nil
@name = entities.to_s
- @path = options.delete(:path) || @name
+ @path = (options.delete(:path) || @name).to_s
@controller = (options.delete(:controller) || plural).to_s
@as = options.delete(:as)
@options = options
end
- def member_name
- name
+ def plural
+ @plural ||= name.to_s.pluralize
end
- alias :collection_name :member_name
- def member_scope
- path
+ def singular
+ @singular ||= name.to_s
end
- alias :nested_scope :member_scope
- end
- def initialize(*args) #:nodoc:
- super
- @scope[:path_names] = @set.resources_path_names
+ 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
+ # PUT /geocoder
+ # DELETE /geocoder
+ #
+ # === Options
+ # Takes same options as +resources+.
def resource(*resources, &block)
options = resources.extract_options!
@@ -577,25 +990,121 @@ module ActionDispatch
resource_scope(SingletonResource.new(resources.pop, options)) do
yield if block_given?
- collection_scope do
+ collection do
post :create
end if parent_resource.actions.include?(:create)
- new_scope do
+ new do
get :new
end if parent_resource.actions.include?(:new)
- member_scope do
+ member do
+ get :edit if parent_resource.actions.include?(:edit)
get :show if parent_resource.actions.include?(:show)
put :update if parent_resource.actions.include?(:update)
delete :destroy if parent_resource.actions.include?(:destroy)
- get :edit if parent_resource.actions.include?(:edit)
end
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/new
+ # POST /photos
+ # GET /photos/:id
+ # GET /photos/:id/edit
+ # 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/:id/comments/new
+ # POST /photos/:id/comments
+ # GET /photos/:id/comments/:id
+ # GET /photos/:id/comments/:id/edit
+ # PUT /photos/:id/comments/:id
+ # DELETE /photos/:id/comments/:id
+ #
+ # === Options
+ # Takes same options as <tt>Base#match</tt> as well as:
+ #
+ # [:path_names]
+ # Allows you to change the paths of the seven default actions.
+ # Paths not specified are not changed.
+ #
+ # resources :posts, :path_names => { :new => "brand_new" }
+ #
+ # The above example will now change /posts/new to /posts/brand_new
+ #
+ # [: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
+ # end
+ # resources :comments
+ #
+ # [:shallow_path]
+ # Prefixes nested shallow routes with the specified path.
+ #
+ # scope :shallow_path => "sekret" do
+ # resources :posts do
+ # resources :comments, :shallow => true
+ # end
+ # end
+ #
+ # The +comments+ resource here will have the following routes generated for it:
+ #
+ # post_comments GET /sekret/posts/:post_id/comments(.:format)
+ # post_comments POST /sekret/posts/:post_id/comments(.:format)
+ # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format)
+ # edit_comment GET /sekret/comments/:id/edit(.:format)
+ # comment GET /sekret/comments/:id(.:format)
+ # comment PUT /sekret/comments/:id(.:format)
+ # comment DELETE /sekret/comments/:id(.:format)
+ #
+ # === Examples
+ #
+ # # routes call Admin::PostsController
+ # resources :posts, :module => "admin"
+ #
+ # # resource actions are at /admin/posts.
+ # resources :posts, :path => "admin"
def resources(*resources, &block)
options = resources.extract_options!
@@ -606,43 +1115,70 @@ module ActionDispatch
resource_scope(Resource.new(resources.pop, options)) do
yield if block_given?
- collection_scope do
+ collection do
get :index if parent_resource.actions.include?(:index)
post :create if parent_resource.actions.include?(:create)
end
- new_scope do
+ new do
get :new
end if parent_resource.actions.include?(:new)
- member_scope do
+ member do
+ get :edit if parent_resource.actions.include?(:edit)
get :show if parent_resource.actions.include?(:show)
put :update if parent_resource.actions.include?(:update)
delete :destroy if parent_resource.actions.include?(:destroy)
- get :edit if parent_resource.actions.include?(:edit)
end
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 @scope[:scope_level] == :resources
- raise ArgumentError, "can't use collection outside resources scope"
+ unless resource_scope?
+ raise ArgumentError, "can't use collection outside resource(s) scope"
end
- collection_scope do
- yield
+ 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
- member_scope do
- yield
+ with_scope_level(:member) do
+ scope(parent_resource.member_scope) do
+ yield
+ end
end
end
@@ -651,8 +1187,10 @@ module ActionDispatch
raise ArgumentError, "can't use new outside resource(s) scope"
end
- new_scope do
- yield
+ with_scope_level(:new) do
+ scope(parent_resource.new_scope(action_path(:new))) do
+ yield
+ end
end
end
@@ -678,6 +1216,7 @@ module ActionDispatch
end
end
+ # See ActionDispatch::Routing::Mapper::Scoping#namespace
def namespace(path, options = {})
if resource_scope?
nested { super }
@@ -687,7 +1226,7 @@ module ActionDispatch
end
def shallow
- scope(:shallow => true) do
+ scope(:shallow => true, :shallow_path => @scope[:path]) do
yield
end
end
@@ -713,46 +1252,36 @@ module ActionDispatch
raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
end
- if @scope[:scope_level] == :resource
+ if @scope[:scope_level] == :resources
+ args.push(options)
+ return nested { match(*args) }
+ elsif @scope[:scope_level] == :resource
args.push(options)
return member { match(*args) }
end
- path = options.delete(:path)
action = args.first
+ path = path_for_action(action, options.delete(:path))
- if action.is_a?(Symbol)
- path = path_for_action(action, path)
- options[:to] ||= action
- options[:as] = name_for_action(action, options[:as])
-
- with_exclusive_scope do
- return super(path, options)
- end
- elsif resource_method_scope?
- path = path_for_custom_action
- options[:as] = name_for_action(options[:as]) if options[:as]
- args.push(options)
-
- with_exclusive_scope do
- scope(path) do
- return super
- end
- end
+ if action.to_s =~ /^[\w\/]+$/
+ options[:action] ||= action unless action.to_s.include?("/")
+ else
+ action = nil
end
- if resource_scope?
- raise ArgumentError, "can't define route directly in resource(s) scope"
+ if options.key?(:as) && !options[:as]
+ options.delete(:as)
+ else
+ options[:as] = name_for_action(options[:as], action)
end
- args.push(options)
- super
+ super(path, options)
end
def root(options={})
if @scope[:scope_level] == :resources
- with_scope_level(:nested) do
- scope(parent_resource.path, :as => parent_resource.collection_name) do
+ with_scope_level(:root) do
+ scope(parent_resource.path) do
super(options)
end
end
@@ -767,12 +1296,21 @@ module ActionDispatch
@scope[:scope_level_resource]
end
- def apply_common_behavior_for(method, resources, options, &block)
+ 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
@@ -785,33 +1323,26 @@ module ActionDispatch
options.merge!(scope_action_options) if scope_action_options?
end
- if resource_scope?
- nested do
- send(method, resources.pop, options, &block)
- end
- return true
- end
-
false
end
- def action_options?(options)
+ def action_options?(options) #:nodoc:
options[:only] || options[:except]
end
- def scope_action_options?
+ def scope_action_options? #:nodoc:
@scope[:options].is_a?(Hash) && (@scope[:options][:only] || @scope[:options][:except])
end
- def scope_action_options
+ def scope_action_options #:nodoc:
@scope[:options].slice(:only, :except)
end
- def resource_scope?
+ def resource_scope? #:nodoc:
[:resource, :resources].include?(@scope[:scope_level])
end
- def resource_method_scope?
+ def resource_method_scope? #:nodoc:
[:collection, :member, :new].include?(@scope[:scope_level])
end
@@ -837,7 +1368,7 @@ module ActionDispatch
@scope[:scope_level_resource] = old_resource
end
- def resource_scope(resource)
+ def resource_scope(resource) #:nodoc:
with_scope_level(resource.is_a?(SingletonResource) ? :resource : :resources, resource) do
scope(parent_resource.resource_scope) do
yield
@@ -845,116 +1376,108 @@ module ActionDispatch
end
end
- def new_scope
- with_scope_level(:new) do
- scope(parent_resource.new_scope(action_path(:new))) do
- yield
- end
- end
- end
-
- def collection_scope
- with_scope_level(:collection) do
- scope(parent_resource.collection_scope) do
- yield
- end
- end
- end
-
- def member_scope
- with_scope_level(:member) do
- scope(parent_resource.member_scope) do
- yield
- end
- end
- end
-
- def nested_options
+ def nested_options #:nodoc:
{}.tap do |options|
options[:as] = parent_resource.member_name
options[:constraints] = { "#{parent_resource.singular}_id".to_sym => id_constraint } if id_constraint?
end
end
- def id_constraint?
- @scope[:id].is_a?(Regexp) || (@scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp))
+ def id_constraint? #:nodoc:
+ @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)
end
- def id_constraint
- @scope[:id] || @scope[:constraints][:id]
+ def id_constraint #:nodoc:
+ @scope[:constraints][:id]
end
- def canonical_action?(action, flag)
- flag && CANONICAL_ACTIONS.include?(action)
+ def canonical_action?(action, flag) #:nodoc:
+ flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
end
- def shallow_scoping?
+ def shallow_scoping? #:nodoc:
shallow? && @scope[:scope_level] == :member
end
- def path_for_action(action, path)
+ def path_for_action(action, path) #:nodoc:
prefix = shallow_scoping? ?
"#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path]
- if canonical_action?(action, path.blank?)
- "#{prefix}(.:format)"
- else
- "#{prefix}/#{action_path(action, path)}(.:format)"
- end
- end
-
- def path_for_custom_action
- if shallow_scoping?
- "#{@scope[:shallow_path]}/#{parent_resource.path}/:id"
+ path = if canonical_action?(action, path.blank?)
+ prefix.to_s
else
- @scope[:path]
+ "#{prefix}/#{action_path(action, path)}"
end
end
- def action_path(name, path = nil)
+ def action_path(name, path = nil) #:nodoc:
path || @scope[:path_names][name.to_sym] || name.to_s
end
- def prefix_name_for_action(action, as)
- if as.present?
- "#{as}_"
- elsif as
- ""
+ def prefix_name_for_action(as, action) #:nodoc:
+ if as
+ as.to_s
elsif !canonical_action?(action, @scope[:scope_level])
- "#{action}_"
+ action.to_s
end
end
- def name_for_action(action, as=nil)
- prefix = prefix_name_for_action(action, as)
+ 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 if as.nil? && action.nil?
+
collection_name = parent_resource.collection_name
member_name = parent_resource.member_name
- name_prefix = "#{name_prefix}_" if name_prefix.present?
end
- case @scope[:scope_level]
+ name = case @scope[:scope_level]
+ when :nested
+ [name_prefix, prefix]
when :collection
- "#{prefix}#{name_prefix}#{collection_name}"
+ [prefix, name_prefix, collection_name]
when :new
- "#{prefix}new_#{name_prefix}#{member_name}"
+ [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
- if shallow_scoping?
- shallow_prefix = "#{@scope[:shallow_prefix]}_" if @scope[:shallow_prefix].present?
- "#{prefix}#{shallow_prefix}#{member_name}"
- else
- "#{prefix}#{name_prefix}#{member_name}"
- end
+ [name_prefix, member_name, prefix]
end
+
+ candidate = name.select(&:present?).join("_").presence
+ candidate unless as.nil? && @set.routes.find { |r| r.name == candidate }
+ end
+ end
+
+ module Shorthand #:nodoc:
+ def match(*args)
+ if args.size == 1 && args.last.is_a?(Hash)
+ options = args.pop
+ path, to = options.find { |name, value| name.is_a?(String) }
+ options.merge!(:to => to).delete(path)
+ super(path, options)
+ else
+ super
end
+ end
+ end
+
+ def initialize(set) #:nodoc:
+ @set = set
+ @scope = { :path_names => @set.resources_path_names }
end
include Base
include HttpHelpers
+ include Redirection
include Scoping
include Resources
+ include Shorthand
end
end
end
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index 31dba835ac..82c4fadb50 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -17,7 +17,7 @@ module ActionDispatch
#
# == Usage within the framework
#
- # Polymorphic URL helpers are used in a number of places throughout the Rails 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>;
@@ -42,6 +42,18 @@ module ActionDispatch
#
# edit_polymorphic_path(@post) # => "/posts/1/edit"
# polymorphic_path(@post, :format => :pdf) # => "/posts/1.pdf"
+ #
+ # == Using with mounted engines
+ #
+ # If you use mounted engine, there is a possibility that you will need to use
+ # polymorphic_url pointing at engine's routes. To do that, just pass proxy used
+ # to reach engine's routes as a first argument:
+ #
+ # For example:
+ #
+ # polymorphic_url([blog, @post]) # it will call blog.post_path(@post)
+ # form_for([blog, @post]) # => "/blog/posts/1
+ #
module PolymorphicRoutes
# Constructs a call to a named RESTful route for the given record and returns the
# resulting URL string. For example:
@@ -78,19 +90,20 @@ module ActionDispatch
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 = record.to_model if record.respond_to?(:to_model)
- args = case record_or_hash_or_array
- when Hash; [ record_or_hash_or_array ]
- when Array; record_or_hash_or_array.dup
- else [ record_or_hash_or_array ]
- end
+ args = Array === record_or_hash_or_array ?
+ record_or_hash_or_array.dup :
+ [ record_or_hash_or_array ]
- inflection = if options[:action].to_s == "new"
+ inflection = if options[:action] && options[:action].to_s == "new"
args.pop
:singular
elsif (record.respond_to?(:persisted?) && !record.persisted?)
@@ -111,7 +124,14 @@ module ActionDispatch
args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
end
- send(named_route, *args)
+ if proxy
+ proxy.send(named_route, *args)
+ else
+ # we need to use url_for, because polymorphic_url can be used in context of other than
+ # current routes (e.g. engine's routes). As named routes from engine are not included
+ # calling engine's named route directly would fail.
+ url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args)
+ end
end
# Returns the path component of a URL for the given record. It uses
@@ -146,31 +166,31 @@ module ActionDispatch
end
def build_named_route_call(records, inflection, options = {})
- unless records.is_a?(Array)
- record = extract_record(records)
- route = ''
- else
+ if records.is_a?(Array)
record = records.pop
- route = records.inject("") do |string, parent|
+ route = records.map do |parent|
if parent.is_a?(Symbol) || parent.is_a?(String)
- string << "#{parent}_"
+ parent
else
- string << ActiveModel::Naming.plural(parent).singularize
- string << "_"
+ ActiveModel::Naming.route_key(parent).singularize
end
end
+ else
+ record = extract_record(records)
+ route = []
end
if record.is_a?(Symbol) || record.is_a?(String)
- route << "#{record}_"
+ route << record
else
- route << ActiveModel::Naming.plural(record)
- route = route.singularize if inflection == :singular
- route << "_"
- route << "index_" if ActiveModel::Naming.uncountable?(record) && inflection == :plural
+ route << ActiveModel::Naming.route_key(record)
+ route = [route.join("_").singularize] if inflection == :singular
+ route << "index" if ActiveModel::Naming.uncountable?(record) && inflection == :plural
end
- action_prefix(options) + route + routing_type(options).to_s
+ route << routing_type(options)
+
+ action_prefix(options) + route.join("_")
end
def extract_record(record_or_hash_or_array)
diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb
new file mode 100644
index 0000000000..804991ad5f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/redirection.rb
@@ -0,0 +1,110 @@
+require 'action_dispatch/http/request'
+
+module ActionDispatch
+ module Routing
+ module Redirection
+
+ # Redirect any path to another path:
+ #
+ # match "/stories" => redirect("/posts")
+ #
+ # You can also use interpolation in the supplied redirect argument:
+ #
+ # match '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.
+ #
+ # match 'jokes/:number', :to => redirect do |params, request|
+ # path = (params[:number].to_i.even? ? "/wheres-the-beef" : "/i-love-lamp")
+ # "http://#{request.host_with_port}/#{path}"
+ # end
+ #
+ # 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.
+ #
+ # match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}')
+ # match '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.
+ #
+ # match 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
+ #
+ def redirect(*args, &block)
+ options = args.last.is_a?(Hash) ? args.pop : {}
+ status = options.delete(:status) || 301
+
+ path = args.shift
+
+ path_proc = if path.is_a?(String)
+ proc { |params| (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) }
+ elsif options.any?
+ options_proc(options)
+ elsif path.respond_to?(:call)
+ proc { |params, request| path.call(params, request) }
+ elsif block
+ block
+ else
+ raise ArgumentError, "redirection argument not supported"
+ end
+
+ redirection_proc(status, path_proc)
+ end
+
+ private
+
+ def options_proc(options)
+ proc do |params, request|
+ path = if options[:path].nil?
+ request.path
+ elsif params.empty? || !options[:path].match(/%\{\w*\}/)
+ options.delete(:path)
+ else
+ (options.delete(:path) % params)
+ end
+
+ default_options = {
+ :protocol => request.protocol,
+ :host => request.host,
+ :port => request.optional_port,
+ :path => path,
+ :params => request.query_parameters
+ }
+
+ ActionDispatch::Http::URL.url_for(options.reverse_merge(default_options))
+ end
+ end
+
+ def redirection_proc(status, path_proc)
+ lambda do |env|
+ req = Request.new(env)
+
+ params = [req.symbolized_path_parameters]
+ params << req if path_proc.arity > 1
+
+ uri = URI.parse(path_proc.call(*params))
+ uri.scheme ||= req.scheme
+ uri.host ||= req.host
+ uri.port ||= req.port unless req.standard_port?
+
+ body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
+
+ headers = {
+ 'Location' => uri.to_s,
+ 'Content-Type' => 'text/html',
+ 'Content-Length' => body.length.to_s
+ }
+
+ [ status, headers, [body] ]
+ end
+ end
+
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb
index aefebf8f80..a049510182 100644
--- a/actionpack/lib/action_dispatch/routing/route.rb
+++ b/actionpack/lib/action_dispatch/routing/route.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/module/deprecation'
+
module ActionDispatch
module Routing
class Route #:nodoc:
@@ -10,6 +12,8 @@ module ActionDispatch
@defaults = defaults
@name = name
+ # FIXME: we should not be doing this much work in a constructor.
+
@requirements = requirements.merge(defaults)
@requirements.delete(:controller) if @requirements[:controller].is_a?(Regexp)
@requirements.delete_if { |k, v|
@@ -21,24 +25,22 @@ module ActionDispatch
conditions[:path_info] = ::Rack::Mount::Strexp.compile(path, requirements, SEPARATORS, anchor)
end
- @conditions = conditions.inject({}) { |h, (k, v)|
- h[k] = Rack::Mount::RegexpWithNamedGroups.new(v)
- h
- }
+ @verbs = conditions[:request_method] || []
+ @conditions = conditions.dup
+
+ # Rack-Mount requires that :request_method be a regular expression.
+ # :request_method represents the HTTP verb that matches this route.
+ #
+ # Here we munge values before they get sent on to rack-mount.
+ @conditions[:request_method] = %r[^#{verb}$] unless @verbs.empty?
+ @conditions[:path_info] = Rack::Mount::RegexpWithNamedGroups.new(@conditions[:path_info]) if @conditions[:path_info]
@conditions.delete_if{ |k,v| k != :path_info && !valid_condition?(k) }
@requirements.delete_if{ |k,v| !valid_condition?(k) }
end
def verb
- if method = conditions[:request_method]
- case method
- when Regexp
- method.source.upcase
- else
- method.to_s.upcase
- end
- end
+ @verbs.join '|'
end
def segment_keys
@@ -48,6 +50,7 @@ module ActionDispatch
def to_a
[@app, @conditions, @defaults, @name]
end
+ deprecate :to_a
def to_s
@to_s ||= begin
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index d23b580d97..b28f6c2297 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -1,7 +1,8 @@
require 'rack/mount'
require 'forwardable'
+require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/to_query'
-require 'action_dispatch/routing/deprecated_mapper'
+require 'active_support/core_ext/hash/slice'
module ActionDispatch
module Routing
@@ -50,12 +51,13 @@ module ActionDispatch
private
def controller_reference(controller_param)
+ controller_name = "#{controller_param.camelize}Controller"
+
unless controller = @controllers[controller_param]
- controller_name = "#{controller_param.camelize}Controller"
controller = @controllers[controller_param] =
- ActiveSupport::Dependencies.ref(controller_name)
+ ActiveSupport::Dependencies.reference(controller_name)
end
- controller.get
+ controller.get(controller_name)
end
def dispatch(controller, action, env)
@@ -67,7 +69,7 @@ module ActionDispatch
end
def split_glob_param!(params)
- params[@glob_param] = params[@glob_param].split('/').map { |v| URI.unescape(v) }
+ params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
end
end
@@ -158,10 +160,18 @@ module ActionDispatch
# We use module_eval to avoid leaks
@module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
- def #{selector}(options = nil) # def hash_for_users_url(options = nil)
- options ? #{options.inspect}.merge(options) : #{options.inspect} # options ? {:only_path=>false}.merge(options) : {:only_path=>false}
- end # end
- protected :#{selector} # protected :hash_for_users_url
+ remove_method :#{selector} if method_defined?(:#{selector})
+ def #{selector}(*args)
+ options = args.extract_options!
+
+ if args.any?
+ options[:_positional_args] = args
+ options[:_positional_keys] = #{route.segment_keys.inspect}
+ end
+
+ options ? #{options.inspect}.merge(options) : #{options.inspect}
+ end
+ protected :#{selector}
END_EVAL
helpers << selector
end
@@ -184,22 +194,16 @@ module ActionDispatch
hash_access_method = hash_access_name(name, kind)
@module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
+ remove_method :#{selector} if method_defined?(:#{selector})
def #{selector}(*args)
- options = #{hash_access_method}(args.extract_options!)
-
- if args.any?
- options[:_positional_args] = args
- options[:_positional_keys] = #{route.segment_keys.inspect}
- end
-
- url_for(options)
+ url_for(#{hash_access_method}(*args))
end
END_EVAL
helpers << selector
end
end
- attr_accessor :set, :routes, :named_routes
+ attr_accessor :set, :routes, :named_routes, :default_scope
attr_accessor :disable_clear_and_finalize, :resources_path_names
attr_accessor :default_url_options, :request_class, :valid_conditions
@@ -211,7 +215,6 @@ module ActionDispatch
self.routes = []
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
- self.controller_namespaces = Set.new
self.default_url_options = {}
self.request_class = request_class
@@ -219,27 +222,35 @@ module ActionDispatch
self.valid_conditions.delete(:id)
self.valid_conditions.push(:controller, :action)
+ @append = []
@disable_clear_and_finalize = false
clear!
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 eval_block(block)
mapper = Mapper.new(self)
- if block.arity == 1
- mapper.instance_exec(DeprecatedMapper.new(self), &block)
+ if default_scope
+ mapper.with_default_scope(default_scope, &block)
else
mapper.instance_exec(&block)
end
-
- finalize! unless @disable_clear_and_finalize
-
- nil
end
def finalize!
return if @finalized
+ @append.each { |blk| eval_block(blk) }
@finalized = true
@set.freeze
end
@@ -261,6 +272,31 @@ module ActionDispatch
named_routes.install(destinations, regenerate_code)
end
+ module MountedHelpers
+ end
+
+ def mounted_helpers(name = :main_app)
+ define_mounted_helper(name) if name
+ 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, self._routes_context)
+ end
+ end
+
+ MountedHelpers.class_eval <<-RUBY
+ def #{name}
+ @#{name} ||= _#{name}
+ end
+ RUBY
+ end
+
def url_helpers
@url_helpers ||= begin
routes = self
@@ -269,9 +305,9 @@ module ActionDispatch
extend ActiveSupport::Concern
include UrlFor
- @routes = routes
+ @_routes = routes
class << self
- delegate :url_for, :to => '@routes'
+ delegate :url_for, :to => '@_routes'
end
extend routes.named_routes.module
@@ -280,10 +316,10 @@ module ActionDispatch
# Yes plz - JP
included do
routes.install_helpers(self)
- singleton_class.send(:define_method, :_routes) { routes }
+ singleton_class.send(:redefine_method, :_routes) { routes }
end
- define_method(:_routes) { routes }
+ define_method(:_routes) { @_routes || routes }
end
helpers
@@ -295,18 +331,31 @@ module ActionDispatch
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)
route = Route.new(self, app, conditions, requirements, defaults, name, anchor)
- @set.add_route(*route)
+ @set.add_route(route.app, route.conditions, route.defaults, route.name)
named_routes[name] = route if name
routes << route
route
end
class Generator #:nodoc:
- attr_reader :options, :recall, :set, :script_name, :named_route
+ PARAMETERIZE = {
+ :parameterize => lambda do |name, value|
+ if name == :controller
+ value
+ elsif value.is_a?(Array)
+ value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/')
+ else
+ return nil unless param = value.to_param
+ param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/")
+ end
+ end
+ }
+
+ attr_reader :options, :recall, :set, :named_route
def initialize(options, recall, set, extras = false)
- @script_name = options.delete(:script_name)
@named_route = options.delete(:use_route)
@options = options.dup
@recall = recall.dup
@@ -392,36 +441,19 @@ module ActionDispatch
end
def generate
- path, params = @set.set.generate(:path_info, named_route, options, recall, opts)
+ path, params = @set.set.generate(:path_info, named_route, options, recall, PARAMETERIZE)
raise_routing_error unless path
- params.reject! {|k,v| !v }
-
return [path, params.keys] if @extras
- path << "?#{params.to_query}" if params.any?
- "#{script_name}#{path}"
+ [path, params]
rescue Rack::Mount::RoutingError
raise_routing_error
end
- def opts
- parameterize = lambda do |name, value|
- if name == :controller
- value
- elsif value.is_a?(Array)
- value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/')
- else
- return nil unless param = value.to_param
- param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/")
- end
- end
- {:parameterize => parameterize}
- end
-
def raise_routing_error
- raise ActionController::RoutingError.new("No route matches #{options.inspect}")
+ raise ActionController::RoutingError, "No route matches #{options.inspect}"
end
def different_controller?
@@ -453,7 +485,12 @@ module ActionDispatch
Generator.new(options, recall, self, extras).generate
end
- RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash]
+ RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
+ :trailing_slash, :anchor, :params, :only_path, :script_name]
+
+ def _generate_prefix(options = {})
+ nil
+ end
def url_for(options)
finalize!
@@ -461,30 +498,24 @@ module ActionDispatch
handle_positional_args(options)
- rewritten_url = ""
-
- path_segments = options.delete(:_path_segments)
-
- unless options[:only_path]
- rewritten_url << (options[:protocol] || "http")
- rewritten_url << "://" unless rewritten_url.match("://")
- rewritten_url << rewrite_authentication(options)
-
- raise "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" unless options[:host]
+ user, password = extract_authentication(options)
+ path_segments = options.delete(:_path_segments)
+ script_name = options.delete(:script_name)
- rewritten_url << options[:host]
- rewritten_url << ":#{options.delete(:port)}" if options.key?(:port)
- end
+ path = (script_name.blank? ? _generate_prefix(options) : script_name.chomp('/')).to_s
path_options = options.except(*RESERVED_OPTIONS)
path_options = yield(path_options) if block_given?
- path = generate(path_options, path_segments || {})
- # ROUTES TODO: This can be called directly, so script_name should probably be set in the routes
- rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path)
- rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor]
+ path_addition, params = generate(path_options, path_segments || {})
+ path << path_addition
- rewritten_url
+ ActionDispatch::Http::URL.url_for(options.merge({
+ :path => path,
+ :params => params,
+ :user => user,
+ :password => password
+ }))
end
def call(env)
@@ -494,7 +525,7 @@ module ActionDispatch
def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase
- path = Rack::Mount::Utils.normalize_path(path)
+ path = Rack::Mount::Utils.normalize_path(path) unless path =~ %r{://}
begin
env = Rack::MockRequest.env_for(path, {:method => method})
@@ -502,17 +533,19 @@ module ActionDispatch
raise ActionController::RoutingError, e.message
end
- req = Rack::Request.new(env)
+ req = @request_class.new(env)
@set.recognize(req) do |route, matches, params|
params.each do |key, value|
if value.is_a?(String)
value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware?
- params[key] = URI.unescape(value)
+ params[key] = URI.parser.unescape(value)
end
end
dispatcher = route.app
- dispatcher = dispatcher.app while dispatcher.is_a?(Mapper::Constraints)
+ while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
+ dispatcher = dispatcher.app
+ end
if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false)
dispatcher.prepare_params!(params)
@@ -524,28 +557,25 @@ module ActionDispatch
end
private
+
+ def extract_authentication(options)
+ if options[:user] && options[:password]
+ [options.delete(:user), options.delete(:password)]
+ else
+ nil
+ end
+ end
+
def handle_positional_args(options)
return unless args = options.delete(:_positional_args)
keys = options.delete(:_positional_keys)
keys -= options.keys if args.size < keys.size - 1 # take format into account
- args = args.zip(keys).inject({}) do |h, (v, k)|
- h[k] = v
- h
- end
-
# Tell url_for to skip default_url_options
- options.merge!(args)
+ options.merge!(Hash[args.zip(keys).map { |v, k| [k, v] }])
end
- def rewrite_authentication(options)
- if options[:user] && options[:password]
- "#{Rack::Utils.escape(options.delete(:user))}:#{Rack::Utils.escape(options.delete(:password))}@"
- else
- ""
- 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 0000000000..f7d5f6397d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/routes_proxy.rb
@@ -0,0 +1,35 @@
+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 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
index ba93ff8630..d4db78a25a 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -1,6 +1,6 @@
module ActionDispatch
module Routing
- # In <b>routes.rb</b> one defines URL-to-controller mappings, but the reverse
+ # 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.
#
@@ -12,15 +12,14 @@ module ActionDispatch
#
# == URL generation from parameters
#
- # As you may know, some functions - such as ActionController::Base#url_for
+ # 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!') %>
- #
- # # Generates a link to /users/new?message=Welcome%21
+ # # => "/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,
@@ -61,7 +60,7 @@ module ActionDispatch
#
# 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
- # <b>routes.rb</b>:
+ # <tt>config/routes.rb</tt>:
#
# resources :users
#
@@ -99,6 +98,11 @@ module ActionDispatch
end
end
+ def initialize(*)
+ @_routes = nil
+ super
+ end
+
def url_options
default_url_options
end
@@ -111,6 +115,13 @@ module ActionDispatch
# * <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 domain from the host.
+ # * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
+ # to split the subdomain 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/"
@@ -134,6 +145,18 @@ module ActionDispatch
polymorphic_url(options)
end
end
+
+ protected
+ 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/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
index 9c215de743..47c84742aa 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
@@ -3,7 +3,7 @@ require 'action_controller/vendor/html-scanner'
module ActionDispatch
module Assertions
module DomAssertions
- # Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
+ # \Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
#
# ==== Examples
#
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index ec5e9efe44..77a15f3e97 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -1,6 +1,6 @@
module ActionDispatch
module Assertions
- # A small suite of assertions that test responses from Rails applications.
+ # A small suite of assertions that test responses from \Rails applications.
module ResponseAssertions
extend ActiveSupport::Concern
@@ -18,9 +18,9 @@ module ActionDispatch
# * <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 assert_response(501)
- # or its symbolic equivalent assert_response(:not_implemented).
- # See ActionDispatch::StatusCodes for a full list.
+ # 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.
#
# ==== Examples
#
@@ -45,8 +45,8 @@ module ActionDispatch
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 assert_redirected_to(:controller => "weblog") will also
- # match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on.
+ # 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.
#
# ==== Examples
#
@@ -81,14 +81,10 @@ module ActionDispatch
def normalize_argument_to_redirection(fragment)
case fragment
- when %r{^\w[\w\d+.-]*:.*}
+ when %r{^\w[A-Za-z\d+.-]*:.*}
fragment
when String
- if fragment =~ %r{^\w[\w\d+.-]*:.*}
- fragment
- else
- @request.protocol + @request.host_with_port + fragment
- end
+ @request.protocol + @request.host_with_port + fragment
when :back
raise RedirectBackError unless refer = @request.headers["Referer"]
refer
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index 9338fa9e70..11e8c63fa0 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -1,12 +1,13 @@
+require 'uri'
require 'active_support/core_ext/hash/diff'
require 'active_support/core_ext/hash/indifferent_access'
module ActionDispatch
module Assertions
- # Suite of assertions to test routes generated by Rails and the handling of requests made to them.
+ # 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+.
+ # 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
@@ -36,18 +37,8 @@ module ActionDispatch
#
# # Test a custom route
# assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1')
- #
- # # Check a Simply RESTful generated route
- # assert_recognizes list_items_url, 'items/list'
def assert_recognizes(expected_options, path, extras={}, message=nil)
- if path.is_a? Hash
- request_method = path[:method]
- path = path[:path]
- else
- request_method = nil
- end
-
- request = recognized_request_for(path, request_method)
+ request = recognized_request_for(path)
expected_options = expected_options.clone
extras.each_key { |key| expected_options.delete key } unless extras.nil?
@@ -77,7 +68,16 @@ module ActionDispatch
# # 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)
- expected_path = "/#{expected_path}" unless expected_path[0] == ?/
+ if expected_path =~ %r{://}
+ begin
+ uri = URI.parse(expected_path)
+ expected_path = uri.path.to_s.empty? ? "/" : uri.path
+ rescue URI::InvalidURIError => e
+ raise ActionController::RoutingError, e.message
+ 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)
@@ -121,7 +121,8 @@ module ActionDispatch
options[:controller] = "/#{controller}"
end
- assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message)
+ generate_options = options.dup.delete_if{ |k,v| defaults.key?(k) }
+ assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
end
# A helper to make it easier to test different route configurations.
@@ -143,16 +144,16 @@ module ActionDispatch
#
def with_routing
old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
- old_controller, @controller = @controller, @controller.clone if @controller
- _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
- if @controller
+ 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
@@ -161,14 +162,14 @@ module ActionDispatch
yield @routes
ensure
@routes = old_routes
- if @controller
+ 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 @controller && @routes && @routes.named_routes.helpers.include?(selector)
+ if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(selector)
@controller.send(selector, *args, &block)
else
super
@@ -177,15 +178,35 @@ module ActionDispatch
private
# Recognizes the route for a given path.
- def recognized_request_for(path, request_method = nil)
- path = "/#{path}" unless path.first == '/'
+ def recognized_request_for(path)
+ if path.is_a?(Hash)
+ method = path[:method]
+ path = path[:path]
+ else
+ method = :get
+ end
# Assume given controller
request = ActionController::TestRequest.new
- request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method
- request.path = path
- params = @routes.recognize_path(path, { :method => request.method })
+ if path =~ %r{://}
+ begin
+ 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
+ rescue URI::InvalidURIError => e
+ raise ActionController::RoutingError, e.message
+ end
+ else
+ path = "/#{path}" unless path.first == "/"
+ request.path = path
+ end
+
+ request.request_method = method if method
+
+ params = @routes.recognize_path(path, { :method => method })
request.path_parameters = params.with_indifferent_access
request
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
index 2fc9e2b7d6..2b862fb7d6 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -24,10 +24,6 @@ module ActionDispatch
#
# Also see HTML::Selector to learn how to use selectors.
module SelectorAssertions
- # :call-seq:
- # css_select(selector) => array
- # css_select(element, selector) => array
- #
# Select and return all matching elements.
#
# If called with a single argument, uses that argument as a selector
@@ -71,7 +67,7 @@ module ActionDispatch
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 @selected
+ elsif defined?(@selected) && @selected
matches = []
@selected.each do |selected|
@@ -99,10 +95,6 @@ module ActionDispatch
selector.select(root)
end
- # :call-seq:
- # assert_select(selector, equality?, message?)
- # assert_select(element, selector, equality?, message?)
- #
# An assertion that selects elements and makes one or more equality tests.
#
# If the first argument is an element, selects all matching elements
@@ -195,6 +187,7 @@ module ActionDispatch
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),
@@ -332,11 +325,6 @@ module ActionDispatch
end
end
- # :call-seq:
- # assert_select_rjs(id?) { |elements| ... }
- # assert_select_rjs(statement, id?) { |elements| ... }
- # assert_select_rjs(:insert, position, id?) { |elements| ... }
- #
# Selects content from the RJS response.
#
# === Narrowing down
@@ -455,6 +443,7 @@ module ActionDispatch
assert_block("") { true } # to count the assertion
if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
begin
+ @selected ||= nil
in_scope, @selected = @selected, matches
yield matches
ensure
@@ -474,9 +463,6 @@ module ActionDispatch
end
end
- # :call-seq:
- # assert_select_encoded(element?) { |elements| ... }
- #
# Extracts the content of an element, treats it as encoded HTML and runs
# nested assertion on it.
#
@@ -529,8 +515,8 @@ module ActionDispatch
node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { Rack::Utils.escapeHTML($1) }
end
- selected = elements.map do |element|
- text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
+ selected = elements.map do |_element|
+ text = _element.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
@@ -543,9 +529,6 @@ module ActionDispatch
end
end
- # :call-seq:
- # assert_select_email { }
- #
# Extracts the body of an email and runs nested assertions on it.
#
# You must enable deliveries for this assertion to work, use:
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index b52795c575..5c6416a19e 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -115,8 +115,8 @@ module ActionDispatch
end
end
- # An integration Session instance represents a set of requests and responses
- # performed sequentially by some virtual user. Because you can instantiate
+ # 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.
#
@@ -171,6 +171,7 @@ module ActionDispatch
# 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
@@ -182,6 +183,7 @@ module ActionDispatch
reset!
end
+ remove_method :default_url_options
def default_url_options
{ :host => host, :protocol => https? ? "https" : "http" }
end
@@ -233,9 +235,7 @@ module ActionDispatch
# Set the host name to use in the next request.
#
# session.host! "www.example.com"
- def host!(name)
- @host = name
- end
+ alias :host! :host=
private
def _mock_session
@@ -257,12 +257,14 @@ module ActionDispatch
end
end
+ hostname, port = host.split(':')
+
env = {
:method => method,
:params => parameters,
- "SERVER_NAME" => host.split(':')[0],
- "SERVER_PORT" => (https? ? "443" : "80"),
+ "SERVER_NAME" => hostname,
+ "SERVER_PORT" => port || (https? ? "443" : "80"),
"HTTPS" => https? ? "on" : "off",
"rack.url_scheme" => https? ? "https" : "http",
@@ -305,7 +307,7 @@ module ActionDispatch
include ActionDispatch::Assertions
def app
- @app
+ @app ||= nil
end
# Reset the current session. This is useful for testing multiple sessions
@@ -317,10 +319,10 @@ module ActionDispatch
%w(get post put head delete 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! unless integration_session
# reset the html_document variable, but only for new get/post calls
@html_document = nil unless %w(cookies assigns).include?(method)
- @integration_session.__send__(method, *args).tap do
+ integration_session.__send__(method, *args).tap do
copy_session_variables!
end
end
@@ -345,7 +347,7 @@ module ActionDispatch
# Copy the instance variables from the current session instance into the
# test instance.
def copy_session_variables! #:nodoc:
- return unless @integration_session
+ return unless integration_session
%w(controller response request).each do |var|
instance_variable_set("@#{var}", @integration_session.__send__(var))
end
@@ -355,35 +357,44 @@ module ActionDispatch
include ActionDispatch::Routing::UrlFor
def url_options
- reset! unless @integration_session
- @integration_session.url_options
+ reset! unless integration_session
+ integration_session.url_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
+ 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 IntegrationTest is one that spans multiple controllers and actions,
+ # An test that 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 IntegrationTest and write your tests
+ # At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
# using the get/post methods:
#
# require "test_helper"
#
- # class ExampleTest < ActionController::IntegrationTest
+ # class ExampleTest < ActionDispatch::IntegrationTest
# fixtures :people
#
# def test_login
@@ -403,11 +414,11 @@ module ActionDispatch
# 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!
+ # reference any named routes you happen to have defined.
#
# require "test_helper"
#
- # class AdvancedTest < ActionController::IntegrationTest
+ # class AdvancedTest < ActionDispatch::IntegrationTest
# fixtures :people, :rooms
#
# def test_login_and_speak
diff --git a/actionpack/lib/action_dispatch/testing/performance_test.rb b/actionpack/lib/action_dispatch/testing/performance_test.rb
index 33a5c68b9d..e7aeb45fb3 100644
--- a/actionpack/lib/action_dispatch/testing/performance_test.rb
+++ b/actionpack/lib/action_dispatch/testing/performance_test.rb
@@ -1,5 +1,4 @@
require 'active_support/testing/performance'
-require 'active_support/testing/default'
begin
module ActionDispatch
@@ -11,9 +10,8 @@ begin
# formats are written, so you'll have two output files per test method.
class PerformanceTest < ActionDispatch::IntegrationTest
include ActiveSupport::Testing::Performance
- include ActiveSupport::Testing::Default
end
end
rescue NameError
$stderr.puts "Specify ruby-prof as application's dependency in Gemfile to run benchmarks."
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
index c56ebc6438..d430691429 100644
--- a/actionpack/lib/action_dispatch/testing/test_process.rb
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -22,7 +22,7 @@ module ActionDispatch
end
def cookies
- @request.cookies.merge(@response.cookies)
+ @request.cookies.merge(@response.cookies).with_indifferent_access
end
def redirect_to_url
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index b3e67f6e36..822adb6a47 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/reverse_merge'
+require 'rack/utils'
module ActionDispatch
class TestRequest < Request
@@ -10,9 +11,10 @@ module ActionDispatch
end
def initialize(env = {})
- env = Rails.application.env_defaults.merge(env) if defined?(Rails.application)
+ env = Rails.application.env_config.merge(env) if defined?(Rails.application)
super(DEFAULT_ENV.merge(env))
+ @cookies = nil
self.host = 'test.host'
self.remote_addr = '0.0.0.0'
self.user_agent = 'Rails Testing'
@@ -66,7 +68,7 @@ module ActionDispatch
def accept=(mime_types)
@env.delete('action_dispatch.request.accepts')
- @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",")
+ @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
end
def cookies
@@ -76,10 +78,14 @@ module ActionDispatch
private
def write_cookies!
unless @cookies.blank?
- @env['HTTP_COOKIE'] = @cookies.map { |name, value| "#{name}=#{value};" }.join(' ')
+ @env['HTTP_COOKIE'] = @cookies.map { |name, value| escape_cookie(name, value) }.join('; ')
end
end
+ def escape_cookie(name, value)
+ "#{Rack::Utils.escape(name)}=#{Rack::Utils.escape(value)}"
+ end
+
def delete_nil_values!
@env.delete_if { |k, v| v.nil? }
end
diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb
index 44fb1bde99..82039e72e7 100644
--- a/actionpack/lib/action_dispatch/testing/test_response.rb
+++ b/actionpack/lib/action_dispatch/testing/test_response.rb
@@ -14,123 +14,16 @@ module ActionDispatch
end
end
- module DeprecatedHelpers
- def template
- ActiveSupport::Deprecation.warn("response.template has been deprecated. Use controller.template instead", caller)
- @template
- end
- attr_writer :template
-
- def session
- ActiveSupport::Deprecation.warn("response.session has been deprecated. Use request.session instead", caller)
- @request.session
- end
-
- def assigns
- ActiveSupport::Deprecation.warn("response.assigns has been deprecated. Use controller.assigns instead", caller)
- @template.controller.assigns
- end
-
- def layout
- ActiveSupport::Deprecation.warn("response.layout has been deprecated. Use template.layout instead", caller)
- @template.layout
- end
-
- def redirected_to
- ::ActiveSupport::Deprecation.warn("response.redirected_to is deprecated. Use response.redirect_url instead", caller)
- redirect_url
- end
-
- def redirect_url_match?(pattern)
- ::ActiveSupport::Deprecation.warn("response.redirect_url_match? is deprecated. Use assert_match(/foo/, response.redirect_url) instead", caller)
- return false if redirect_url.nil?
- p = Regexp.new(pattern) if pattern.class == String
- p = pattern if pattern.class == Regexp
- return false if p.nil?
- p.match(redirect_url) != nil
- end
-
- # Returns the template of the file which was used to
- # render this response (or nil)
- def rendered
- ActiveSupport::Deprecation.warn("response.rendered has been deprecated. Use template.rendered instead", caller)
- @template.instance_variable_get(:@_rendered)
- end
-
- # A shortcut to the flash. Returns an empty hash if no session flash exists.
- def flash
- ActiveSupport::Deprecation.warn("response.flash has been deprecated. Use request.flash instead", caller)
- request.session['flash'] || {}
- end
-
- # Do we have a flash?
- def has_flash?
- ActiveSupport::Deprecation.warn("response.has_flash? has been deprecated. Use flash.any? instead", caller)
- !flash.empty?
- end
-
- # Do we have a flash that has contents?
- def has_flash_with_contents?
- ActiveSupport::Deprecation.warn("response.has_flash_with_contents? has been deprecated. Use flash.any? instead", caller)
- !flash.empty?
- end
-
- # Does the specified flash object exist?
- def has_flash_object?(name=nil)
- ActiveSupport::Deprecation.warn("response.has_flash_object? has been deprecated. Use flash[name] instead", caller)
- !flash[name].nil?
- end
-
- # Does the specified object exist in the session?
- def has_session_object?(name=nil)
- ActiveSupport::Deprecation.warn("response.has_session_object? has been deprecated. Use session[name] instead", caller)
- !session[name].nil?
- end
-
- # A shortcut to the template.assigns
- def template_objects
- ActiveSupport::Deprecation.warn("response.template_objects has been deprecated. Use template.assigns instead", caller)
- @template.assigns || {}
- end
-
- # Does the specified template object exist?
- def has_template_object?(name=nil)
- ActiveSupport::Deprecation.warn("response.has_template_object? has been deprecated. Use tempate.assigns[name].nil? instead", caller)
- !template_objects[name].nil?
- end
-
- # Returns binary content (downloadable file), converted to a String
- def binary_content
- ActiveSupport::Deprecation.warn("response.binary_content has been deprecated. Use response.body instead", caller)
- body
- end
- end
- include DeprecatedHelpers
-
# Was the response successful?
- def success?
- (200..299).include?(response_code)
- end
+ alias_method :success?, :successful?
# Was the URL not found?
- def missing?
- response_code == 404
- end
+ alias_method :missing?, :not_found?
# Were we redirected?
- def redirect?
- (300..399).include?(response_code)
- end
+ alias_method :redirect?, :redirection?
# Was there a server-side error?
- def error?
- (500..599).include?(response_code)
- end
- alias_method :server_error?, :error?
-
- # Was there a client client?
- def client_error?
- (400..499).include?(response_code)
- end
+ alias_method :error?, :server_error?
end
end
diff --git a/actionpack/lib/action_pack.rb b/actionpack/lib/action_pack.rb
index 1a1497385a..914b13dbfb 100644
--- a/actionpack/lib/action_pack.rb
+++ b/actionpack/lib/action_pack.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb
index 7eaf7d0534..170ceb299a 100644
--- a/actionpack/lib/action_pack/version.rb
+++ b/actionpack/lib/action_pack/version.rb
@@ -1,10 +1,10 @@
module ActionPack
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index c0d7423682..60665387b6 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -21,9 +21,6 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
-$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
require 'active_support/ruby/shim'
require 'active_support/core_ext/class/attribute_accessors'
@@ -33,35 +30,43 @@ module ActionView
extend ActiveSupport::Autoload
eager_autoload do
+ autoload :Base
autoload :Context
- autoload :Template
autoload :Helpers
+ autoload :LookupContext
+ autoload :Partials
+ autoload :PathSet
+ autoload :Rendering
+ autoload :Template
+ autoload :TestCase
- autoload_under "render" do
- autoload :Layouts
- autoload :Partials
- autoload :Rendering
+ autoload_under "renderer" do
+ autoload :AbstractRenderer
+ autoload :PartialRenderer
+ autoload :TemplateRenderer
end
- autoload :Base
- autoload :LookupContext
- autoload :Resolver, 'action_view/template/resolver'
- autoload :PathResolver, 'action_view/template/resolver'
- autoload :FileSystemResolver, 'action_view/template/resolver'
- autoload :PathSet, 'action_view/paths'
+ autoload_at "action_view/template/resolver" do
+ autoload :Resolver
+ autoload :PathResolver
+ autoload :FileSystemResolver
+ autoload :FallbackFileSystemResolver
+ end
- autoload :MissingTemplate, 'action_view/template/error'
- autoload :ActionViewError, 'action_view/template/error'
- autoload :EncodingError, 'action_view/template/error'
- autoload :TemplateError, 'action_view/template/error'
- autoload :WrongEncodingError, 'action_view/template/error'
+ autoload_at "action_view/template/error" do
+ autoload :MissingTemplate
+ autoload :ActionViewError
+ autoload :EncodingError
+ autoload :TemplateError
+ autoload :WrongEncodingError
+ end
- autoload :TemplateHandler, 'action_view/template'
- autoload :TemplateHandlers, 'action_view/template'
+ autoload_at "action_view/template" do
+ autoload :TemplateHandler
+ autoload :TemplateHandlers
+ end
end
- autoload :TestCase, 'action_view/test_case'
-
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
end
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 20a2e7c1f0..ab8c6259c5 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -6,9 +6,6 @@ require 'active_support/ordered_options'
require 'action_view/log_subscriber'
module ActionView #:nodoc:
- class NonConcattingString < ActiveSupport::SafeBuffer
- end
-
# = Action View Base
#
# Action View templates can be written in three ways. If the template file has a <tt>.erb</tt> (or <tt>.rhtml</tt>) extension then it uses a mixture of ERb
@@ -21,7 +18,7 @@ module ActionView #:nodoc:
# following loop for names:
#
# <b>Names of all the people</b>
- # <% for person in @people %>
+ # <% @people.each do |person| %>
# Name: <%= person.name %><br/>
# <% end %>
#
@@ -79,8 +76,8 @@ module ActionView #:nodoc:
#
# === 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.
+ # 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
#
@@ -156,12 +153,9 @@ module ActionView #:nodoc:
#
# This refreshes the sidebar, removes a person element and highlights the user list.
#
- # See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.
+ # See the ActionView::Helpers::PrototypeHelper::JavaScriptGenerator::GeneratorMethods documentation for more details.
class Base
- module Subclasses
- end
-
- include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context
+ include Helpers, Rendering, Partials, ::ERB::Util, Context
# Specify whether RJS responses should be wrapped in a try/catch block
# that alert()s the caught exception (and then re-raises it).
@@ -178,24 +172,26 @@ module ActionView #:nodoc:
class << self
delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
delegate :logger, :to => 'ActionController::Base', :allow_nil => true
+
+ def cache_template_loading
+ ActionView::Resolver.caching?
+ end
+
+ def cache_template_loading=(value)
+ ActionView::Resolver.caching = value
+ end
end
- attr_accessor :base_path, :assigns, :template_extension, :lookup_context
- attr_internal :captures, :request, :controller, :template, :config
+ attr_accessor :_template
+ attr_internal :request, :controller, :config, :assigns, :lookup_context
- delegate :find_template, :template_exists?, :formats, :formats=, :locale, :locale=,
- :view_paths, :view_paths=, :with_fallbacks, :update_details, :with_layout_format, :to => :lookup_context
+ delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, :to => :lookup_context
- delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
+ delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
:flash, :action_name, :controller_name, :to => :controller
delegate :logger, :to => :controller, :allow_nil => true
- # TODO: HACK FOR RJS
- def view_context
- self
- end
-
def self.xss_safe? #:nodoc:
true
end
@@ -206,33 +202,40 @@ module ActionView #:nodoc:
end
def assign(new_assigns) # :nodoc:
- self.assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
+ @_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
end
def initialize(lookup_context = nil, assigns_for_first_render = {}, controller = nil, formats = nil) #:nodoc:
assign(assigns_for_first_render)
- self.helpers = self.class.helpers || Module.new
-
- if @_controller = controller
- @_request = controller.request if controller.respond_to?(:request)
- end
-
- config = controller && controller.respond_to?(:config) ? controller.config : {}
- @_config = ActiveSupport::InheritableOptions.new(config)
+ self.helpers = Module.new unless self.class.helpers
+ @_config = {}
@_content_for = Hash.new { |h,k| h[k] = ActiveSupport::SafeBuffer.new }
@_virtual_path = nil
@output_buffer = nil
- @lookup_context = lookup_context.is_a?(ActionView::LookupContext) ?
+ if @_controller = controller
+ @_request = controller.request if controller.respond_to?(:request)
+ @_config = controller.config.inheritable_copy if controller.respond_to?(:config)
+ end
+
+ @_lookup_context = lookup_context.is_a?(ActionView::LookupContext) ?
lookup_context : ActionView::LookupContext.new(lookup_context)
- @lookup_context.formats = formats if formats
+ @_lookup_context.formats = formats if formats
+ end
+
+ def store_content_for(key, value)
+ @_content_for[key] = value
end
def controller_path
@controller_path ||= controller && controller.controller_path
end
+ def controller_prefixes
+ @controller_prefixes ||= controller && controller._prefixes
+ end
+
ActiveSupport.run_load_hooks(:action_view, self)
end
end
diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb
index b7ffa345cc..d338ce616a 100644
--- a/actionpack/lib/action_view/helpers.rb
+++ b/actionpack/lib/action_view/helpers.rb
@@ -12,14 +12,13 @@ module ActionView #:nodoc:
autoload :CsrfHelper
autoload :DateHelper
autoload :DebugHelper
- autoload :DeprecatedBlockHelpers
autoload :FormHelper
autoload :FormOptionsHelper
autoload :FormTagHelper
autoload :JavaScriptHelper, "action_view/helpers/javascript_helper"
autoload :NumberHelper
autoload :PrototypeHelper
- autoload :RawOutputHelper
+ autoload :OutputSafetyHelper
autoload :RecordTagHelper
autoload :SanitizeHelper
autoload :ScriptaculousHelper
@@ -49,7 +48,7 @@ module ActionView #:nodoc:
include JavaScriptHelper
include NumberHelper
include PrototypeHelper
- include RawOutputHelper
+ include OutputSafetyHelper
include RecordTagHelper
include SanitizeHelper
include ScriptaculousHelper
diff --git a/actionpack/lib/action_view/helpers/active_model_helper.rb b/actionpack/lib/action_view/helpers/active_model_helper.rb
index 6bb0875bc3..96c3eec337 100644
--- a/actionpack/lib/action_view/helpers/active_model_helper.rb
+++ b/actionpack/lib/action_view/helpers/active_model_helper.rb
@@ -7,25 +7,6 @@ module ActionView
# = Active Model Helpers
module Helpers
module ActiveModelHelper
- %w(input form error_messages_for error_message_on).each do |method|
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{method}(*args)
- ActiveSupport::Deprecation.warn "#{method} was removed from Rails and is now available as a plugin. " <<
- "Please install it with `rails plugin install git://github.com/rails/dynamic_form.git`.", caller
- end
- RUBY
- end
- end
-
- module ActiveModelFormBuilder
- %w(error_messages error_message_on).each do |method|
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{method}(*args)
- ActiveSupport::Deprecation.warn "f.#{method} was removed from Rails and is now available as a plugin. " <<
- "Please install it with `rails plugin install git://github.com/rails/dynamic_form.git`.", caller
- end
- RUBY
- end
end
module ActiveModelInstanceTag
@@ -67,10 +48,6 @@ module ActionView
end
end
- class FormBuilder
- include ActiveModelFormBuilder
- end
-
class InstanceTag
include ActiveModelInstanceTag
end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index a3c43d3e93..f6b2d4f3f4 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -1,9 +1,6 @@
-require 'thread'
-require 'cgi'
-require 'action_view/helpers/url_helper'
-require 'action_view/helpers/tag_helper'
-require 'active_support/core_ext/file'
-require 'active_support/core_ext/object/blank'
+require 'action_view/helpers/asset_tag_helpers/javascript_tag_helpers'
+require 'action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers'
+require 'action_view/helpers/asset_tag_helpers/asset_paths'
module ActionView
# = Action View Asset Tag Helpers
@@ -152,7 +149,7 @@ module ActionView
#
# # Normally you'd calculate RELEASE_NUMBER at startup.
# RELEASE_NUMBER = 12345
- # config.action_controller.asset_path_template = proc { |asset_path|
+ # config.action_controller.asset_path = proc { |asset_path|
# "/release-#{RELEASE_NUMBER}#{asset_path}"
# }
#
@@ -194,20 +191,8 @@ module ActionView
# RewriteEngine On
# RewriteRule ^/release-\d+/(images|javascripts|stylesheets)/(.*)$ /$1/$2 [L]
module AssetTagHelper
- mattr_reader :javascript_expansions
- @@javascript_expansions = { }
-
- mattr_reader :stylesheet_expansions
- @@stylesheet_expansions = {}
-
- # You can enable or disable the asset tag timestamps cache.
- # With the cache enabled, the asset tag helper methods will make fewer
- # expensive file system calls. However this prevents you from modifying
- # any asset files while the server is running.
- #
- # ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
- mattr_accessor :cache_asset_timestamps
-
+ include JavascriptTagHelpers
+ include StylesheetTagHelpers
# 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
@@ -241,263 +226,6 @@ module ActionView
)
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.
- #
- # ==== Examples
- # 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.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr
- # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
- def javascript_path(source)
- compute_public_path(source, 'javascripts', 'js')
- end
- alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
-
- # Returns an html script tag for each of the +sources+ provided. You
- # can pass in the filename (.js extension is optional) of javascript files
- # that exist in your public/javascripts directory for inclusion into the
- # current page or you can pass the full path relative to your document
- # root. To include the Prototype and Scriptaculous javascript libraries in
- # your application, pass <tt>:defaults</tt> as the source. When using
- # <tt>:defaults</tt>, if an application.js file exists in your public
- # javascripts directory, it will be included as well. You can modify the
- # html attributes of the script tag by passing a hash as the last argument.
- #
- # ==== Examples
- # javascript_include_tag "xmlhr" # =>
- # <script type="text/javascript" src="/javascripts/xmlhr.js"></script>
- #
- # javascript_include_tag "xmlhr.js" # =>
- # <script type="text/javascript" src="/javascripts/xmlhr.js"></script>
- #
- # javascript_include_tag "common.javascript", "/elsewhere/cools" # =>
- # <script type="text/javascript" src="/javascripts/common.javascript"></script>
- # <script type="text/javascript" src="/elsewhere/cools.js"></script>
- #
- # javascript_include_tag "http://www.railsapplication.com/xmlhr" # =>
- # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script>
- #
- # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # =>
- # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script>
- #
- # javascript_include_tag :defaults # =>
- # <script type="text/javascript" src="/javascripts/prototype.js"></script>
- # <script type="text/javascript" src="/javascripts/effects.js"></script>
- # ...
- # <script type="text/javascript" src="/javascripts/application.js"></script>
- #
- # * = The application.js file is only referenced if it exists
- #
- # Though it's not really recommended practice, if you need to extend the default JavaScript set for any reason
- # (e.g., you're going to be using a certain .js file in every action), then take a look at the register_javascript_include_default method.
- #
- # You can also include all javascripts in the javascripts directory using <tt>:all</tt> as the source:
- #
- # javascript_include_tag :all # =>
- # <script type="text/javascript" src="/javascripts/prototype.js"></script>
- # <script type="text/javascript" src="/javascripts/effects.js"></script>
- # ...
- # <script type="text/javascript" src="/javascripts/application.js"></script>
- # <script type="text/javascript" src="/javascripts/shop.js"></script>
- # <script type="text/javascript" src="/javascripts/checkout.js"></script>
- #
- # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to
- # all subsequently included files.
- #
- # If you want Rails to search in all the subdirectories under javascripts, you should explicitly set <tt>:recursive</tt>:
- #
- # javascript_include_tag :all, :recursive => true
- #
- # == Caching multiple javascripts into one
- #
- # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be
- # compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching
- # is set to <tt>true</tt> (which is the case by default for the Rails production environment, but not for the development
- # environment).
- #
- # ==== Examples
- # javascript_include_tag :all, :cache => true # when config.perform_caching is false =>
- # <script type="text/javascript" src="/javascripts/prototype.js"></script>
- # <script type="text/javascript" src="/javascripts/effects.js"></script>
- # ...
- # <script type="text/javascript" src="/javascripts/application.js"></script>
- # <script type="text/javascript" src="/javascripts/shop.js"></script>
- # <script type="text/javascript" src="/javascripts/checkout.js"></script>
- #
- # javascript_include_tag :all, :cache => true # when config.perform_caching is true =>
- # <script type="text/javascript" src="/javascripts/all.js"></script>
- #
- # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is false =>
- # <script type="text/javascript" src="/javascripts/prototype.js"></script>
- # <script type="text/javascript" src="/javascripts/cart.js"></script>
- # <script type="text/javascript" src="/javascripts/checkout.js"></script>
- #
- # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is true =>
- # <script type="text/javascript" src="/javascripts/shop.js"></script>
- #
- # The <tt>:recursive</tt> option is also available for caching:
- #
- # javascript_include_tag :all, :cache => true, :recursive => true
- def javascript_include_tag(*sources)
- options = sources.extract_options!.stringify_keys
- concat = options.delete("concat")
- cache = concat || options.delete("cache")
- recursive = options.delete("recursive")
-
- if concat || (config.perform_caching && cache)
- joined_javascript_name = (cache == true ? "all" : cache) + ".js"
- joined_javascript_path = File.join(joined_javascript_name[/^#{File::SEPARATOR}/] ? config.assets_dir : config.javascripts_dir, joined_javascript_name)
-
- unless config.perform_caching && File.exists?(joined_javascript_path)
- write_asset_file_contents(joined_javascript_path, compute_javascript_paths(sources, recursive))
- end
- javascript_src_tag(joined_javascript_name, options)
- else
- sources = expand_javascript_sources(sources, recursive)
- ensure_javascript_sources!(sources) if cache
- sources.collect { |source| javascript_src_tag(source, options) }.join("\n").html_safe
- end
- end
-
- # Register one or more javascript files to be included when <tt>symbol</tt>
- # is passed to <tt>javascript_include_tag</tt>. This method is typically intended
- # to be called from plugin initialization to register javascript files
- # that the plugin installed in <tt>public/javascripts</tt>.
- #
- # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
- #
- # javascript_include_tag :monkey # =>
- # <script type="text/javascript" src="/javascripts/head.js"></script>
- # <script type="text/javascript" src="/javascripts/body.js"></script>
- # <script type="text/javascript" src="/javascripts/tail.js"></script>
- def self.register_javascript_expansion(expansions)
- @@javascript_expansions.merge!(expansions)
- end
-
- # Register one or more stylesheet files to be included when <tt>symbol</tt>
- # is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended
- # to be called from plugin initialization to register stylesheet files
- # that the plugin installed in <tt>public/stylesheets</tt>.
- #
- # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
- #
- # stylesheet_link_tag :monkey # =>
- # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
- def self.register_stylesheet_expansion(expansions)
- @@stylesheet_expansions.merge!(expansions)
- end
-
- # 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.
- #
- # ==== Examples
- # 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.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style
- # stylesheet_path "http://www.railsapplication.com/css/style.css" # => http://www.railsapplication.com/css/style.css
- def stylesheet_path(source)
- compute_public_path(source, 'stylesheets', 'css')
- end
- alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
-
- # Returns a stylesheet link tag for the sources specified as arguments. If
- # you don't specify an extension, <tt>.css</tt> will be appended automatically.
- # You can modify the link attributes by passing a hash as the last argument.
- #
- # ==== Examples
- # stylesheet_link_tag "style" # =>
- # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "style.css" # =>
- # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "http://www.railsapplication.com/style.css" # =>
- # <link href="http://www.railsapplication.com/style.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "style", :media => "all" # =>
- # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "style", :media => "print" # =>
- # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "random.styles", "/css/stylish" # =>
- # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source:
- #
- # stylesheet_link_tag :all # =>
- # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>:
- #
- # stylesheet_link_tag :all, :recursive => true
- #
- # == Caching multiple stylesheets into one
- #
- # 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 config.perform_caching
- # is set to true (which is the case by default for the Rails production environment, but not for the development
- # environment). Examples:
- #
- # ==== Examples
- # stylesheet_link_tag :all, :cache => true # when config.perform_caching is false =>
- # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag :all, :cache => true # when config.perform_caching is true =>
- # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is false =>
- # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is true =>
- # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # The <tt>:recursive</tt> option is also available for caching:
- #
- # stylesheet_link_tag :all, :cache => true, :recursive => true
- #
- # To force concatenation (even in development mode) set <tt>:concat</tt> to true. This is useful if
- # you have too many stylesheets for IE to load.
- #
- # stylesheet_link_tag :all, :concat => true
- #
- def stylesheet_link_tag(*sources)
- options = sources.extract_options!.stringify_keys
- concat = options.delete("concat")
- cache = concat || options.delete("cache")
- recursive = options.delete("recursive")
-
- if concat || (config.perform_caching && cache)
- joined_stylesheet_name = (cache == true ? "all" : cache) + ".css"
- joined_stylesheet_path = File.join(joined_stylesheet_name[/^#{File::SEPARATOR}/] ? config.assets_dir : config.stylesheets_dir, joined_stylesheet_name)
-
- unless config.perform_caching && File.exists?(joined_stylesheet_path)
- write_asset_file_contents(joined_stylesheet_path, compute_stylesheet_paths(sources, recursive))
- end
- stylesheet_tag(joined_stylesheet_name, options)
- else
- sources = expand_stylesheet_sources(sources, recursive)
- ensure_stylesheet_sources!(sources) if cache
- sources.collect { |source| stylesheet_tag(source, options) }.join("\n").html_safe
- end
- end
-
# Web browsers cache favicons. If you just throw a <tt>favicon.ico</tt> into the document
# root of your application and it changes later, clients that have it in their cache
# won't see the update. Using this helper prevents that because it appends an asset ID:
@@ -546,7 +274,7 @@ module ActionView
# 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)
- compute_public_path(source, 'images')
+ asset_paths.compute_public_path(source, 'images')
end
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
@@ -561,7 +289,7 @@ module ActionView
# video_path("/trailers/hd.avi") # => /trailers/hd.avi
# video_path("http://www.railsapplication.com/vid/hd.avi") # => http://www.railsapplication.com/vid/hd.avi
def video_path(source)
- compute_public_path(source, 'videos')
+ asset_paths.compute_public_path(source, 'videos')
end
alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
@@ -571,12 +299,12 @@ module ActionView
#
# ==== Examples
# audio_path("horse") # => /audios/horse
- # audio_path("horse.wav") # => /audios/horse.avi
- # audio_path("sounds/horse.wav") # => /audios/sounds/horse.avi
- # audio_path("/sounds/horse.wav") # => /sounds/horse.avi
+ # 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.railsapplication.com/sounds/horse.wav") # => http://www.railsapplication.com/sounds/horse.wav
def audio_path(source)
- compute_public_path(source, 'audios')
+ asset_paths.compute_public_path(source, 'audios')
end
alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
@@ -705,202 +433,8 @@ module ActionView
private
- def rewrite_extension?(source, dir, ext)
- source_ext = File.extname(source)[1..-1]
- ext && (source_ext.blank? || (ext != source_ext && File.exist?(File.join(config.assets_dir, dir, "#{source}.#{ext}"))))
- end
-
- def rewrite_host_and_protocol(source, has_request)
- host = compute_asset_host(source)
- if has_request && host.present? && !is_uri?(host)
- host = "#{controller.request.protocol}#{host}"
- end
- "#{host}#{source}"
- end
-
- # Add the the extension +ext+ if not present. Return full URLs otherwise untouched.
- # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
- # roots. Rewrite the asset path for cache-busting asset ids. Include
- # asset host, if configured, with the correct request protocol.
- def compute_public_path(source, dir, ext = nil, include_host = true)
- return source if is_uri?(source)
-
- source += ".#{ext}" if rewrite_extension?(source, dir, ext)
- source = "/#{dir}/#{source}" unless source[0] == ?/
- source = rewrite_asset_path(source, config.asset_path)
-
- has_request = controller.respond_to?(:request)
- if has_request && include_host && source !~ %r{^#{controller.config.relative_url_root}/}
- source = "#{controller.config.relative_url_root}#{source}"
- end
- source = rewrite_host_and_protocol(source, has_request) if include_host
-
- source
- end
-
- def is_uri?(path)
- path =~ %r{^[-a-z]+://|^cid:}
- 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 the proc if it's a proc or the value from
- # invoking call if it's an object responding to call.
- def compute_asset_host(source)
- if host = config.asset_host
- if host.is_a?(Proc) || host.respond_to?(:call)
- case host.is_a?(Proc) ? host.arity : host.method(:call).arity
- when 2
- request = controller.respond_to?(:request) && controller.request
- host.call(source, request)
- else
- host.call(source)
- end
- else
- (host =~ /%d/) ? host % (source.hash % 4) : host
- end
- end
- end
-
- @@asset_timestamps_cache = {}
- @@asset_timestamps_cache_guard = Mutex.new
-
- # Use the RAILS_ASSET_ID environment variable or the source's
- # modification time as its cache-busting asset id.
- def rails_asset_id(source)
- if asset_id = ENV["RAILS_ASSET_ID"]
- asset_id
- else
- if @@cache_asset_timestamps && (asset_id = @@asset_timestamps_cache[source])
- asset_id
- else
- path = File.join(config.assets_dir, source)
- asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : ''
-
- if @@cache_asset_timestamps
- @@asset_timestamps_cache_guard.synchronize do
- @@asset_timestamps_cache[source] = asset_id
- end
- end
-
- asset_id
- end
- end
- end
-
- # Break out the asset path rewrite in case plugins wish to put the asset id
- # someplace other than the query string.
- def rewrite_asset_path(source, path = nil)
- if path && path.respond_to?(:call)
- return path.call(source)
- elsif path && path.is_a?(String)
- return path % [source]
- end
-
- asset_id = rails_asset_id(source)
- if asset_id.blank?
- source
- else
- source + "?#{asset_id}"
- end
- end
-
- def javascript_src_tag(source, options)
- content_tag("script", "", { "type" => Mime::JS, "src" => path_to_javascript(source) }.merge(options))
- end
-
- def stylesheet_tag(source, options)
- tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => html_escape(path_to_stylesheet(source)) }.merge(options), false, false)
- end
-
- def compute_javascript_paths(*args)
- expand_javascript_sources(*args).collect { |source| compute_public_path(source, 'javascripts', 'js', false) }
- end
-
- def compute_stylesheet_paths(*args)
- expand_stylesheet_sources(*args).collect { |source| compute_public_path(source, 'stylesheets', 'css', false) }
- end
-
- def expand_javascript_sources(sources, recursive = false)
- if sources.include?(:all)
- all_javascript_files = collect_asset_files(config.javascripts_dir, ('**' if recursive), '*.js')
- ((determine_source(:defaults, @@javascript_expansions).dup & all_javascript_files) + all_javascript_files).uniq
- else
- expanded_sources = sources.collect do |source|
- determine_source(source, @@javascript_expansions)
- end.flatten
- expanded_sources << "application" if sources.include?(:defaults) && File.exist?(File.join(config.javascripts_dir, "application.js"))
- expanded_sources
- end
- end
-
- def expand_stylesheet_sources(sources, recursive)
- if sources.first == :all
- collect_asset_files(config.stylesheets_dir, ('**' if recursive), '*.css')
- else
- sources.collect do |source|
- determine_source(source, @@stylesheet_expansions)
- end.flatten
- end
- end
-
- def determine_source(source, collection)
- case source
- when Symbol
- collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}")
- else
- source
- end
- end
-
- def ensure_stylesheet_sources!(sources)
- sources.each do |source|
- asset_file_path!(path_to_stylesheet(source))
- end
- return sources
- end
-
- def ensure_javascript_sources!(sources)
- sources.each do |source|
- asset_file_path!(path_to_javascript(source))
- end
- return sources
- end
-
- def join_asset_file_contents(paths)
- paths.collect { |path| File.read(asset_file_path!(path)) }.join("\n\n")
- end
-
- def write_asset_file_contents(joined_asset_path, asset_paths)
-
- FileUtils.mkdir_p(File.dirname(joined_asset_path))
- File.atomic_write(joined_asset_path) { |cache| cache.write(join_asset_file_contents(asset_paths)) }
-
- # Set mtime to the latest of the combined files to allow for
- # consistent ETag without a shared filesystem.
- mt = asset_paths.map { |p| File.mtime(asset_file_path(p)) }.max
- File.utime(mt, mt, joined_asset_path)
- end
-
- def asset_file_path(path)
- File.join(config.assets_dir, path.split('?').first)
- end
-
- def asset_file_path!(path)
- unless is_uri?(path)
- absolute_path = asset_file_path(path)
- raise(Errno::ENOENT, "Asset file not found at '#{absolute_path}'" ) unless File.exist?(absolute_path)
- return absolute_path
- end
- end
-
- def collect_asset_files(*path)
- dir = path.first
-
- Dir[File.join(*path.compact)].collect do |file|
- file[-(file.size - dir.size - 1)..-1].sub(/\.\w+$/, '')
- end.sort
+ def asset_paths
+ @asset_paths ||= AssetPaths.new(config, controller)
end
end
end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
new file mode 100644
index 0000000000..52eb43a1cd
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
@@ -0,0 +1,146 @@
+require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/file'
+require 'action_view/helpers/tag_helper'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class AssetIncludeTag
+ attr_reader :config, :asset_paths
+
+ class_attribute :expansions
+ def self.inherited(base)
+ base.expansions = { }
+ end
+
+ def initialize(config, asset_paths)
+ @config = config
+ @asset_paths = asset_paths
+ end
+
+ def asset_name
+ raise NotImplementedError
+ end
+
+ def extension
+ raise NotImplementedError
+ end
+
+ def custom_dir
+ raise NotImplementedError
+ end
+
+ def asset_tag(source, options)
+ raise NotImplementedError
+ end
+
+ def include_tag(*sources)
+ options = sources.extract_options!.stringify_keys
+ concat = options.delete("concat")
+ cache = concat || options.delete("cache")
+ recursive = options.delete("recursive")
+
+ if concat || (config.perform_caching && cache)
+ joined_name = (cache == true ? "all" : cache) + ".#{extension}"
+ joined_path = File.join((joined_name[/^#{File::SEPARATOR}/] ? config.assets_dir : custom_dir), joined_name)
+ unless config.perform_caching && File.exists?(joined_path)
+ write_asset_file_contents(joined_path, compute_paths(sources, recursive))
+ end
+ asset_tag(joined_name, options)
+ else
+ sources = expand_sources(sources, recursive)
+ ensure_sources!(sources) if cache
+ sources.collect { |source| asset_tag(source, options) }.join("\n").html_safe
+ end
+ end
+
+
+ private
+
+ def path_to_asset(source, include_host = true)
+ asset_paths.compute_public_path(source, asset_name.to_s.pluralize, extension, include_host)
+ end
+
+ def compute_paths(*args)
+ expand_sources(*args).collect { |source| asset_paths.compute_public_path(source, asset_name.pluralize, extension, false) }
+ end
+
+ def expand_sources(sources, recursive)
+ if sources.first == :all
+ collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}")
+ else
+ sources.inject([]) do |list, source|
+ determined_source = determine_source(source, expansions)
+ update_source_list(list, determined_source)
+ end
+ end
+ end
+
+ def update_source_list(list, source)
+ case source
+ when String
+ list.delete(source)
+ list << source
+ when Array
+ updated_sources = source - list
+ list.concat(updated_sources)
+ end
+ end
+
+ def ensure_sources!(sources)
+ sources.each do |source|
+ asset_file_path!(path_to_asset(source, false))
+ end
+ end
+
+ def collect_asset_files(*path)
+ dir = path.first
+
+ Dir[File.join(*path.compact)].collect do |file|
+ file[-(file.size - dir.size - 1)..-1].sub(/\.\w+$/, '')
+ end.sort
+ end
+
+ def determine_source(source, collection)
+ case source
+ when Symbol
+ collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}")
+ else
+ source
+ end
+ end
+
+ def join_asset_file_contents(paths)
+ paths.collect { |path| File.read(asset_file_path!(path, true)) }.join("\n\n")
+ end
+
+ def write_asset_file_contents(joined_asset_path, asset_paths)
+ FileUtils.mkdir_p(File.dirname(joined_asset_path))
+ File.atomic_write(joined_asset_path) { |cache| cache.write(join_asset_file_contents(asset_paths)) }
+
+ # Set mtime to the latest of the combined files to allow for
+ # consistent ETag without a shared filesystem.
+ mt = asset_paths.map { |p| File.mtime(asset_file_path(p)) }.max
+ File.utime(mt, mt, joined_asset_path)
+ end
+
+ def asset_file_path(path)
+ File.join(config.assets_dir, path.split('?').first)
+ end
+
+ def asset_file_path!(path, error_if_file_is_uri = false)
+ if asset_paths.is_uri?(path)
+ raise(Errno::ENOENT, "Asset file #{path} is uri and cannot be merged into single file") if error_if_file_is_uri
+ else
+ absolute_path = asset_file_path(path)
+ raise(Errno::ENOENT, "Asset file not found at '#{absolute_path}'" ) unless File.exist?(absolute_path)
+ return absolute_path
+ end
+ end
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb
new file mode 100644
index 0000000000..014a03c54d
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb
@@ -0,0 +1,153 @@
+require 'active_support/core_ext/file'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class AssetPaths
+ # You can enable or disable the asset tag ids cache.
+ # With the cache enabled, the asset tag helper methods will make fewer
+ # expensive file system calls (the default implementation checks the file
+ # system timestamp). However this prevents you from modifying any asset
+ # files while the server is running.
+ #
+ # ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
+ mattr_accessor :cache_asset_ids
+
+ attr_reader :config, :controller
+
+ def initialize(config, controller)
+ @config = config
+ @controller = controller
+ end
+
+ # Add the extension +ext+ if not present. Return full URLs otherwise untouched.
+ # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
+ # roots. Rewrite the asset path for cache-busting asset ids. Include
+ # asset host, if configured, with the correct request protocol.
+ def compute_public_path(source, dir, ext = nil, include_host = true)
+ return source if is_uri?(source)
+
+ source = rewrite_extension(source, dir, ext) if ext
+ source = "/#{dir}/#{source}" unless source[0] == ?/
+ if controller.respond_to?(:env) && controller.env["action_dispatch.asset_path"]
+ source = rewrite_asset_path(source, controller.env["action_dispatch.asset_path"])
+ end
+ source = rewrite_asset_path(source, config.asset_path)
+
+ has_request = controller.respond_to?(:request)
+ source = rewrite_relative_url_root(source, controller.config.relative_url_root) if has_request && include_host
+ source = rewrite_host_and_protocol(source, has_request) if include_host
+
+ source
+ end
+
+ # Add or change an asset id in the asset id cache. This can be used
+ # for SASS on Heroku.
+ # :api: public
+ def add_to_asset_ids_cache(source, asset_id)
+ self.asset_ids_cache_guard.synchronize do
+ self.asset_ids_cache[source] = asset_id
+ end
+ end
+
+ def is_uri?(path)
+ path =~ %r{^[-a-z]+://|^cid:}
+ end
+
+ private
+
+ def rewrite_extension(source, dir, ext)
+ source_ext = File.extname(source)
+
+ source_with_ext = if source_ext.empty?
+ "#{source}.#{ext}"
+ elsif ext != source_ext[1..-1]
+ with_ext = "#{source}.#{ext}"
+ with_ext if File.exist?(File.join(config.assets_dir, dir, with_ext))
+ end
+
+ source_with_ext || source
+ end
+
+ # Break out the asset path rewrite in case plugins wish to put the asset id
+ # someplace other than the query string.
+ def rewrite_asset_path(source, path = nil)
+ if path && path.respond_to?(:call)
+ return path.call(source)
+ elsif path && path.is_a?(String)
+ return path % [source]
+ end
+
+ asset_id = rails_asset_id(source)
+ if asset_id.empty?
+ source
+ else
+ "#{source}?#{asset_id}"
+ end
+ end
+
+ mattr_accessor :asset_ids_cache
+ self.asset_ids_cache = {}
+
+ mattr_accessor :asset_ids_cache_guard
+ self.asset_ids_cache_guard = Mutex.new
+
+ # Use the RAILS_ASSET_ID environment variable or the source's
+ # modification time as its cache-busting asset id.
+ def rails_asset_id(source)
+ if asset_id = ENV["RAILS_ASSET_ID"]
+ asset_id
+ else
+ if self.cache_asset_ids && (asset_id = self.asset_ids_cache[source])
+ asset_id
+ else
+ path = File.join(config.assets_dir, source)
+ asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : ''
+
+ if self.cache_asset_ids
+ add_to_asset_ids_cache(source, asset_id)
+ end
+
+ asset_id
+ end
+ end
+ end
+
+ def rewrite_relative_url_root(source, relative_url_root)
+ relative_url_root && !source.starts_with?("#{relative_url_root}/") ? "#{relative_url_root}#{source}" : source
+ end
+
+ def rewrite_host_and_protocol(source, has_request)
+ host = compute_asset_host(source)
+ if has_request && host && !is_uri?(host)
+ host = "#{controller.request.protocol}#{host}"
+ end
+ "#{host}#{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 the proc if it's a proc or the value from
+ # invoking call if it's an object responding to call.
+ def compute_asset_host(source)
+ if host = config.asset_host
+ if host.is_a?(Proc) || host.respond_to?(:call)
+ case host.is_a?(Proc) ? host.arity : host.method(:call).arity
+ when 2
+ request = controller.respond_to?(:request) && controller.request
+ host.call(source, request)
+ else
+ host.call(source)
+ end
+ else
+ (host =~ /%d/) ? host % (source.hash % 4) : host
+ end
+ end
+ end
+ end
+
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
new file mode 100644
index 0000000000..82bbfcc7d2
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
@@ -0,0 +1,184 @@
+require 'active_support/concern'
+require 'active_support/core_ext/file'
+require 'action_view/helpers/tag_helper'
+require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class JavascriptIncludeTag < AssetIncludeTag
+ include TagHelper
+
+ def asset_name
+ 'javascript'
+ end
+
+ def extension
+ 'js'
+ end
+
+ def asset_tag(source, options)
+ content_tag("script", "", { "type" => Mime::JS, "src" => path_to_asset(source) }.merge(options))
+ end
+
+ def custom_dir
+ config.javascripts_dir
+ end
+
+ private
+
+ def expand_sources(sources, recursive = false)
+ if sources.include?(:all)
+ all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application']) << 'application'
+ ((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq
+ else
+ expanded_sources = sources.inject([]) do |list, source|
+ determined_source = determine_source(source, expansions)
+ update_source_list(list, determined_source)
+ end
+ add_application_js(expanded_sources, sources)
+ expanded_sources
+ end
+ end
+
+ def add_application_js(expanded_sources, sources)
+ if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}"))
+ expanded_sources.delete('application')
+ expanded_sources << "application"
+ end
+ end
+ end
+
+
+ module JavascriptTagHelpers
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Register one or more javascript files to be included when <tt>symbol</tt>
+ # is passed to <tt>javascript_include_tag</tt>. This method is typically intended
+ # to be called from plugin initialization to register javascript files
+ # that the plugin installed in <tt>public/javascripts</tt>.
+ #
+ # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
+ #
+ # javascript_include_tag :monkey # =>
+ # <script type="text/javascript" src="/javascripts/head.js"></script>
+ # <script type="text/javascript" src="/javascripts/body.js"></script>
+ # <script type="text/javascript" src="/javascripts/tail.js"></script>
+ def register_javascript_expansion(expansions)
+ js_expansions = JavascriptIncludeTag.expansions
+ expansions.each do |key, values|
+ js_expansions[key] = (js_expansions[key] || []) | Array(values)
+ 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.
+ #
+ # ==== Examples
+ # 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.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr
+ # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
+ def javascript_path(source)
+ asset_paths.compute_public_path(source, 'javascripts', 'js')
+ end
+ alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
+
+ # 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 <tt>public/javascripts</tt> directory for inclusion into the
+ # current page or you can pass the full path relative to your document
+ # root. To include the Prototype and Scriptaculous JavaScript libraries in
+ # your application, pass <tt>:defaults</tt> as the source. When using
+ # <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in
+ # <tt>public/javascripts</tt> it will be included as well. You can modify the
+ # HTML attributes of the script tag by passing a hash as the last argument.
+ #
+ # ==== Examples
+ # javascript_include_tag "xmlhr" # =>
+ # <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "xmlhr.js" # =>
+ # <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "common.javascript", "/elsewhere/cools" # =>
+ # <script type="text/javascript" src="/javascripts/common.javascript?1284139606"></script>
+ # <script type="text/javascript" src="/elsewhere/cools.js?1423139606"></script>
+ #
+ # javascript_include_tag "http://www.railsapplication.com/xmlhr" # =>
+ # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # =>
+ # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag :defaults # =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
+ # ...
+ # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
+ #
+ # * = The application.js file is only referenced if it exists
+ #
+ # You can also include all javascripts in the +javascripts+ directory using <tt>:all</tt> as the source:
+ #
+ # javascript_include_tag :all # =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
+ # ...
+ # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
+ #
+ # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to
+ # all subsequently included files.
+ #
+ # If you want Rails to search in all the subdirectories under javascripts, you should explicitly set <tt>:recursive</tt>:
+ #
+ # javascript_include_tag :all, :recursive => true
+ #
+ # == Caching multiple javascripts into one
+ #
+ # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be
+ # compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching
+ # is set to <tt>true</tt> (which is the case by default for the Rails production environment, but not for the development
+ # environment).
+ #
+ # ==== Examples
+ # javascript_include_tag :all, :cache => true # when config.perform_caching is false =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
+ # ...
+ # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
+ #
+ # javascript_include_tag :all, :cache => true # when config.perform_caching is true =>
+ # <script type="text/javascript" src="/javascripts/all.js?1344139789"></script>
+ #
+ # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is false =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/cart.js?1289139157"></script>
+ # <script type="text/javascript" src="/javascripts/checkout.js?1299139816"></script>
+ #
+ # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is true =>
+ # <script type="text/javascript" src="/javascripts/shop.js?1299139816"></script>
+ #
+ # The <tt>:recursive</tt> option is also available for caching:
+ #
+ # javascript_include_tag :all, :cache => true, :recursive => true
+ def javascript_include_tag(*sources)
+ @javascript_include ||= JavascriptIncludeTag.new(config, asset_paths)
+ @javascript_include.include_tag(*sources)
+ end
+
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
new file mode 100644
index 0000000000..a48c87b49a
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
@@ -0,0 +1,147 @@
+require 'active_support/concern'
+require 'active_support/core_ext/file'
+require 'action_view/helpers/tag_helper'
+require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class StylesheetIncludeTag < AssetIncludeTag
+ include TagHelper
+
+ def asset_name
+ 'stylesheet'
+ end
+
+ def extension
+ 'css'
+ end
+
+ def asset_tag(source, options)
+ tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => ERB::Util.html_escape(path_to_asset(source)) }.merge(options), false, false)
+ end
+
+ def custom_dir
+ config.stylesheets_dir
+ end
+ end
+
+
+ module StylesheetTagHelpers
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Register one or more stylesheet files to be included when <tt>symbol</tt>
+ # is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended
+ # to be called from plugin initialization to register stylesheet files
+ # that the plugin installed in <tt>public/stylesheets</tt>.
+ #
+ # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
+ #
+ # stylesheet_link_tag :monkey # =>
+ # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
+ def register_stylesheet_expansion(expansions)
+ style_expansions = StylesheetIncludeTag.expansions
+ expansions.each do |key, values|
+ style_expansions[key] = (style_expansions[key] || []) | Array(values)
+ end
+ end
+ end
+
+ # 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.
+ #
+ # ==== Examples
+ # 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.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style
+ # stylesheet_path "http://www.railsapplication.com/css/style.css" # => http://www.railsapplication.com/css/style.css
+ def stylesheet_path(source)
+ asset_paths.compute_public_path(source, 'stylesheets', 'css')
+ end
+ alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
+
+ # Returns a stylesheet link tag for the sources specified as arguments. If
+ # you don't specify an extension, <tt>.css</tt> will be appended automatically.
+ # You can modify the link attributes by passing a hash as the last argument.
+ #
+ # ==== Examples
+ # stylesheet_link_tag "style" # =>
+ # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "style.css" # =>
+ # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "http://www.railsapplication.com/style.css" # =>
+ # <link href="http://www.railsapplication.com/style.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "style", :media => "all" # =>
+ # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "style", :media => "print" # =>
+ # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "random.styles", "/css/stylish" # =>
+ # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source:
+ #
+ # stylesheet_link_tag :all # =>
+ # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>:
+ #
+ # stylesheet_link_tag :all, :recursive => true
+ #
+ # == Caching multiple stylesheets into one
+ #
+ # 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 config.perform_caching
+ # is set to true (which is the case by default for the Rails production environment, but not for the development
+ # environment). Examples:
+ #
+ # ==== Examples
+ # stylesheet_link_tag :all, :cache => true # when config.perform_caching is false =>
+ # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag :all, :cache => true # when config.perform_caching is true =>
+ # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is false =>
+ # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is true =>
+ # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # The <tt>:recursive</tt> option is also available for caching:
+ #
+ # stylesheet_link_tag :all, :cache => true, :recursive => true
+ #
+ # To force concatenation (even in development mode) set <tt>:concat</tt> to true. This is useful if
+ # you have too many stylesheets for IE to load.
+ #
+ # stylesheet_link_tag :all, :concat => true
+ #
+ def stylesheet_link_tag(*sources)
+ @stylesheet_include ||= StylesheetIncludeTag.new(config, asset_paths)
+ @stylesheet_include.include_tag(*sources)
+ end
+
+ end
+
+ 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
index 8e7cf2e701..db9d7a08ff 100644
--- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb
+++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
@@ -51,7 +51,7 @@ module ActionView
# * <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.request_uri.split(".")[0]}"
+ # * <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).
diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb
index f544a9d147..385378ea29 100644
--- a/actionpack/lib/action_view/helpers/cache_helper.rb
+++ b/actionpack/lib/action_view/helpers/cache_helper.rb
@@ -2,31 +2,29 @@ module ActionView
# = Action View Cache Helper
module Helpers
module CacheHelper
- # This helper to exposes a method for caching of view fragments.
- # See ActionController::Caching::Fragments for usage instructions.
+ # This helper exposes a method for caching fragments of a view
+ # rather than an entire action or page. This technique is useful
+ # caching pieces like menus, lists of newstopics, static HTML
+ # fragments, and so on. This method takes a block that contains
+ # the content you wish to cache.
#
- # A method for caching fragments of a view rather than an entire
- # action or page. This technique is useful caching pieces like
- # menus, lists of news topics, static HTML fragments, and so on.
- # This method takes a block that contains the content you wish
- # to cache. See ActionController::Caching::Fragments for more
- # information.
+ # See ActionController::Caching::Fragments for usage instructions.
#
# ==== Examples
- # If you wanted to cache a navigation menu, you could do the
- # following.
+ # If you want to cache a navigation menu, you can do following:
#
# <% cache do %>
# <%= render :partial => "menu" %>
# <% end %>
#
- # You can also cache static content...
+ # You can also cache static content:
#
# <% cache do %>
# <p>Hello users! Welcome to our website!</p>
# <% end %>
#
- # ...and static content mixed with RHTML content.
+ # Static content with embedded ruby content can be cached as
+ # well:
#
# <% cache do %>
# Topics:
@@ -46,8 +44,8 @@ module ActionView
private
# TODO: Create an object that has caching read/write on it
def fragment_for(name = {}, options = nil, &block) #:nodoc:
- if controller.fragment_exist?(name, options)
- controller.read_fragment(name, options)
+ if fragment = controller.read_fragment(name, options)
+ fragment
else
# VIEW TODO: Make #capture usable outside of ERB
# This dance is needed because Builder can't use capture
diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb
index 89e95e8694..c88bd1efd5 100644
--- a/actionpack/lib/action_view/helpers/capture_helper.rb
+++ b/actionpack/lib/action_view/helpers/capture_helper.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/output_safety'
module ActionView
# = Action View Capture Helper
@@ -38,7 +39,7 @@ module ActionView
value = nil
buffer = with_output_buffer { value = yield(*args) }
if string = buffer.presence || value and string.is_a?(String)
- NonConcattingString.new(string)
+ ERB::Util.html_escape string
end
end
@@ -106,7 +107,7 @@ module ActionView
# <%= javascript_include_tag :defaults %>
# <% end %>
#
- # That will place <script> tags for Prototype, Scriptaculous, and application.js (if it exists)
+ # That will place <tt>script</tt> tags for Prototype, Scriptaculous, and application.js (if it exists)
# on the page; this technique is useful if you'll only be using these scripts in a few views.
#
# Note that content_for concatenates the blocks it is given for a particular
diff --git a/actionpack/lib/action_view/helpers/csrf_helper.rb b/actionpack/lib/action_view/helpers/csrf_helper.rb
index 3d03f6aac6..65c8debc76 100644
--- a/actionpack/lib/action_view/helpers/csrf_helper.rb
+++ b/actionpack/lib/action_view/helpers/csrf_helper.rb
@@ -1,14 +1,30 @@
+require 'active_support/core_ext/string/strip'
+
module ActionView
# = Action View CSRF Helper
module Helpers
module CsrfHelper
- # Returns a meta tag with the cross-site request forgery protection token
- # for forms to use. Place this in your head.
- def csrf_meta_tag
- if protect_against_forgery?
- %(<meta name="csrf-param" content="#{Rack::Utils.escape_html(request_forgery_protection_token)}"/>\n<meta name="csrf-token" content="#{Rack::Utils.escape_html(form_authenticity_token)}"/>).html_safe
- end
+ # 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
+ <<-METAS.strip_heredoc.chomp.html_safe if protect_against_forgery?
+ <meta name="csrf-param" content="#{Rack::Utils.escape_html(request_forgery_protection_token)}"/>
+ <meta name="csrf-token" content="#{Rack::Utils.escape_html(form_authenticity_token)}"/>
+ METAS
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
index 8050669adb..6cd1565031 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -1,6 +1,8 @@
-require "date"
+require 'date'
require 'action_view/helpers/tag_helper'
+require 'active_support/core_ext/date/conversions'
require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/object/with_options'
module ActionView
module Helpers
@@ -214,21 +216,10 @@ module ActionView
# # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute
# time_select("post", "sunrise")
#
- # # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted
- # # attribute
- # time_select("order", "submitted")
- #
- # # Creates a time select tag that, when POSTed, will be stored in the mail variable in the sent_at attribute
- # time_select("mail", "sent_at")
- #
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in
# # the sunrise attribute.
# time_select("post", "start_time", :include_seconds => true)
#
- # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the entry variables in
- # # the submission_time attribute.
- # time_select("entry", "submission_time", :include_seconds => true)
- #
# # You can set the :minute_step to 15 which will give you: 00, 15, 30 and 45.
# time_select 'game', 'game_time', {:minute_step => 15}
#
@@ -576,6 +567,27 @@ module ActionView
def select_year(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_year
end
+
+ # Returns an html time tag for the given date or time.
+ #
+ # ==== Examples
+ # time_tag Date.today # =>
+ # <time datetime="2010-11-04">November 04, 2010</time>
+ # time_tag Time.now # =>
+ # <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
+ # time_tag Date.yesterday, 'Yesterday' # =>
+ # <time datetime="2010-11-03">Yesterday</time>
+ # time_tag Date.today, :pubdate => true # =>
+ # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
+ #
+ def time_tag(date_or_time, *args)
+ options = args.extract_options!
+ format = options.delete(:format) || :long
+ content = args.first || I18n.l(date_or_time, :format => format)
+ datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339
+
+ content_tag(:time, content, options.reverse_merge(:datetime => datetime))
+ end
end
class DateTimeSelector #:nodoc:
@@ -605,7 +617,7 @@ module ActionView
@options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
- # valid (otherwise it could be 31 and february wouldn't be a valid date)
+ # valid (otherwise it could be 31 and February wouldn't be a valid date)
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
@@ -632,7 +644,7 @@ module ActionView
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
- # valid (otherwise it could be 31 and february wouldn't be a valid date)
+ # valid (otherwise it could be 31 and February wouldn't be a valid date)
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
@@ -751,10 +763,8 @@ module ActionView
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
def translated_month_names
- begin
- key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
- I18n.translate(key, :locale => @options[:locale])
- end
+ key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
+ I18n.translate(key, :locale => @options[:locale])
end
# Lookup month name for number
@@ -781,9 +791,7 @@ module ActionView
memoize :date_order
def translated_date_order
- begin
- I18n.translate(:'date.order', :locale => @options[:locale]) || []
- end
+ I18n.translate(:'date.order', :locale => @options[:locale]) || []
end
# Build full select tag from date type and options
@@ -837,15 +845,14 @@ module ActionView
# prompt_option_tag(:month, :prompt => 'Select month')
# => "<option value="">Select month</option>"
def prompt_option_tag(type, options)
- default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
-
- case options
- when Hash
- prompt = default_options.merge(options)[type.to_sym]
- when String
- prompt = options
- else
- prompt = I18n.translate(('datetime.prompts.' + type.to_s).to_sym, :locale => @options[:locale])
+ 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 => '') : ''
@@ -897,6 +904,8 @@ module ActionView
# Returns the separator for a given datetime component
def separator(type)
case type
+ when :year
+ @options[:discard_year] ? "" : @options[:date_separator]
when :month
@options[:discard_month] ? "" : @options[:date_separator]
when :day
@@ -927,6 +936,7 @@ module ActionView
private
def datetime_selector(options, html_options)
datetime = value(object) || default_datetime(options)
+ @auto_index ||= nil
options = options.dup
options[:field_name] = @method_name
diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb
index 1491cb073f..cd67851642 100644
--- a/actionpack/lib/action_view/helpers/debug_helper.rb
+++ b/actionpack/lib/action_view/helpers/debug_helper.rb
@@ -1,6 +1,6 @@
module ActionView
# = Action View Debug Helper
- #
+ #
# Provides a set of methods for making it easier to debug Rails objects.
module Helpers
module DebugHelper
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index ebe055bebd..48abf119f1 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -2,9 +2,11 @@ require 'cgi'
require 'action_view/helpers/date_helper'
require 'action_view/helpers/tag_helper'
require 'action_view/helpers/form_tag_helper'
-require 'active_support/core_ext/class/inheritable_attributes'
+require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/array/extract_options'
module ActionView
# = Action View Form Helpers
@@ -111,6 +113,7 @@ module ActionView
# <%= f.text_field :version %><br />
# <%= f.label :author, 'Author' %>:
# <%= f.text_field :author %><br />
+ # <%= f.submit %>
# <% end %>
#
# There, +form_for+ is able to generate the rest of RESTful form
@@ -128,6 +131,7 @@ module ActionView
# Last name : <%= f.text_field :last_name %><br />
# Biography : <%= f.text_area :biography %><br />
# Admin? : <%= f.check_box :admin %><br />
+ # <%= f.submit %>
# <% end %>
#
# There, the argument is a symbol or string with the name of the
@@ -159,6 +163,7 @@ module ActionView
# Last name : <%= f.text_field :last_name %>
# Biography : <%= text_area :person, :biography %>
# Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %>
+ # <%= f.submit %>
# <% end %>
#
# This also works for the methods in FormOptionHelper and DateHelper that
@@ -202,10 +207,16 @@ module ActionView
# ...
# <% end %>
#
+ # You can also set the answer format, like this:
+ #
+ # <%= form_for(@post, :format => :json) do |f| %>
+ # ...
+ # <% end %>
+ #
# If you have an object that needs to be represented as a different
# parameter, like a Client that acts as a Person:
#
- # <%= form_for(@post, :as => :client do |f| %>
+ # <%= form_for(@post, :as => :client) do |f| %>
# ...
# <% end %>
#
@@ -222,8 +233,8 @@ module ActionView
# ...
# <% end %>
#
- # Where +@document = Document.find(params[:id])+ and
- # +@comment = Comment.new+.
+ # Where <tt>@document = Document.find(params[:id])</tt> and
+ # <tt>@comment = Comment.new</tt>.
#
# === Unobtrusive JavaScript
#
@@ -252,6 +263,24 @@ module ActionView
# ...
# </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(@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
@@ -262,8 +291,9 @@ module ActionView
# <%= form_for @person, :url => { :action => "create" }, :builder => LabellingFormBuilder do |f| %>
# <%= f.text_field :first_name %>
# <%= f.text_field :last_name %>
- # <%= text_area :person, :biography %>
- # <%= check_box_tag "person[admin]", @person.company.admin? %>
+ # <%= f.text_area :biography %>
+ # <%= f.check_box :admin %>
+ # <%= f.submit %>
# <% end %>
#
# In this case, if you use this:
@@ -287,31 +317,46 @@ module ActionView
#
# If you don't need to attach a form to a model instance, then check out
# FormTagHelper#form_tag.
- def form_for(record_or_name_or_array, *args, &proc)
+ #
+ # === Form to external resources
+ #
+ # When you build forms to external resources sometimes you need to set an authenticity token or just render a form
+ # without it, for example when you submit data to a payment gateway number and types of fields could be limited.
+ #
+ # To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
+ #
+ # <%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
+ # ...
+ # <% end %>
+ #
+ # If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
+ #
+ # <%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
+ # ...
+ # <% end %>
+ def form_for(record, options = {}, &proc)
raise ArgumentError, "Missing block" unless block_given?
- options = args.extract_options!
+ options[:html] ||= {}
- case record_or_name_or_array
+ case record
when String, Symbol
- ActiveSupport::Deprecation.warn("Using form_for(:name, @resource) is deprecated. Please use form_for(@resource, :as => :name) instead.", caller) unless args.empty?
- object_name = record_or_name_or_array
- when Array
- object = record_or_name_or_array.last
- object_name = options[:as] || ActiveModel::Naming.singular(object)
- apply_form_for_options!(record_or_name_or_array, options)
- args.unshift object
+ object_name = record
+ object = nil
else
- object = record_or_name_or_array
- object_name = options[:as] || ActiveModel::Naming.singular(object)
- apply_form_for_options!([object], options)
- args.unshift object
+ object = record.is_a?(Array) ? record.last : record
+ object_name = options[:as] || ActiveModel::Naming.param_key(object)
+ apply_form_for_options!(record, options)
end
- (options[:html] ||= {})[:remote] = true if options.delete(:remote)
+ options[:html][:remote] = options.delete(:remote)
+ options[:html][:authenticity_token] = options.delete(:authenticity_token)
- output = form_tag(options.delete(:url) || {}, options.delete(:html) || {})
- output << fields_for(object_name, *(args << options), &proc)
+ builder = options[:parent_builder] = instantiate_builder(object_name, object, options, &proc)
+ fields_for = fields_for(object_name, object, options, &proc)
+ default_options = builder.multipart? ? { :multipart => true } : {}
+ output = form_tag(options.delete(:url) || {}, default_options.merge!(options.delete(:html)))
+ output << fields_for
output.safe_concat('</form>')
end
@@ -319,21 +364,17 @@ module ActionView
object = object_or_array.is_a?(Array) ? object_or_array.last : object_or_array
object = convert_to_model(object)
- html_options =
- if object.respond_to?(:persisted?) && object.persisted?
- { :class => options[:as] ? "#{options[:as]}_edit" : dom_class(object, :edit),
- :id => options[:as] ? "#{options[:as]}_edit" : dom_id(object, :edit),
- :method => :put }
- else
- { :class => options[:as] ? "#{options[:as]}_new" : dom_class(object, :new),
- :id => options[:as] ? "#{options[:as]}_new" : dom_id(object),
- :method => :post }
- end
+ as = options[:as]
+ action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :put] : [:new, :post]
+ options[:html].reverse_merge!(
+ :class => as ? "#{as}_#{action}" : dom_class(object, action),
+ :id => as ? "#{as}_#{action}" : dom_id(object, action),
+ :method => method
+ )
- options[:html] ||= {}
- options[:html].reverse_merge!(html_options)
- options[:url] ||= polymorphic_path(object_or_array)
+ options[:url] ||= polymorphic_path(object_or_array, :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
@@ -348,6 +389,8 @@ module ActionView
# <%= fields_for @person.permission do |permission_fields| %>
# Admin? : <%= permission_fields.check_box :admin %>
# <% end %>
+ #
+ # <%= f.submit %>
# <% end %>
#
# ...or if you have an object that needs to be represented as a different
@@ -409,6 +452,7 @@ module ActionView
# 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
@@ -438,6 +482,7 @@ module ActionView
# ...
# Delete: <%= address_fields.check_box :_destroy %>
# <% end %>
+ # ...
# <% end %>
#
# ==== One-to-many
@@ -467,6 +512,7 @@ module ActionView
# Name: <%= project_fields.text_field :name %>
# <% end %>
# <% end %>
+ # ...
# <% end %>
#
# It's also possible to specify the instance to be used:
@@ -480,6 +526,7 @@ module ActionView
# <% end %>
# <% end %>
# <% end %>
+ # ...
# <% end %>
#
# Or a collection to be used:
@@ -489,6 +536,7 @@ module ActionView
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
+ # ...
# <% end %>
#
# When projects is already an association on Person you can use
@@ -518,22 +566,13 @@ module ActionView
# <%= person_form.fields_for :projects do |project_fields| %>
# Delete: <%= project_fields.check_box :_destroy %>
# <% end %>
+ # ...
# <% end %>
- def fields_for(record_or_name_or_array, *args, &block)
- raise ArgumentError, "Missing block" unless block_given?
- options = args.extract_options!
-
- case record_or_name_or_array
- when String, Symbol
- object_name = record_or_name_or_array
- object = args.first
- else
- object = record_or_name_or_array
- object_name = ActiveModel::Naming.singular(object)
- end
-
- builder = options[:builder] || ActionView::Base.default_form_builder
- capture(builder.new(object_name, object, self, options, block), &block)
+ def fields_for(record, record_object = nil, options = {}, &block)
+ builder = instantiate_builder(record, record_object, options, &block)
+ output = capture(builder, &block)
+ output.concat builder.hidden_field(:id) if output && options[:hidden_field_id] && !builder.emitted_hidden_id?
+ output
end
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
@@ -624,19 +663,19 @@ module ActionView
#
# ==== Examples
# password_field(:login, :pass, :size => 20)
- # # => <input type="text" id="login_pass" name="login[pass]" size="20" value="#{@login.pass}" />
+ # # => <input type="password" id="login_pass" name="login[pass]" size="20" />
#
- # password_field(:account, :secret, :class => "form_input")
- # # => <input type="text" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
+ # 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]').length > 30 { alert('Your password needs to be shorter!'); }")
- # # => <input type="text" id="user_password" name="user[password]" value="#{@user.password}" onchange = "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }"/>
+ # # => <input type="password" id="user_password" name="user[password]" onchange = "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }"/>
#
# password_field(:account, :pin, :size => 20, :class => 'form_input')
- # # => <input type="text" id="account_pin" name="account[pin]" size="20" value="#{@account.pin}" class="form_input" />
+ # # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" />
#
def password_field(object_name, method, options = {})
- InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("password", options)
+ InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("password", { :value => nil }.merge!(options))
end
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
@@ -657,11 +696,13 @@ module ActionView
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("hidden", options)
end
- # Returns an file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # 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>.
+ #
# ==== Examples
# file_field(:user, :avatar)
# # => <input type="file" id="user_avatar" name="user[avatar]" />
@@ -803,7 +844,7 @@ module ActionView
options["incremental"] = true unless options.has_key?("incremental")
end
- InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("search", options)
+ InstanceTag.new(object_name, method, self, options.delete("object")).to_input_field_tag("search", options)
end
# Returns a text_field of type "tel".
@@ -837,29 +878,42 @@ module ActionView
def range_field(object_name, method, options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_number_field_tag("range", options)
end
+
+ private
+
+ def instantiate_builder(record, *args, &block)
+ options = args.extract_options!
+ record_object = args.shift
+
+ case record
+ when String, Symbol
+ object = record_object
+ object_name = record
+ else
+ object = record
+ object_name = ActiveModel::Naming.param_key(object)
+ end
+
+ builder = options[:builder] || ActionView::Base.default_form_builder
+ builder.new(object_name, object, self, options, block)
+ end
end
- module InstanceTagMethods #:nodoc:
- extend ActiveSupport::Concern
+ class InstanceTag
include Helpers::CaptureHelper, Context, Helpers::TagHelper, Helpers::FormTagHelper
- attr_reader :method_name, :object_name
+ attr_reader :object, :method_name, :object_name
- DEFAULT_FIELD_OPTIONS = { "size" => 30 }.freeze
- DEFAULT_RADIO_OPTIONS = { }.freeze
- DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 }.freeze
+ DEFAULT_FIELD_OPTIONS = { "size" => 30 }
+ DEFAULT_RADIO_OPTIONS = { }
+ DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 }
def initialize(object_name, method_name, template_object, object = nil)
@object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
@template_object = template_object
- @object = object
- if @object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
- if (object ||= @template_object.instance_variable_get("@#{Regexp.last_match.pre_match}")) && 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
+ @object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
+ @object = retrieve_object(object)
+ @auto_index = retrieve_autoindex(Regexp.last_match.pre_match) if Regexp.last_match
end
def to_label_tag(text = nil, options = {}, &block)
@@ -905,7 +959,7 @@ module ActionView
end
options["type"] ||= field_type
options["value"] = options.fetch("value"){ value_before_type_cast(object) } unless field_type == "file"
- options["value"] &&= html_escape(options["value"])
+ options["value"] &&= ERB::Util.html_escape(options["value"])
add_default_name_and_id(options)
tag("input", options)
end
@@ -941,7 +995,7 @@ module ActionView
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
end
- content_tag("textarea", html_escape(options.delete('value') || value_before_type_cast(object)), options)
+ content_tag("textarea", ERB::Util.html_escape(options.delete('value') || value_before_type_cast(object)), options)
end
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
@@ -983,14 +1037,26 @@ module ActionView
content_tag(tag_name, value(object), options)
end
- def object
- @object || @template_object.instance_variable_get("@#{@object_name}")
+ 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.
+ # 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 value(object)
self.class.value(object, @method_name)
end
@@ -999,16 +1065,16 @@ module ActionView
self.class.value_before_type_cast(object, @method_name)
end
- module ClassMethods
+ class << self
def value(object, method_name)
- object.send method_name unless object.nil?
+ object.send method_name if object
end
def value_before_type_cast(object, method_name)
unless object.nil?
- object.respond_to?(method_name) ?
- object.send(method_name) :
- object.send(method_name + "_before_type_cast")
+ object.respond_to?(method_name + "_before_type_cast") ?
+ object.send(method_name + "_before_type_cast") :
+ object.send(method_name)
end
end
@@ -1085,17 +1151,21 @@ module ActionView
end
end
- class InstanceTag
- include InstanceTagMethods
- end
-
- class FormBuilder #:nodoc:
+ class FormBuilder
# The methods which wrap a form helper call.
- class_inheritable_accessor :field_helpers
+ class_attribute :field_helpers
self.field_helpers = (FormHelper.instance_method_names - ['form_for'])
attr_accessor :object_name, :object, :options
+ attr_reader :multipart, :parent_builder
+ alias :multipart? :multipart
+
+ def multipart=(multipart)
+ @multipart = multipart
+ parent_builder.multipart = multipart if parent_builder
+ end
+
def self.model_name
@model_name ||= Struct.new(:partial_path).new(name.demodulize.underscore.sub!(/_builder$/, ''))
end
@@ -1107,6 +1177,7 @@ module ActionView
def initialize(object_name, object, template, options, proc)
@nested_child_index = {}
@object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
+ @parent_builder = options[:parent_builder]
@default_options = @options ? @options.slice(:index) : {}
if @object_name.to_s.match(/\[\]$/)
if object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:to_param)
@@ -1115,9 +1186,10 @@ module ActionView
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
end
- (field_helpers - %w(label check_box radio_button fields_for hidden_field)).each do |selector|
+ (field_helpers - %w(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(
@@ -1139,27 +1211,23 @@ module ActionView
index = ""
end
- if options[:builder]
- args << {} unless args.last.is_a?(Hash)
- args.last[:builder] ||= options[:builder]
- end
+ args << {} unless args.last.is_a?(Hash)
+ args.last[:builder] ||= options[:builder]
+ args.last[:parent_builder] = self
case record_or_name_or_array
when String, Symbol
if nested_attributes_association?(record_or_name_or_array)
return fields_for_with_nested_attributes(record_or_name_or_array, args, block)
else
- name = "#{object_name}#{index}[#{record_or_name_or_array}]"
+ name = record_or_name_or_array
end
- when Array
- object = record_or_name_or_array.last
- name = "#{object_name}#{index}[#{ActiveModel::Naming.singular(object)}]"
- args.unshift(object)
else
- object = record_or_name_or_array
- name = "#{object_name}#{index}[#{ActiveModel::Naming.singular(object)}]"
+ object = record_or_name_or_array.is_a?(Array) ? record_or_name_or_array.last : record_or_name_or_array
+ name = ActiveModel::Naming.param_key(object)
args.unshift(object)
end
+ name = "#{object_name}#{index}[#{name}]"
@template.fields_for(name, *args, &block)
end
@@ -1181,6 +1249,11 @@ module ActionView
@template.hidden_field(@object_name, method, objectify_options(options))
end
+ 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:
#
@@ -1211,11 +1284,11 @@ module ActionView
def submit(value=nil, options={})
value, options = nil, value if value.is_a?(Hash)
value ||= submit_default_value
- @template.submit_tag(value, options.reverse_merge(:id => "#{object_name}_submit"))
+ @template.submit_tag(value, options)
end
def emitted_hidden_id?
- @emitted_hidden_id
+ @emitted_hidden_id ||= nil
end
private
@@ -1224,7 +1297,7 @@ module ActionView
end
def submit_default_value
- object = @object.respond_to?(:to_model) ? @object.to_model : @object
+ object = convert_to_model(@object)
key = object ? (object.persisted? ? :update : :create) : :submit
model = if object.class.respond_to?(:model_name)
@@ -1249,15 +1322,15 @@ module ActionView
name = "#{object_name}[#{association_name}_attributes]"
options = args.extract_options!
association = args.shift
- association = association.to_model if association.respond_to?(:to_model)
+ association = convert_to_model(association)
if association.respond_to?(:persisted?)
association = [association] if @object.send(association_name).is_a?(Array)
- elsif !association.is_a?(Array)
+ elsif !association.respond_to?(:to_ary)
association = @object.send(association_name)
end
- if association.is_a?(Array)
+ if association.respond_to?(:to_ary)
explicit_child_index = options[:child_index]
output = ActiveSupport::SafeBuffer.new
association.each do |child|
@@ -1270,22 +1343,22 @@ module ActionView
end
def fields_for_nested_model(name, object, options, block)
- object = object.to_model if object.respond_to?(:to_model)
+ object = convert_to_model(object)
- if object.persisted?
- @template.fields_for(name, object, options) do |builder|
- block.call(builder)
- @template.concat builder.hidden_field(:id) unless builder.emitted_hidden_id?
- end
- else
- @template.fields_for(name, object, options, &block)
- end
+ parent_include_id = self.options.fetch(:include_id, true)
+ include_id = options.fetch(:include_id, parent_include_id)
+ options[:hidden_field_id] = object.persisted? && include_id
+ @template.fields_for(name, object, options, &block)
end
def nested_child_index(name)
@nested_child_index[name] ||= -1
@nested_child_index[name] += 1
end
+
+ def convert_to_model(object)
+ object.respond_to?(:to_model) ? object.to_model : object
+ end
end
end
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index ee34452769..7698602022 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -2,6 +2,7 @@ require 'cgi'
require 'erb'
require 'action_view/helpers/form_helper'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/output_safety'
module ActionView
# = Action View Form Option Helpers
@@ -53,16 +54,16 @@ module ActionView
# <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
+ #
+ # 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.
- #
- # Example:
- #
+ #
+ # Example:
+ #
# 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>
@@ -100,7 +101,6 @@ module ActionView
#
module FormOptionsHelper
# ERB::Util can mask some helpers like textilize. Make sure to include them.
- include ERB::Util
include TextHelper
# Create a select tag and a series of contained option tags for the provided object and method.
@@ -140,7 +140,7 @@ module ActionView
# 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.
- #
+ #
# Example object structure for use with this method:
# class Post < ActiveRecord::Base
# belongs_to :author
@@ -247,7 +247,7 @@ module ActionView
#
# time_zone_select( "user", 'time_zone', /Australia/)
#
- # time_zone_select( "user", "time_zone", ActiveSupport::Timezone.all.sort, :model => ActiveSupport::Timezone)
+ # 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 = {})
InstanceTag.new(object, method, self, options.delete(:object)).to_time_zone_select_tag(priority_zones, options, html_options)
end
@@ -297,18 +297,18 @@ module ActionView
def options_for_select(container, selected = nil)
return container if String === container
- container = container.to_a if Hash === container
- selected, disabled = extract_selected_and_disabled(selected)
+ selected, disabled = extract_selected_and_disabled(selected).map do | r |
+ Array.wrap(r).map(&:to_s)
+ end
- options_for_select = container.inject([]) do |options, element|
+ container.map do |element|
html_attributes = option_html_attributes(element)
- text, value = option_text_and_value(element)
+ text, value = option_text_and_value(element).map(&:to_s)
selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
- options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{html_escape(text.to_s)}</option>)
- end
+ %(<option value="#{ERB::Util.html_escape(value)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{ERB::Util.html_escape(text)}</option>)
+ end.join("\n").html_safe
- options_for_select.join("\n").html_safe
end
# Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the
@@ -394,12 +394,12 @@ module ActionView
# <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.inject("") do |options_for_select, group|
+ collection.map do |group|
group_label_string = eval("group.#{group_label_method}")
- options_for_select += "<optgroup label=\"#{html_escape(group_label_string)}\">"
- options_for_select += options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key)
- options_for_select += '</optgroup>'
- end.html_safe
+ "<optgroup label=\"#{ERB::Util.html_escape(group_label_string)}\">" +
+ options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key) +
+ '</optgroup>'
+ end.join.html_safe
end
# Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
@@ -493,7 +493,7 @@ module ActionView
end
zone_options += options_for_select(convert_zones[zones], selected)
- zone_options
+ zone_options.html_safe
end
private
@@ -501,7 +501,7 @@ module ActionView
return "" unless Array === element
html_attributes = []
element.select { |e| Hash === e }.reduce({}, :merge).each do |k, v|
- html_attributes << " #{k}=\"#{html_escape(v.to_s)}\""
+ html_attributes << " #{k}=\"#{ERB::Util.html_escape(v.to_s)}\""
end
html_attributes.join
end
@@ -528,10 +528,12 @@ module ActionView
end
def extract_selected_and_disabled(selected)
- if selected.is_a?(Hash)
- [selected[:selected], selected[:disabled]]
+ if selected.is_a?(Proc)
+ [ selected, nil ]
else
- [selected, nil]
+ selected = Array.wrap(selected)
+ options = selected.extract_options!.symbolize_keys
+ [ options.include?(:selected) ? options[:selected] : selected, options[:disabled] ]
end
end
@@ -593,11 +595,11 @@ module ActionView
private
def add_options(option_tags, options, value = nil)
if options[:include_blank]
- option_tags = "<option value=\"\">#{html_escape(options[:include_blank]) if options[:include_blank].kind_of?(String)}</option>\n" + option_tags
+ option_tags = "<option value=\"\">#{ERB::Util.html_escape(options[:include_blank]) if options[:include_blank].kind_of?(String)}</option>\n" + option_tags
end
if value.blank? && options[:prompt]
prompt = options[:prompt].kind_of?(String) ? options[:prompt] : I18n.translate('helpers.select.prompt', :default => 'Please select')
- option_tags = "<option value=\"\">#{html_escape(prompt)}</option>\n" + option_tags
+ option_tags = "<option value=\"\">#{ERB::Util.html_escape(prompt)}</option>\n" + option_tags
end
option_tags.html_safe
end
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 1ea870426a..49aa434020 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -1,6 +1,7 @@
require 'cgi'
require 'action_view/helpers/tag_helper'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/output_safety'
module ActionView
# = Action View Form Tag Helpers
@@ -24,8 +25,11 @@ module ActionView
# * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post".
# If "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt>
# is added to simulate the verb over post.
+ # * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to
+ # pass custom authenticity token string, or to not add authenticity_token field at all
+ # (by passing <tt>false</tt>).
# * A list of parameters to feed to the URL the form will be posted to.
- # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
+ # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behaviour. By default this behaviour is an ajax submit.
#
# ==== Examples
@@ -38,14 +42,20 @@ module ActionView
# form_tag('/upload', :multipart => true)
# # => <form action="/upload" method="post" enctype="multipart/form-data">
#
- # <%= form_tag('/posts')do -%>
+ # <%= 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>
- #
+ #
# <%= form_tag('/posts', :remote => true) %>
# # => <form action="/posts" method="post" data-remote="true">
- #
+ #
+ # form_tag('http://far.away.com/form', :authenticity_token => false)
+ # # form without authenticity token
+ #
+ # form_tag('http://far.away.com/form', :authenticity_token => "cf50faa3fe97702ca1ae")
+ # # form with custom authenticity token
+ #
def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)
html_options = html_options_for_form(url_for_options, options, *parameters_for_url)
if block_given?
@@ -67,7 +77,7 @@ module ActionView
# * Any other key creates standard HTML attributes for the tag.
#
# ==== Examples
- # select_tag "people", options_from_collection_for_select(@people, "name", "id")
+ # select_tag "people", options_from_collection_for_select(@people, "id", "name")
# # <select id="people" name="people"><option value="1">David</option></select>
#
# select_tag "people", "<option>David</option>"
@@ -93,10 +103,6 @@ module ActionView
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
# # <option>Paris</option><option>Rome</option></select>
def select_tag(name, option_tags = nil, options = {})
- if Array === option_tags
- ActiveSupport::Deprecation.warn 'Passing an array of option_tags to select_tag implicitly joins them without marking them as HTML-safe. Pass option_tags.join.html_safe instead.', caller
- end
-
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
if blank = options.delete(:include_blank)
if blank.kind_of?(String)
@@ -115,6 +121,7 @@ module ActionView
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
+ # * <tt>:placeholder</tt> - The text contained in the field by default which is removed when the field receives focus.
# * Any other key creates standard HTML attributes for the tag.
#
# ==== Examples
@@ -124,6 +131,9 @@ module ActionView
# text_field_tag 'query', 'Enter your search query here'
# # => <input id="query" name="query" type="text" value="Enter your search query here" />
#
+ # text_field_tag 'search', nil, :placeholder => 'Enter search term...'
+ # # => <input id="search" name="search" placeholder="Enter search term..." type="text" />
+ #
# text_field_tag 'request', nil, :class => 'special_input'
# # => <input class="special_input" id="request" name="request" type="text" />
#
@@ -291,7 +301,7 @@ module ActionView
end
escape = options.key?("escape") ? options.delete("escape") : true
- content = html_escape(content) if escape
+ 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
@@ -351,12 +361,12 @@ module ActionView
# Creates a submit button with the text <tt>value</tt> as the caption.
#
# ==== Options
- # * <tt>:confirm => 'question?'</tt> - If present the unobtrusive JavaScript
- # drivers will provide a prompt with the question specified. If the user accepts,
+ # * <tt>:confirm => 'question?'</tt> - If present the unobtrusive JavaScript
+ # drivers will provide a prompt with the question specified. If the user accepts,
# the form is processed normally, otherwise no action is taken.
# * <tt>:disabled</tt> - If true, the user will not be able to use this input.
- # * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
- # disabled version of the submit button when the form is submitted. This feature is
+ # * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
+ # disabled version of the submit button when the form is submitted. This feature is
# provided by the unobtrusive JavaScript driver.
# * Any other key creates standard HTML options for the tag.
#
@@ -383,7 +393,7 @@ module ActionView
# # name="commit" type="submit" value="Edit" />
#
# submit_tag "Save", :confirm => "Are you sure?"
- # # => <input name='commit' type='submit' value='Save'
+ # # => <input name='commit' type='submit' value='Save'
# data-confirm="Are you sure?" />
#
def submit_tag(value = "Save changes", options = {})
@@ -394,12 +404,65 @@ module ActionView
end
if confirm = options.delete("confirm")
- add_confirm_to_attributes!(options, confirm)
+ options["data-confirm"] = confirm
end
tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys)
end
+ # Creates a button element that defines a <tt>submit</tt> button,
+ # <tt>reset</tt>button or a generic button which can be used in
+ # JavaScript, for example. You can use the button tag as a regular
+ # submit tag but it isn't supported in legacy browsers. However,
+ # the button tag allows richer labels such as images and emphasis,
+ # so this helper will also accept a block.
+ #
+ # ==== Options
+ # * <tt>:confirm => 'question?'</tt> - If present, the
+ # unobtrusive JavaScript drivers will provide a prompt with
+ # the question specified. If the user accepts, the form is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disabled</tt> - If true, the user will not be able to
+ # use this input.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Examples
+ # button_tag
+ # # => <button name="button" type="submit">Button</button>
+ #
+ # button_tag(:type => 'button') do
+ # content_tag(:strong, 'Ask me!')
+ # end
+ # # => <button name="button" type="button">
+ # <strong>Ask me!</strong>
+ # </button>
+ #
+ # button_tag "Checkout", :disable_with => "Please wait..."
+ # # => <button data-disable-with="Please wait..." name="button"
+ # type="submit">Checkout</button>
+ #
+ def button_tag(content_or_options = nil, options = nil, &block)
+ options = content_or_options if block_given? && content_or_options.is_a?(Hash)
+ options ||= {}
+ options.stringify_keys!
+
+ if disable_with = options.delete("disable_with")
+ options["data-disable-with"] = disable_with
+ end
+
+ if confirm = options.delete("confirm")
+ options["data-confirm"] = confirm
+ end
+
+ options.reverse_merge! 'name' => 'button', 'type' => 'submit'
+
+ content_tag :button, content_or_options || 'Button', options, &block
+ end
+
# Displays an image which when clicked will submit the form.
#
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
@@ -427,7 +490,7 @@ module ActionView
options.stringify_keys!
if confirm = options.delete("confirm")
- add_confirm_to_attributes!(options, confirm)
+ options["data-confirm"] = confirm
end
tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options.stringify_keys)
@@ -529,17 +592,19 @@ module ActionView
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
- # responsability of the caller to escape all the values.
+ # responsibility of the caller to escape all the values.
html_options["action"] = url_for(url_for_options, *parameters_for_url)
html_options["accept-charset"] = "UTF-8"
html_options["data-remote"] = true if html_options.delete("remote")
+ html_options["authenticity_token"] = html_options.delete("authenticity_token") if html_options.has_key?("authenticity_token")
end
end
def extra_tags_for_form(html_options)
snowman_tag = tag(:input, :type => "hidden",
- :name => "_e", :value => "&#9731;".html_safe)
+ :name => "utf8", :value => "&#x2713;".html_safe)
+ authenticity_token = html_options.delete("authenticity_token")
method = html_options.delete("method").to_s
method_tag = case method
@@ -548,10 +613,10 @@ module ActionView
''
when /^post$/i, "", nil
html_options["method"] = "post"
- token_tag
+ token_tag(authenticity_token)
else
html_options["method"] = "post"
- tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag
+ tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag(authenticity_token)
end
tags = snowman_tag << method_tag
@@ -571,11 +636,12 @@ module ActionView
output.safe_concat("</form>")
end
- def token_tag
- unless protect_against_forgery?
+ def token_tag(token)
+ if token == false || !protect_against_forgery?
''
else
- tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
+ token = form_authenticity_token if token.nil?
+ tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => token)
end
end
diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb
index 84f53b842c..cd3a3eac80 100644
--- a/actionpack/lib/action_view/helpers/javascript_helper.rb
+++ b/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -65,7 +65,8 @@ module ActionView
# //]]>
# </script>
#
- # +html_options+ may be a hash of attributes for the <script> tag. Example:
+ # +html_options+ may be a hash of attributes for the <tt>\<script></tt>
+ # tag. Example:
# javascript_tag "alert('All is good')", :defer => 'defer'
# # => <script defer="defer" type="text/javascript">alert('All is good')</script>
#
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index f11027bc93..05a9c5b4f1 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -1,6 +1,7 @@
require 'active_support/core_ext/big_decimal/conversions'
require 'active_support/core_ext/float/rounding'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/output_safety'
module ActionView
# = Action View Number Helpers
@@ -14,7 +15,7 @@ module ActionView
# unchanged if can't be converted into a valid number.
module NumberHelper
- DEFAULT_CURRENCY_VALUES = { :format => "%u%n", :unit => "$", :separator => ".", :delimiter => ",",
+ DEFAULT_CURRENCY_VALUES = { :format => "%u%n", :negative_format => "-%u%n", :unit => "$", :separator => ".", :delimiter => ",",
:precision => 2, :significant => false, :strip_insignificant_zeros => false }
# Raised when argument +number+ param given to the helpers is invalid and
@@ -47,51 +48,51 @@ module ActionView
# number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".")
# => +1.123.555.1234 x 1343
def number_to_phone(number, options = {})
- return nil if number.nil?
+ return unless number
begin
Float(number)
- is_number_html_safe = true
rescue ArgumentError, TypeError
- if options[:raise]
- raise InvalidNumberError, number
- else
- is_number_html_safe = number.to_s.html_safe?
- end
- end
+ raise InvalidNumberError, number
+ end if options[:raise]
number = number.to_s.strip
options = options.symbolize_keys
- area_code = options[:area_code] || nil
+ area_code = options[:area_code]
delimiter = options[:delimiter] || "-"
- extension = options[:extension].to_s.strip || nil
- country_code = options[:country_code] || nil
+ extension = options[:extension]
+ country_code = options[:country_code]
- str = ""
- str << "+#{country_code}#{delimiter}" unless country_code.blank?
- str << if area_code
- number.gsub!(/([0-9]{1,3})([0-9]{3})([0-9]{4}$)/,"(\\1) \\2#{delimiter}\\3")
+ if area_code
+ number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
else
- number.gsub!(/([0-9]{0,3})([0-9]{3})([0-9]{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
- number.starts_with?('-') ? number.slice!(1..-1) : number
+ number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
+ number.slice!(0, 1) if number.starts_with?('-')
end
+
+ str = []
+ str << "+#{country_code}#{delimiter}" unless country_code.blank?
+ str << number
str << " x #{extension}" unless extension.blank?
- is_number_html_safe ? str.html_safe : str
+ ERB::Util.html_escape(str.join)
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 of the output string (defaults to "%u%n"). The field types are:
- #
- # %u The currency unit
- # %n The number
+ # * <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
@@ -99,12 +100,14 @@ module ActionView
# number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506
# number_to_currency(1234567890.506, :locale => :fr) # => 1 234 567 890,506 €
#
+ # number_to_currency(1234567890.50, :negative_format => "(%u%n)")
+ # # => ($1,234,567,890.51)
# number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "")
# # => &pound;1234567890,50
# number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "", :format => "%n %u")
# # => 1234567890,50 &pound;
def number_to_currency(number, options = {})
- return nil if number.nil?
+ return unless number
options.symbolize_keys!
@@ -112,11 +115,17 @@ module ActionView
currency = I18n.translate(:'number.currency.format', :locale => options[:locale], :default => {})
defaults = DEFAULT_CURRENCY_VALUES.merge(defaults).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 < 0
+ format = options.delete(:negative_format)
+ number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
+ end
+
begin
value = number_with_precision(number, options.merge(:raise => true))
format.gsub(/%n/, value).gsub(/%u/, unit).html_safe
@@ -149,7 +158,7 @@ module ActionView
# number_to_percentage(302.24398923423, :precision => 5) # => 302.24399%
# number_to_percentage(1000, :locale => :fr) # => 1 000,000%
def number_to_percentage(number, options = {})
- return nil if number.nil?
+ return unless number
options.symbolize_keys!
@@ -260,13 +269,14 @@ module ActionView
if number == 0
digits, rounded_number = 1, 0
else
- digits = (Math.log10(number) + 1).floor
- rounded_number = BigDecimal.new((number / 10 ** (digits - precision)).to_s).round.to_f * 10 ** (digits - precision)
+ digits = (Math.log10(number.abs) + 1).floor
+ rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
+ digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
end
- precision = precision - digits
+ precision -= digits
precision = precision > 0 ? precision : 0 #don't let it be negative
else
- rounded_number = BigDecimal.new((number * (10 ** precision)).to_s).round.to_f / 10 ** precision
+ rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
end
formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options)
if strip_insignificant_zeros
@@ -325,7 +335,7 @@ module ActionView
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
human = I18n.translate(:'number.human.format', :locale => options[:locale], :default => {})
defaults = defaults.merge(human)
-
+
options = options.reverse_merge(defaults)
#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)
@@ -359,7 +369,7 @@ module ActionView
# 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 mililiters", etc). You may define
+ # (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
@@ -415,13 +425,13 @@ module ActionView
# thousand:
# one: "kilometer"
# other: "kilometers"
- # billion: "gazilion-distance"
+ # 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 gazilion-distance"
+ # 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"
@@ -447,6 +457,8 @@ module ActionView
#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
@@ -457,10 +469,10 @@ module ActionView
I18n.translate(:"number.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| DECIMAL_UNITS.invert[e_name] }.sort_by{|e| -e}
+ end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
- number_exponent = Math.log10(number).floor
- display_exponent = unit_exponents.find{|e| number_exponent >= 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
diff --git a/actionpack/lib/action_view/helpers/output_safety_helper.rb b/actionpack/lib/action_view/helpers/output_safety_helper.rb
new file mode 100644
index 0000000000..a035dd70ad
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/output_safety_helper.rb
@@ -0,0 +1,38 @@
+require 'active_support/core_ext/string/output_safety'
+
+module ActionView #:nodoc:
+ # = Action View Raw Output Helper
+ module Helpers #:nodoc:
+ module OutputSafetyHelper
+ # This method outputs without escaping a string. Since escaping tags is
+ # now default, this can be used when you don't want Rails to automatically
+ # escape tags. This is not recommended if the data is coming from the user's
+ # input.
+ #
+ # For example:
+ #
+ # <%=raw @user.name %>
+ def raw(stringish)
+ stringish.to_s.html_safe
+ end
+
+ # This method returns a html safe string similar to what <tt>Array#join</tt>
+ # would return. All items in the array, including the supplied separator, are
+ # html escaped unless they are html safe, and the returned string is marked
+ # as html safe.
+ #
+ # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
+ # # => "<p>foo</p>&lt;br /&gt;&lt;p&gt;bar&lt;/p&gt;"
+ #
+ # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
+ # # => "<p>foo</p><br /><p>bar</p>"
+ #
+ def safe_join(array, sep=$,)
+ sep ||= "".html_safe
+ sep = ERB::Util.html_escape(sep)
+
+ array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index 99f9363a9a..18e303778c 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -1,6 +1,7 @@
require 'set'
require 'active_support/json'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/output_safety'
module ActionView
# = Action View Prototype Helpers
@@ -102,7 +103,7 @@ module ActionView
:form, :with, :update, :script, :type ]).merge(CALLBACKS)
# Returns the JavaScript needed for a remote function.
- # See the link_to_remote documentation at http://github.com/rails/prototype_legacy_helper as it takes the same arguments.
+ # See the link_to_remote documentation at https://github.com/rails/prototype_legacy_helper as it takes the same arguments.
#
# Example:
# # Generates: <select id="options" onchange="new Ajax.Updater('options',
@@ -130,8 +131,7 @@ module ActionView
"new Ajax.Updater(#{update}, "
url_options = options[:url]
- url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash)
- function << "'#{html_escape(escape_javascript(url_for(url_options)))}'"
+ function << "'#{ERB::Util.html_escape(escape_javascript(url_for(url_options)))}'"
function << ", #{javascript_options})"
function = "#{options[:before]}; #{function}" if options[:before]
@@ -161,8 +161,8 @@ module ActionView
# JavaScriptGenerator generates blocks of JavaScript code that allow you
# to change the content and presentation of multiple DOM elements. Use
- # this in your Ajax response bodies, either in a <script> tag or as plain
- # JavaScript sent with a Content-type of "text/javascript".
+ # this in your Ajax response bodies, either in a <tt>\<script></tt> tag
+ # or as plain JavaScript sent with a Content-type of "text/javascript".
#
# Create new instances with PrototypeHelper#update_page or with
# ActionController::Base#render, then call +insert_html+, +replace_html+,
@@ -224,7 +224,7 @@ module ActionView
#
# You can also use PrototypeHelper#update_page_tag instead of
# PrototypeHelper#update_page to wrap the generated JavaScript in a
- # <script> tag.
+ # <tt>\<script></tt> tag.
module GeneratorMethods
def to_s #:nodoc:
(@lines * $/).tap do |javascript|
@@ -546,7 +546,7 @@ module ActionView
end
def with_formats(*args)
- @context ? @context.update_details(:formats => args) { yield } : yield
+ @context ? @context.lookup_context.update_details(:formats => args) { yield } : yield
end
def javascript_object_for(object)
@@ -579,15 +579,15 @@ module ActionView
# page.hide 'spinner'
# end
def update_page(&block)
- JavaScriptGenerator.new(view_context, &block).to_s.html_safe
+ JavaScriptGenerator.new(self, &block).to_s.html_safe
end
- # Works like update_page but wraps the generated JavaScript in a <script>
- # tag. Use this to include generated JavaScript in an ERb template.
- # See JavaScriptGenerator for more information.
+ # Works like update_page but wraps the generated JavaScript in a
+ # <tt>\<script></tt> tag. Use this to include generated JavaScript in an
+ # ERb template. See JavaScriptGenerator for more information.
#
- # +html_options+ may be a hash of <script> attributes to be passed
- # to ActionView::Helpers::JavaScriptHelper#javascript_tag.
+ # +html_options+ may be a hash of <tt>\<script></tt> attributes to be
+ # passed to ActionView::Helpers::JavaScriptHelper#javascript_tag.
def update_page_tag(html_options = {}, &block)
javascript_tag update_page(&block), html_options
end
diff --git a/actionpack/lib/action_view/helpers/raw_output_helper.rb b/actionpack/lib/action_view/helpers/raw_output_helper.rb
deleted file mode 100644
index da7599fa8f..0000000000
--- a/actionpack/lib/action_view/helpers/raw_output_helper.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module ActionView #:nodoc:
- # = Action View Raw Output Helper
- module Helpers #:nodoc:
- module RawOutputHelper
- # This method outputs without escaping a string. Since escaping tags is
- # now default, this can be used when you don't want Rails to automatically
- # escape tags. This is not recommended if the data is coming from the user's
- # input.
- #
- # For example:
- #
- # <%=raw @user.name %>
- def raw(stringish)
- stringish.to_s.html_safe
- end
- end
- end
-end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/record_tag_helper.rb b/actionpack/lib/action_view/helpers/record_tag_helper.rb
index e4a9210cde..4d300a1469 100644
--- a/actionpack/lib/action_view/helpers/record_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/record_tag_helper.rb
@@ -52,9 +52,9 @@ module ActionView
#
# <li id="person_123" class="person bar">...
#
- def content_tag_for(tag_name, record, *args, &block)
- prefix = args.first.is_a?(Hash) ? nil : args.shift
- options = args.extract_options!
+ def content_tag_for(tag_name, record, prefix = nil, options = nil, &block)
+ options, prefix = prefix, nil if prefix.is_a?(Hash)
+ options ||= {}
options.merge!({ :class => "#{dom_class(record, prefix)} #{options[:class]}".strip, :id => dom_id(record, prefix) })
content_tag(tag_name, options, &block)
end
diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb
index d82005fa24..0fee34f8a4 100644
--- a/actionpack/lib/action_view/helpers/sanitize_helper.rb
+++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb
@@ -9,7 +9,7 @@ module ActionView
# 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
+ # 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.
@@ -21,7 +21,7 @@ module ActionView
#
# 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
+ # tags/attributes for single uses of +sanitize+ by passing either the
# <tt>:attributes</tt> or <tt>:tags</tt> options:
#
# Normal Use
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb
index 5d032b32a7..786af5ca58 100644
--- a/actionpack/lib/action_view/helpers/tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/tag_helper.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/output_safety'
require 'set'
module ActionView
@@ -7,16 +8,14 @@ module ActionView
# Provides methods to generate HTML tags programmatically when you can't use
# a Builder. By default, they output XHTML compliant tags.
module TagHelper
- include ERB::Util
-
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).to_set
- BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attr| attr.to_sym })
+ autofocus novalidate formnovalidate open pubdate).to_set
+ BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
# Returns an empty HTML tag of type +name+ which by default is XHTML
# compliant. Set +open+ to true to create an open tag compatible
@@ -25,9 +24,21 @@ module ActionView
# 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.
+ # 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")
@@ -36,14 +47,17 @@ module ActionView
# tag("br", nil, true)
# # => <br>
#
- # tag("input", { :type => 'text', :disabled => true })
+ # tag("input", :type => 'text', :disabled => true)
# # => <input type="text" disabled="disabled" />
#
- # tag("img", { :src => "open & shut.png" })
+ # tag("img", :src => "open & shut.png")
# # => <img src="open &amp; shut.png" />
#
- # tag("img", { :src => "open &amp; shut.png" }, false, false)
+ # tag("img", {:src => "open &amp; shut.png"}, false, false)
# # => <img src="open &amp; shut.png" />
+ #
+ # tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
+ # # => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
def tag(name, options = nil, open = false, escape = true)
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
end
@@ -118,11 +132,19 @@ module ActionView
unless options.blank?
attrs = []
options.each_pair do |key, value|
- if BOOLEAN_ATTRIBUTES.include?(key)
+ if key.to_s == 'data' && value.is_a?(Hash)
+ value.each do |k, v|
+ if !v.is_a?(String) && !v.is_a?(Symbol)
+ v = v.to_json
+ end
+ v = ERB::Util.html_escape(v) if escape
+ attrs << %(data-#{k.to_s.dasherize}="#{v}")
+ end
+ elsif BOOLEAN_ATTRIBUTES.include?(key)
attrs << %(#{key}="#{key}") if value
elsif !value.nil?
final_value = value.is_a?(Array) ? value.join(" ") : value
- final_value = html_escape(final_value) if escape
+ final_value = ERB::Util.html_escape(final_value) if escape
attrs << %(#{key}="#{final_value}")
end
end
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index c1de5c8cb3..2d3c5fe7e7 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -9,6 +9,24 @@ module ActionView
# 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>&lt;a href=\"http://example.com/\"&gt;Example&lt;/a&gt;</p>"
module TextHelper
extend ActiveSupport::Concern
@@ -134,6 +152,8 @@ module ActionView
# excerpt('This is an example', 'an', 5) # => ...s is an exam...
# excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example
def excerpt(text, phrase, *args)
+ return unless text && phrase
+
options = args.extract_options!
unless args.empty?
options[:radius] = args[0] || 100
@@ -141,21 +161,16 @@ module ActionView
end
options.reverse_merge!(:radius => 100, :omission => "...")
- if text && phrase
- phrase = Regexp.escape(phrase)
+ phrase = Regexp.escape(phrase)
+ return unless found_pos = text.mb_chars =~ /(#{phrase})/i
- if found_pos = text.mb_chars =~ /(#{phrase})/i
- start_pos = [ found_pos - options[:radius], 0 ].max
- end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min
+ start_pos = [ found_pos - options[:radius], 0 ].max
+ end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min
- prefix = start_pos > 0 ? options[:omission] : ""
- postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""
+ prefix = start_pos > 0 ? options[:omission] : ""
+ postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""
- prefix + text.mb_chars[start_pos..end_pos].strip + postfix
- else
- nil
- end
- end
+ prefix + text.mb_chars[start_pos..end_pos].strip + postfix
end
# Attempts to pluralize the +singular+ word unless +count+ is 1. If
@@ -219,6 +234,10 @@ module ActionView
#
# You can pass any HTML attributes into <tt>html_options</tt>. These
# will be added to all created paragraphs.
+ #
+ # ==== Options
+ # * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
+ #
# ==== Examples
# my_text = "Here is some basic text...\n...with a line break."
#
@@ -232,6 +251,9 @@ module ActionView
#
# simple_format("Look ma! A class!", :class => 'description')
# # => "<p class='description'>Look ma! A class!</p>"
+ #
+ # simple_format("<span>I'm allowed!</span> It's true.", {}, :sanitize => false)
+ # # => "<p><span>I'm allowed!</span> It's true.</p>"
def simple_format(text, html_options={}, options={})
text = ''.html_safe if text.nil?
start_tag = tag('p', html_options, true)
@@ -263,7 +285,7 @@ module ActionView
#
# post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com."
# auto_link(post_body, :html => { :target => '_blank' }) do |text|
- # truncate(text, 15)
+ # truncate(text, :length => 15)
# end
# # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>.
# Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>."
@@ -345,10 +367,10 @@ module ActionView
values.unshift(first_value)
cycle = get_cycle(name)
- if (cycle.nil? || cycle.values != values)
+ unless cycle && cycle.values == values
cycle = set_cycle(name, Cycle.new(*values))
end
- return cycle.to_s
+ cycle.to_s
end
# Returns the current cycle string after a cycle has been started. Useful
@@ -365,7 +387,7 @@ module ActionView
# <% end %>
def current_cycle(name = "default")
cycle = get_cycle(name)
- cycle.current_value unless cycle.nil?
+ cycle.current_value if cycle
end
# Resets a cycle so that it starts from the first element the next time
@@ -389,7 +411,7 @@ module ActionView
# </table>
def reset_cycle(name = "default")
cycle = get_cycle(name)
- cycle.reset unless cycle.nil?
+ cycle.reset if cycle
end
class Cycle #:nodoc:
@@ -444,7 +466,7 @@ module ActionView
end
AUTO_LINK_RE = %r{
- (?: ([\w+.:-]+:)// | www\. )
+ (?: ([0-9A-Za-z+.:-]+:)// | www\. )
[^\s<]+
}x
@@ -462,7 +484,7 @@ module ActionView
text.gsub(AUTO_LINK_RE) do
scheme, href = $1, $&
punctuation = []
-
+
if auto_linked?($`, $')
# do not change string; URL is already linked
href
@@ -507,7 +529,7 @@ module ActionView
end
end
end
-
+
# Detects already linked context or position in the middle of a tag
def auto_linked?(left, right)
(left =~ AUTO_LINK_CRE[0] and right =~ AUTO_LINK_CRE[1]) or
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
index dac9c28ab7..59e6ce878f 100644
--- a/actionpack/lib/action_view/helpers/translation_helper.rb
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -1,38 +1,56 @@
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?(MissingTranslationData) ? super.html_safe : super
+ end
+ }
+ end
+end
module ActionView
# = Action View Translation Helpers
module Helpers
module TranslationHelper
# Delegates to I18n#translate but also performs three additional functions.
- # First, it'll catch MissingTranslationData exceptions and turn them into
- # inline spans that contains the missing key, such that you can see in a
- # view what is missing where.
#
- # 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
+ # First, it'll pass the :rescue_format => :html option to I18n so that any caught
+ # MissingTranslationData exceptions 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: 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,
+ # 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
+ # 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 = {})
- translation = I18n.translate(scope_key_by_partial(key), options.merge!(:raise => true))
+ options.merge!(:rescue_format => :html) unless options.key?(:rescue_format)
+ translation = I18n.translate(scope_key_by_partial(key), options)
if html_safe_translation_key?(key) && translation.respond_to?(:html_safe)
translation.html_safe
else
translation
end
- rescue I18n::MissingTranslationData => e
- keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope])
- content_tag('span', keys.join(', '), :class => 'translation_missing')
end
alias :t :translate
@@ -45,8 +63,8 @@ module ActionView
private
def scope_key_by_partial(key)
if key.to_s.first == "."
- if @_virtual_path
- @_virtual_path.gsub(%r{/_?}, ".") + key.to_s
+ if (path = @_template && @_template.virtual_path)
+ path.gsub(%r{/_?}, ".") + key.to_s
else
raise "Cannot use t(#{key.inspect}) shortcut because path is not available"
end
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index a5c6718c58..2cd2dca711 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -1,6 +1,7 @@
require 'action_view/helpers/javascript_helper'
require 'active_support/core_ext/array/access'
require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/string/output_safety'
require 'action_dispatch'
module ActionView
@@ -13,7 +14,7 @@ module ActionView
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 the4 context of a request
+ # 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.
@@ -22,6 +23,10 @@ module ActionView
include ActionDispatch::Routing::UrlFor
include TagHelper
+ def _routes_context
+ controller
+ end
+
# Need to map default url options to controller one.
# def default_url_options(*args) #:nodoc:
# controller.send(:default_url_options, *args)
@@ -91,7 +96,7 @@ module ActionView
# # => javascript:history.back()
def url_for(options = {})
options ||= {}
- url = case options
+ case options
when String
options
when Hash
@@ -102,8 +107,6 @@ module ActionView
else
polymorphic_path(options)
end
-
- url
end
# Creates a link tag of the given +name+ using a URL created by the set
@@ -235,16 +238,11 @@ module ActionView
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
- if html_options
- html_options = html_options.stringify_keys
- href = html_options['href']
- tag_options = tag_options(html_options)
- else
- tag_options = nil
- end
+ href = html_options['href']
+ tag_options = tag_options(html_options)
- href_attr = "href=\"#{html_escape(url)}\"" unless href
- "<a #{href_attr}#{tag_options}>#{html_escape(name || url)}</a>".html_safe
+ href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
+ "<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
end
end
@@ -255,8 +253,9 @@ module ActionView
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
# the +link_to+ documentation.
#
- # The generated form element has a class name of <tt>button_to</tt>
- # to allow styling of the form itself and its children. You can control
+ # By default, the generated form element has a class name of <tt>button_to</tt>
+ # to allow styling of the form itself and its children. This can be changed
+ # using the <tt>:form_class</tt> modifier within +html_options+. You can control
# the form submission and input element behavior using +html_options+.
# This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
# described in the +link_to+ documentation. If no <tt>:method</tt> modifier
@@ -269,13 +268,16 @@ module ActionView
# The +options+ hash accepts the same options as url_for.
#
# There are a few special +html_options+:
- # * <tt>:method</tt> - Specifies the anchor name to be appended to the path.
- # * <tt>:disabled</tt> - Specifies the anchor name to be appended to the path.
+ # * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
+ # <tt>:delete</tt> and <tt>:put</tt>. By default it will be <tt>:post</tt>.
+ # * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
# * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
# prompt with the question specified. If the user accepts, the link is
# processed normally, otherwise no action is taken.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behaviour. By default this behaviour is an ajax submit.
+ # * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
+ # be placed
#
# ==== Examples
# <%= button_to "New", :action => "new" %>
@@ -284,6 +286,12 @@ module ActionView
# # </form>"
#
#
+ # <%= button_to "New", :action => "new", :form_class => "new-thing" %>
+ # # => "<form method="post" action="/controller/new" class="new-thing">
+ # # <div><input value="New" type="submit" /></div>
+ # # </form>"
+ #
+ #
# <%= button_to "Delete Image", { :action => "delete", :id => @image.id },
# :confirm => "Are you sure?", :method => :delete %>
# # => "<form method="post" action="/images/delete/1" class="button_to">
@@ -313,6 +321,7 @@ module ActionView
end
form_method = method.to_s == 'get' ? 'get' : 'post'
+ form_class = html_options.delete('form_class') || 'button_to'
remote = html_options.delete('remote')
@@ -328,7 +337,7 @@ module ActionView
html_options.merge!("type" => "submit", "value" => name)
- ("<form method=\"#{form_method}\" action=\"#{html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"button_to\"><div>" +
+ ("<form method=\"#{form_method}\" action=\"#{ERB::Util.html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"#{ERB::Util.html_escape(form_class)}\"><div>" +
method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe
end
@@ -367,8 +376,8 @@ module ActionView
# "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' })
+ # 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)
@@ -474,43 +483,41 @@ module ActionView
# :subject => "This is an example email"
# # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
def mail_to(email_address, name = nil, html_options = {})
- email_address = html_escape(email_address)
+ email_address = ERB::Util.html_escape(email_address)
html_options = html_options.stringify_keys
encode = html_options.delete("encode").to_s
- cc, bcc, subject, body = html_options.delete("cc"), html_options.delete("bcc"), html_options.delete("subject"), html_options.delete("body")
- extras = []
- extras << "cc=#{Rack::Utils.escape(cc).gsub("+", "%20")}" unless cc.nil?
- extras << "bcc=#{Rack::Utils.escape(bcc).gsub("+", "%20")}" unless bcc.nil?
- extras << "body=#{Rack::Utils.escape(body).gsub("+", "%20")}" unless body.nil?
- extras << "subject=#{Rack::Utils.escape(subject).gsub("+", "%20")}" unless subject.nil?
- extras = extras.empty? ? '' : '?' + html_escape(extras.join('&'))
+ extras = %w{ cc bcc body subject }.map { |item|
+ option = html_options.delete(item) || next
+ "#{item}=#{Rack::Utils.escape(option).gsub("+", "%20")}"
+ }.compact
+ extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
email_address_obfuscated = email_address.dup
- email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.has_key?("replace_at")
- email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.has_key?("replace_dot")
-
- string = ''
-
- if encode == "javascript"
- "document.write('#{content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))}');".each_byte do |c|
+ email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at")
+ email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot")
+ case encode
+ when "javascript"
+ string = ''
+ html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))
+ html = escape_javascript(html)
+ "document.write('#{html}');".each_byte do |c|
string << sprintf("%%%x", c)
end
"<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>".html_safe
- elsif encode == "hex"
- email_address_encoded = ''
- email_address_obfuscated.each_byte do |c|
- email_address_encoded << sprintf("&#%d;", c)
- end
-
- protocol = 'mailto:'
- protocol.each_byte { |c| string << sprintf("&#%d;", c) }
-
- email_address.each_byte do |c|
+ when "hex"
+ email_address_encoded = email_address_obfuscated.unpack('C*').map {|c|
+ sprintf("&#%d;", c)
+ }.join
+
+ string = 'mailto:'.unpack('C*').map { |c|
+ sprintf("&#%d;", c)
+ }.join + email_address.unpack('C*').map { |c|
char = c.chr
- string << (char =~ /\w/ ? sprintf("%%%x", c) : char)
- end
+ char =~ /\w/ ? sprintf("%%%x", c) : char
+ }.join
+
content_tag "a", name || email_address_encoded.html_safe, html_options.merge("href" => "#{string}#{extras}".html_safe)
else
content_tag "a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)
@@ -586,34 +593,31 @@ module ActionView
private
def convert_options_to_data_attributes(options, html_options)
- html_options = {} if html_options.nil?
- html_options = html_options.stringify_keys
+ if html_options.nil?
+ link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
+ else
+ html_options = html_options.stringify_keys
+ html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
- if (options.is_a?(Hash) && options.key?('remote') && options.delete('remote')) || (html_options.is_a?(Hash) && html_options.key?('remote') && html_options.delete('remote'))
- html_options['data-remote'] = 'true'
- end
+ disable_with = html_options.delete("disable_with")
+ confirm = html_options.delete('confirm')
+ method = html_options.delete('method')
- confirm = html_options.delete("confirm")
+ html_options["data-disable-with"] = disable_with if disable_with
+ html_options["data-confirm"] = confirm if confirm
+ add_method_to_attributes!(html_options, method) if method
- if html_options.key?("popup")
- ActiveSupport::Deprecation.warn(":popup has been deprecated", caller)
+ html_options
end
-
- method, href = html_options.delete("method"), html_options['href']
-
- add_confirm_to_attributes!(html_options, confirm) if confirm
- add_method_to_attributes!(html_options, method) if method
-
- html_options
end
- def add_confirm_to_attributes!(html_options, confirm)
- html_options["data-confirm"] = confirm if confirm
+ def link_to_remote_options?(options)
+ options.is_a?(Hash) && options.key?('remote') && options.delete('remote')
end
def add_method_to_attributes!(html_options, method)
- html_options["rel"] = "nofollow" if method && method.to_s.downcase != "get"
- html_options["data-method"] = method if method
+ html_options["rel"] = "nofollow" if method.to_s.downcase != "get"
+ html_options["data-method"] = method
end
def options_for_javascript(options)
diff --git a/actionpack/lib/action_view/locale/en.yml b/actionpack/lib/action_view/locale/en.yml
index 9004e52c5b..eb816b9446 100644
--- a/actionpack/lib/action_view/locale/en.yml
+++ b/actionpack/lib/action_view/locale/en.yml
@@ -5,7 +5,7 @@
format:
# Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
separator: "."
- # Delimets thousands (e.g. 1,000,000 is a million) (always in groups of three)
+ # 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
diff --git a/actionpack/lib/action_view/log_subscriber.rb b/actionpack/lib/action_view/log_subscriber.rb
index 443a0eafd1..29ffbd6fdd 100644
--- a/actionpack/lib/action_view/log_subscriber.rb
+++ b/actionpack/lib/action_view/log_subscriber.rb
@@ -7,7 +7,7 @@ module ActionView
message = "Rendered #{from_rails_root(event.payload[:identifier])}"
message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
message << (" (%.1fms)" % event.duration)
- info(message)
+ info(message)
end
alias :render_partial :render_template
alias :render_collection :render_template
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
index 3ea8b86af1..06c607931d 100644
--- a/actionpack/lib/action_view/lookup_context.rb
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -10,7 +10,7 @@ module ActionView
# this key is generated just once during the request, it speeds up all cache accesses.
class LookupContext #:nodoc:
mattr_accessor :fallbacks
- @@fallbacks = [FileSystemResolver.new(""), FileSystemResolver.new("/")]
+ @@fallbacks = FallbackFileSystemResolver.instances
mattr_accessor :registered_details
self.registered_details = []
@@ -61,6 +61,7 @@ module ActionView
def initialize(view_paths, details = {})
@details, @details_key = { :handlers => default_handlers }, nil
@frozen_formats, @skip_default_locale = false, false
+ @cache = true
self.view_paths = view_paths
self.registered_detail_setters.each do |key, setter|
@@ -77,17 +78,17 @@ module ActionView
@view_paths = ActionView::Base.process_view_paths(paths)
end
- def find(name, prefix = nil, partial = false)
- @view_paths.find(*args_for_lookup(name, prefix, partial))
+ def find(name, prefixes = [], partial = false, keys = [])
+ @view_paths.find(*args_for_lookup(name, prefixes, partial, keys))
end
alias :find_template :find
- def find_all(name, prefix = nil, partial = false)
- @view_paths.find_all(*args_for_lookup(name, prefix, partial))
+ def find_all(name, prefixes = [], partial = false, keys = [])
+ @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys))
end
- def exists?(name, prefix = nil, partial = false)
- @view_paths.exists?(*args_for_lookup(name, prefix, partial))
+ def exists?(name, prefixes = [], partial = false, keys = [])
+ @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys))
end
alias :template_exists? :exists?
@@ -106,18 +107,26 @@ module ActionView
protected
- def args_for_lookup(name, prefix, partial) #:nodoc:
- name, prefix = normalize_name(name, prefix)
- [name, prefix, partial || false, @details, details_key]
+ def args_for_lookup(name, prefixes, partial, keys) #:nodoc:
+ name, prefixes = normalize_name(name, prefixes)
+ [name, prefixes, partial || false, @details, details_key, keys]
end
# Support legacy foo.erb names even though we now ignore .erb
# as well as incorrectly putting part of the path in the template
# name instead of the prefix.
- def normalize_name(name, prefix) #:nodoc:
+ def normalize_name(name, prefixes) #:nodoc:
name = name.to_s.gsub(handlers_regexp, '')
parts = name.split('/')
- return parts.pop, [prefix, *parts].compact.join("/")
+ name = parts.pop
+
+ prefixes = if prefixes.blank?
+ [parts.join('/')]
+ else
+ prefixes.map { |prefix| [prefix, *parts].compact.join('/') }
+ end
+
+ return name, prefixes
end
def default_handlers #:nodoc:
@@ -130,10 +139,20 @@ module ActionView
end
module Details
+ attr_accessor :cache
+
# Calculate the details key. Remove the handlers from calculation to improve performance
# since the user cannot modify it explicitly.
def details_key #:nodoc:
- @details_key ||= DetailsKey.get(@details)
+ @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
# Freeze the current formats in the lookup context. By freezing them, you are guaranteeing
@@ -145,11 +164,11 @@ module ActionView
@frozen_formats = true
end
- # Overload formats= to reject [:"*/*"] values.
+ # Overload formats= to reject ["*/*"] values.
def formats=(values)
if values && values.size == 1
value = values.first
- values = nil if value == :"*/*"
+ values = nil if value == "*/*"
values << :html if value == :js
end
super(values)
@@ -167,11 +186,11 @@ module ActionView
end
# Overload locale= to also set the I18n.locale. If the current I18n.config object responds
- # to i18n_config, it means that it's has a copy of the original I18n configuration and it's
+ # to original_config, it means that it's has a copy of the original I18n configuration and it's
# acting as proxy, which we need to skip.
def locale=(value)
if value
- config = I18n.config.respond_to?(:i18n_config) ? I18n.config.i18n_config : I18n.config
+ config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
config.locale = value
end
@@ -226,4 +245,4 @@ module ActionView
include Details
include ViewPaths
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/render/partials.rb b/actionpack/lib/action_view/partials.rb
index 459aae94a2..c181689e62 100644
--- a/actionpack/lib/action_view/render/partials.rb
+++ b/actionpack/lib/action_view/partials.rb
@@ -12,19 +12,48 @@ module ActionView
#
# <%= render :partial => "account" %>
#
- # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable
+ # This would render "advertiser/_account.html.erb" and pass the instance variable @account in as a local variable
# +account+ to the template for display.
#
# In another template for Advertiser#buy, we could have:
#
# <%= render :partial => "account", :locals => { :account => @buyer } %>
#
- # <% for ad in @advertisements %>
+ # <% @advertisements.each do |ad| %>
# <%= render :partial => "ad", :locals => { :ad => ad } %>
# <% end %>
#
- # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then
- # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display.
+ # This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then
+ # render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display.
+ #
+ # == The :as and :object options
+ #
+ # By default <tt>ActionView::Partials::PartialRenderer</tt> has its object in a local variable with the same
+ # name as the template. So, given
+ #
+ # <%= render :partial => "contract" %>
+ #
+ # within contract we'll get <tt>@contract</tt> in the local variable +contract+, as if we had written
+ #
+ # <%= render :partial => "contract", :locals => { :contract => @contract } %>
+ #
+ # With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we
+ # wanted it to be +agreement+ instead of +contract+ we'd do:
+ #
+ # <%= render :partial => "contract", :as => 'agreement' %>
+ #
+ # The <tt>:object</tt> option can be used to directly specify which object is rendered into the partial;
+ # useful when the template's object is elsewhere, in a different ivar or in a local variable for instance.
+ #
+ # Revisiting a previous example we could have written this code:
+ #
+ # <%= render :partial => "account", :object => @buyer %>
+ #
+ # <% @advertisements.each do |ad| %>
+ # <%= render :partial => "ad", :object => ad %>
+ # <% end %>
+ #
+ # The <tt>:object</tt> and <tt>:as</tt> options can be used together.
#
# == Rendering a collection of partials
#
@@ -35,10 +64,22 @@ module ActionView
#
# <%= render :partial => "ad", :collection => @advertisements %>
#
- # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An
+ # This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An
# iteration counter will automatically be made available to the template with a name of the form
# +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+.
#
+ # The <tt>:as</tt> option may be used when rendering partials.
+ #
+ # You can specify a partial to be rendered between elements via the <tt>:spacer_template</tt> option.
+ # The following example will render <tt>advertiser/_ad_divider.html.erb</tt> between each ad partial:
+ #
+ # <%= 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.
#
@@ -48,7 +89,7 @@ module ActionView
#
# <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %>
#
- # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from.
+ # This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from.
#
# == Rendering objects with the RecordIdentifier
#
@@ -56,7 +97,7 @@ module ActionView
# you're following its conventions for RecordIdentifier#partial_path. Examples:
#
# # @account is an Account instance, so it uses the RecordIdentifier to replace
- # # <%= render :partial => "accounts/account", :locals => { :account => @buyer } %>
+ # # <%= render :partial => "accounts/account", :locals => { :account => @account} %>
# <%= render :partial => @account %>
#
# # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
@@ -174,165 +215,12 @@ module ActionView
# <%- end -%>
# <% end %>
module Partials
- extend ActiveSupport::Concern
-
- class PartialRenderer
- PARTIAL_NAMES = Hash.new {|h,k| h[k] = {} }
-
- def initialize(view_context, options, block)
- @view = view_context
- @partial_names = PARTIAL_NAMES[@view.controller.class.name]
-
- setup(options, block)
- end
-
- def setup(options, block)
- partial = options[:partial]
-
- @options = options
- @locals = options[:locals] || {}
- @block = block
-
- if String === partial
- @object = options[:object]
- @path = partial
- @collection = collection
- else
- @object = partial
-
- if @collection = collection
- paths = @collection_paths = @collection.map { |o| partial_path(o) }
- @path = paths.uniq.size == 1 ? paths.first : nil
- else
- @path = partial_path
- end
- end
- end
-
- def render
- identifier = ((@template = find_template) ? @template.identifier : @path)
-
- if @collection
- ActiveSupport::Notifications.instrument("render_collection.action_view",
- :identifier => identifier || "collection", :count => @collection.size) do
- render_collection
- end
- else
- content = ActiveSupport::Notifications.instrument("render_partial.action_view",
- :identifier => identifier) do
- render_partial
- end
-
- if !@block && (layout = @options[:layout])
- content = @view._render_layout(find_template(layout), @locals){ content }
- end
-
- content
- end
- end
-
- def render_collection
- return nil if @collection.blank?
-
- if @options.key?(:spacer_template)
- spacer = find_template(@options[:spacer_template]).render(@view, @locals)
- end
-
- result = @template ? collection_with_template : collection_without_template
- result.join(spacer).html_safe
- end
-
- def collection_with_template(template = @template)
- segments, locals, template = [], @locals, @template
-
- if @options[:as]
- as = @options[:as]
- counter = "#{as}_counter".to_sym
- else
- as = template.variable_name
- counter = template.counter_name
- end
-
- locals[counter] = -1
-
- @collection.each do |object|
- locals[counter] += 1
- locals[as] = object
- segments << template.render(@view, locals)
- end
-
- segments
- end
-
- def collection_without_template(collection_paths = @collection_paths)
- segments, locals = [], @locals
- index, template = -1, nil
-
- if @options[:as]
- as = @options[:as]
- counter = "#{as}_counter"
- end
-
- @collection.each_with_index do |object, i|
- template = find_template(collection_paths[i])
- locals[as || template.variable_name] = object
- locals[counter || template.counter_name] = (index += 1)
-
- segments << template.render(@view, locals)
- end
-
- @template = template
- segments
- end
-
- def render_partial(object = @object)
- locals, view, template = @locals, @view, @template
-
- object ||= locals[template.variable_name]
- locals[@options[:as] || template.variable_name] = object
-
- template.render(view, locals) do |*name|
- view._layout_for(*name, &@block)
- end
- end
-
- private
-
- def collection
- if @object.respond_to?(:to_ary)
- @object
- elsif @options.key?(:collection)
- @options[:collection] || []
- end
- end
-
- def find_template(path=@path)
- return path unless path.is_a?(String)
- prefix = @view.controller_path unless path.include?(?/)
- @view.find_template(path, prefix, true)
- end
-
- def partial_path(object = @object)
- @partial_names[object.class.name] ||= begin
- object = object.to_model if object.respond_to?(:to_model)
-
- object.class.model_name.partial_path.dup.tap do |partial|
- path = @view.controller_path
- partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/)
- end
- end
- end
- end
-
def _render_partial(options, &block) #:nodoc:
- if defined?(@renderer)
- @renderer.setup(options, block)
- else
- @renderer = PartialRenderer.new(self, options, block)
- end
-
- @renderer.render
+ _partial_renderer.setup(options, block).render
end
+ def _partial_renderer #:nodoc:
+ @_partial_renderer ||= PartialRenderer.new(self)
+ end
end
end
diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/path_set.rb
index 9857d688d2..e3de3e1eac 100644
--- a/actionpack/lib/action_view/paths.rb
+++ b/actionpack/lib/action_view/path_set.rb
@@ -10,16 +10,16 @@ module ActionView #:nodoc:
METHOD
end
- def find(path, prefix = nil, partial = false, details = {}, key = nil)
- template = find_all(path, prefix, partial, details, key).first
- raise MissingTemplate.new(self, "#{prefix}/#{path}", details, partial) unless template
- template
+ def find(*args)
+ find_all(*args).first || raise(MissingTemplate.new(self, *args))
end
- def find_all(*args)
- each do |resolver|
- templates = resolver.find_all(*args)
- return templates unless templates.empty?
+ def find_all(path, prefixes = [], *args)
+ prefixes.each do |prefix|
+ each do |resolver|
+ templates = resolver.find_all(path, prefix, *args)
+ return templates unless templates.empty?
+ end
end
[]
end
diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb
index 33dfcbb803..501ec07b09 100644
--- a/actionpack/lib/action_view/railtie.rb
+++ b/actionpack/lib/action_view/railtie.rb
@@ -8,10 +8,10 @@ module ActionView
config.action_view.stylesheet_expansions = {}
config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] }
- initializer "action_view.cache_asset_timestamps" do |app|
+ initializer "action_view.cache_asset_ids" do |app|
unless app.config.cache_classes
ActiveSupport.on_load(:action_view) do
- ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
+ ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
end
end
end
@@ -35,5 +35,13 @@ module ActionView
end
end
end
+
+ initializer "action_view.caching" do |app|
+ ActiveSupport.on_load(:action_view) do
+ if app.config.action_view.cache_template_loading.nil?
+ ActionView::Resolver.caching = app.config.cache_classes
+ end
+ end
+ end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/render/layouts.rb b/actionpack/lib/action_view/render/layouts.rb
deleted file mode 100644
index a474783a20..0000000000
--- a/actionpack/lib/action_view/render/layouts.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-module ActionView
- # = Action View Layouts
- module Layouts
- # 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(name = nil, &block) #:nodoc:
- if !block || name
- @_content_for[name || :layout].html_safe
- else
- capture(&block)
- 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)
- begin
- with_layout_format do
- layout =~ /^\// ?
- with_fallbacks { find_template(layout) } : find_template(layout)
- end
- rescue ActionView::MissingTemplate => e
- update_details(:formats => nil) do
- raise unless template_exists?(layout)
- end
- end
- end
-
- # Contains the logic that actually renders the layout.
- def _render_layout(layout, locals, &block) #:nodoc:
- layout.render(self, locals){ |*name| _layout_for(*name, &block) }
- end
- end
-end
diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb
deleted file mode 100644
index 5320245173..0000000000
--- a/actionpack/lib/action_view/render/rendering.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-require 'active_support/core_ext/object/try'
-
-module ActionView
- # = Action View Rendering
- module Rendering
- # Returns the result of a render that's dictated by the options hash. The primary options are:
- #
- # * <tt>:partial</tt> - See ActionView::Partials.
- # * <tt>:update</tt> - Calls update_page with the block given.
- # * <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?
- _render_partial(options.merge(:partial => options[:layout]), &block)
- elsif options.key?(:partial)
- _render_partial(options)
- else
- template = _determine_template(options)
- lookup_context.freeze_formats(template.formats, true)
- _render_template(template, options[:layout], options)
- end
- when :update
- update_page(&block)
- else
- _render_partial(:partial => options, :locals => locals)
- end
- end
-
- # Determine the template to be rendered using the given options.
- def _determine_template(options) #:nodoc:
- if options.key?(:inline)
- handler = Template.handler_class_for_extension(options[:type] || "erb")
- Template.new(options[:inline], "inline template", handler, {})
- elsif options.key?(:text)
- Template::Text.new(options[:text], formats.try(:first))
- elsif options.key?(:file)
- with_fallbacks { find_template(options[:file], options[:prefix]) }
- elsif options.key?(:template)
- options[:template].respond_to?(:render) ?
- options[:template] : find_template(options[:template], options[:prefix])
- end
- end
-
- # Renders the given template. An string representing the layout can be
- # supplied as well.
- def _render_template(template, layout = nil, options = {}) #:nodoc:
- locals = options[:locals] || {}
- layout = find_layout(layout) if layout
-
- ActiveSupport::Notifications.instrument("render_template.action_view",
- :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
-
- content = template.render(self, locals) { |*name| _layout_for(*name) }
- @_content_for[:layout] = content if layout
-
- content = _render_layout(layout, locals) if layout
- content
- end
- 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 0000000000..4a52b3172e
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/abstract_renderer.rb
@@ -0,0 +1,37 @@
+module ActionView
+ class AbstractRenderer #:nodoc:
+ delegate :find_template, :template_exists?, :with_fallbacks, :update_details,
+ :with_layout_format, :formats, :freeze_formats, :to => :@lookup_context
+
+ def initialize(view)
+ @view = view
+ @lookup_context = view.lookup_context
+ end
+
+ def render
+ raise NotImplementedError
+ end
+
+ # Checks if the given path contains a format and if so, change
+ # the lookup context to take this new format into account.
+ def wrap_formats(value)
+ return yield unless value.is_a?(String)
+
+ if value.sub!(formats_regexp, "")
+ update_details(:formats => [$1.to_sym]){ yield }
+ else
+ yield
+ end
+ end
+
+ def formats_regexp
+ @@formats_regexp ||= /\.(#{Mime::SET.symbols.join('|')})$/
+ end
+
+ protected
+
+ def instrument(name, options={})
+ ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
+ 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 0000000000..94c0a8a8fb
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -0,0 +1,167 @@
+require 'action_view/renderer/abstract_renderer'
+
+module ActionView
+ class PartialRenderer < AbstractRenderer #:nodoc:
+ PARTIAL_NAMES = Hash.new {|h,k| h[k] = {} }
+
+ def initialize(view)
+ super
+ @partial_names = PARTIAL_NAMES[@view.controller.class.name]
+ end
+
+ def setup(options, block)
+ partial = options[:partial]
+
+ @options = options
+ @locals = options[:locals] || {}
+ @block = block
+
+ 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 @path
+ @variable, @variable_counter = retrieve_variable(@path)
+ else
+ paths.map! { |path| retrieve_variable(path).unshift(path) }
+ end
+
+ self
+ end
+
+ def render
+ wrap_formats(@path) do
+ identifier = ((@template = find_partial) ? @template.identifier : @path)
+
+ if @collection
+ instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do
+ render_collection
+ end
+ else
+ instrument(:partial, :identifier => identifier) do
+ render_partial
+ end
+ end
+ end
+ end
+
+ def render_collection
+ return nil if @collection.blank?
+
+ if @options.key?(:spacer_template)
+ spacer = find_template(@options[:spacer_template]).render(@view, @locals)
+ end
+
+ result = @template ? collection_with_template : collection_without_template
+ result.join(spacer).html_safe
+ end
+
+ def render_partial
+ locals, view, block = @locals, @view, @block
+ object, as = @object, @variable
+
+ if !block && (layout = @options[:layout])
+ layout = find_template(layout)
+ 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
+
+ def collection
+ if @options.key?(:collection)
+ collection = @options[:collection]
+ collection.respond_to?(:to_ary) ? collection.to_ary : []
+ end
+ end
+
+ def collection_from_object
+ if @object.respond_to?(:to_ary)
+ @object.to_ary
+ end
+ end
+
+ def find_partial
+ if path = @path
+ locals = @locals.keys
+ locals << @variable
+ locals << @variable_counter if @collection
+ find_template(path, locals)
+ end
+ end
+
+ def find_template(path=@path, locals=@locals.keys)
+ prefixes = path.include?(?/) ? [] : @view.controller_prefixes
+ @lookup_context.find_template(path, prefixes, true, locals)
+ end
+
+ def collection_with_template
+ segments, locals, template = [], @locals, @template
+ as, counter = @variable, @variable_counter
+
+ locals[counter] = -1
+
+ @collection.each do |object|
+ locals[counter] += 1
+ locals[as] = object
+ segments << template.render(@view, locals)
+ end
+
+ segments
+ end
+
+ def collection_without_template
+ segments, locals, collection_data = [], @locals, @collection_data
+ index, template, cache = -1, nil, {}
+ keys = @locals.keys
+
+ @collection.each_with_index do |object, i|
+ path, *data = collection_data[i]
+ template = (cache[path] ||= find_template(path, keys + data))
+ locals[data[0]] = object
+ locals[data[1]] = (index += 1)
+ segments << template.render(@view, locals)
+ end
+
+ @template = template
+ segments
+ end
+
+ def partial_path(object = @object)
+ @partial_names[object.class.name] ||= begin
+ object = object.to_model if object.respond_to?(:to_model)
+
+ object.class.model_name.partial_path.dup.tap do |partial|
+ path = @view.controller_prefixes.first
+ partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/)
+ end
+ end
+ end
+
+ def retrieve_variable(path)
+ variable = @options[:as].try(:to_sym) || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym
+ variable_counter = :"#{variable}_counter" if @collection
+ [variable, variable_counter]
+ 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 0000000000..9ae1636131
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -0,0 +1,98 @@
+require 'set'
+require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/array/wrap'
+require 'action_view/renderer/abstract_renderer'
+
+module ActionView
+ class TemplateRenderer < AbstractRenderer #:nodoc:
+ attr_reader :rendered
+
+ def initialize(view)
+ super
+ @rendered = Set.new
+ end
+
+ def render(options)
+ wrap_formats(options[:template] || options[:file]) do
+ template = determine_template(options)
+ render_template(template, options[:layout], options[:locals])
+ end
+ end
+
+ def render_once(options)
+ paths, locals = options[:once], options[:locals] || {}
+ layout, keys = options[:layout], locals.keys
+ prefixes = options.fetch(:prefixes, @view.controller_prefixes)
+
+ raise "render :once expects a String or an Array to be given" unless paths
+
+ render_with_layout(layout, locals) do
+ contents = []
+ Array.wrap(paths).each do |path|
+ template = find_template(path, prefixes, false, keys)
+ contents << render_template(template, nil, locals) if @rendered.add?(template)
+ end
+ contents.join("\n")
+ end
+ end
+
+ # Determine the template to be rendered using the given options.
+ def determine_template(options) #:nodoc:
+ keys = options[:locals].try(:keys) || []
+
+ if options.key?(:text)
+ Template::Text.new(options[:text], formats.try(:first))
+ elsif options.key?(:file)
+ with_fallbacks { find_template(options[:file], options[:prefixes], false, keys) }
+ elsif options.key?(:inline)
+ handler = Template.handler_for_extension(options[:type] || "erb")
+ Template.new(options[:inline], "inline template", handler, :locals => keys)
+ elsif options.key?(:template)
+ options[:template].respond_to?(:render) ?
+ options[:template] : find_template(options[:template], options[:prefixes], false, keys)
+ end
+ end
+
+ # Renders the given template. An string representing the layout can be
+ # supplied as well.
+ def render_template(template, layout_name = nil, locals = {}) #:nodoc:
+ freeze_formats(template.formats, true)
+ 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.store_content_for(: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)
+ begin
+ with_layout_format do
+ layout =~ /^\// ?
+ with_fallbacks { find_template(layout, nil, false, keys) } : find_template(layout, nil, false, keys)
+ end
+ rescue ActionView::MissingTemplate => e
+ update_details(:formats => nil) do
+ raise unless template_exists?(layout)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/rendering.rb b/actionpack/lib/action_view/rendering.rb
new file mode 100644
index 0000000000..baa5d2c3fd
--- /dev/null
+++ b/actionpack/lib/action_view/rendering.rb
@@ -0,0 +1,106 @@
+require 'active_support/core_ext/object/try'
+
+module ActionView
+ # = Action View Rendering
+ module Rendering
+ # Returns the result of a render that's dictated by the options hash. The primary options are:
+ #
+ # * <tt>:partial</tt> - See ActionView::Partials.
+ # * <tt>:update</tt> - Calls update_page with the block given.
+ # * <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.
+ # * <tt>:once</tt> - Accepts a string or an array of strings and Rails will ensure they each of them are rendered just once.
+ #
+ # 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?
+ _render_partial(options.merge(:partial => options[:layout]), &block)
+ elsif options.key?(:partial)
+ _render_partial(options)
+ elsif options.key?(:once)
+ _render_once(options)
+ else
+ _render_template(options)
+ end
+ when :update
+ update_page(&block)
+ else
+ _render_partial(:partial => options, :locals => locals)
+ end
+ end
+
+ # 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 name.is_a?(Symbol)
+ @_content_for[name].html_safe
+ elsif block
+ capture(*args, &block)
+ else
+ @_content_for[:layout].html_safe
+ end
+ end
+
+ def _render_once(options) #:nodoc:
+ _template_renderer.render_once(options)
+ end
+
+ def _render_template(options) #:nodoc:
+ _template_renderer.render(options)
+ end
+
+ def _template_renderer #:nodoc:
+ @_template_renderer ||= TemplateRenderer.new(self)
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index 40ff1f2182..96d506fac5 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/object/try'
require 'active_support/core_ext/kernel/singleton_class'
module ActionView
@@ -97,9 +98,12 @@ module ActionView
extend Template::Handlers
- attr_reader :source, :identifier, :handler, :virtual_path, :formats,
- :original_encoding
+ 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
@@ -109,50 +113,80 @@ module ActionView
end
def initialize(source, identifier, handler, details)
- @source = source
- @identifier = identifier
- @handler = handler
- @original_encoding = nil
-
- @virtual_path = details[:virtual_path]
- @method_names = {}
+ format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
- format = details[:format] || :html
- @formats = Array.wrap(format).map(&:to_sym)
+ @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.wrap(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f }
end
+ # Render a template. If the template was not compiled yet, it is done
+ # 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, &block)
- # 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.
+ old_template, view._template = view._template, self
ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path) do
- if view.is_a?(ActionView::CompiledTemplates)
- mod = ActionView::CompiledTemplates
- else
- mod = view.singleton_class
- end
-
- method_name = compile(locals, view, mod)
+ compile!(view)
view.send(method_name, locals, &block)
end
rescue Exception => e
- if e.is_a?(Template::Error)
- e.sub_template_of(self)
- raise e
- else
- raise Template::Error.new(self, view.respond_to?(:assigns) ? view.assigns : {}, e)
- end
+ handle_render_error(view, e)
+ ensure
+ view._template = old_template
end
def mime_type
@mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first
end
- def variable_name
- @variable_name ||= @virtual_path[%r'_?(\w+)(\.\w+)*$', 1].to_sym
+ # 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
+
+ # Expires this template by setting his updated_at date to Jan 1st, 1970.
+ def expire!
+ @updated_at = Time.utc(1970)
+ end
+
+ # Receives a view context and renders a template exactly like self by using
+ # the @virtual_path. It raises an error if no @virtual_path was given.
+ def rerender(view)
+ raise "A template needs to have a virtual path in order to be rerendered" unless @virtual_path
+ name = @virtual_path.dup
+ if name.sub!(/(^|\/)_([^\/]*)$/, '\1\2')
+ view.render :partial => name
+ else
+ view.render :template => @virtual_path
+ end
end
- def counter_name
- @counter_name ||= "#{variable_name}_counter".to_sym
+ # Used to store template data by template handlers.
+ def data
+ @data ||= {}
end
def inspect
@@ -164,7 +198,27 @@ module ActionView
end
end
- private
+ 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
+
+ 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
+
# Among other things, 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,
@@ -185,11 +239,8 @@ module ActionView
# encode the source into Encoding.default_internal. In general,
# this means that templates will be UTF-8 inside of Rails,
# regardless of the original source encoding.
- def compile(locals, view, mod)
- method_name = build_method_name(locals)
- return method_name if view.respond_to?(method_name)
-
- locals_code = locals.keys.map! { |key| "#{key} = local_assigns[:#{key}];" }.join
+ def compile(view, mod) #:nodoc:
+ method_name = self.method_name
if source.encoding_aware?
# Look for # encoding: *. If we find one, we'll encode the
@@ -223,15 +274,16 @@ module ActionView
end
end
- code = @handler.call(self)
+ arity = @handler.respond_to?(:arity) ? @handler.arity : @handler.method(:call).arity
+ code = arity.abs == 1 ? @handler.call(self) : @handler.call(self, view)
# Make sure that the resulting String to be evalled is in the
# encoding of the code
source = <<-end_src
def #{method_name}(local_assigns)
- _old_virtual_path, @_virtual_path = @_virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
+ _old_output_buffer = @output_buffer;#{locals_code};#{code}
ensure
- @_virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
+ @output_buffer = _old_output_buffer
end
end_src
@@ -254,8 +306,6 @@ module ActionView
begin
mod.module_eval(source, identifier, 0)
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
-
- method_name
rescue Exception => e # errors from template code
if logger = (view && view.logger)
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
@@ -267,12 +317,27 @@ module ActionView
end
end
- def build_method_name(locals)
- @method_names[locals.keys.hash] ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}_#{locals.keys.hash}".gsub('-', "_")
+ def handle_render_error(view, e) #:nodoc:
+ if e.is_a?(Template::Error)
+ e.sub_template_of(self)
+ raise e
+ else
+ assigns = view.respond_to?(:assigns) ? view.assigns : {}
+ template = @virtual_path ? refresh(view) : self
+ raise Template::Error.new(template, assigns, e)
+ end
+ end
+
+ def locals_code #:nodoc:
+ @locals.map { |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
- @identifier_method_name ||= inspect.gsub(/[^a-z_]/, '_')
+ 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
index b1839b65e5..e246646963 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -27,7 +27,7 @@ module ActionView
class MissingTemplate < ActionViewError #:nodoc:
attr_reader :path
- def initialize(paths, path, details, partial)
+ def initialize(paths, path, prefixes, partial, details, *)
@path = path
display_paths = paths.compact.map{ |p| p.to_s.inspect }.join(", ")
template_type = if partial
@@ -38,20 +38,27 @@ module ActionView
'template'
end
- super("Missing #{template_type} #{path} with #{details.inspect} in view paths #{display_paths}")
+ searched_paths = prefixes.map { |prefix| [prefix, path].join("/") }
+
+ out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n"
+ out += paths.compact.map { |p| " * #{p.to_s.inspect}\n" }.join
+ super out
end
end
class Template
- # The Template::Error exception is raised when the compilation of the template fails. This exception then gathers a
- # bunch of intimate details and uses it to report a very precise exception message.
+ # 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, assigns, original_exception)
+ super(original_exception.message)
@template, @assigns, @original_exception = template, assigns.dup, original_exception
+ @sub_templates = nil
@backtrace = original_exception.backtrace
end
@@ -59,10 +66,6 @@ module ActionView
@template.identifier
end
- def message
- ActiveSupport::Deprecation.silence { original_exception.message }
- end
-
def sub_template_message
if @sub_templates
"Trace of template inclusion: " +
diff --git a/actionpack/lib/action_view/template/handler.rb b/actionpack/lib/action_view/template/handler.rb
index 8ecc911519..636f3ebbad 100644
--- a/actionpack/lib/action_view/template/handler.rb
+++ b/actionpack/lib/action_view/template/handler.rb
@@ -1,4 +1,4 @@
-require "action_dispatch/http/mime_type"
+require 'action_dispatch/http/mime_type'
require 'active_support/core_ext/class/attribute'
# Legacy TemplateHandler stub
@@ -7,6 +7,8 @@ module ActionView
module Handlers #:nodoc:
module Compilable
def self.included(base)
+ ActiveSupport::Deprecation.warn "Including Compilable in your template handler is deprecated. " <<
+ "Since Rails 3, all the API your template handler needs to implement is to respond to #call."
base.extend(ClassMethods)
end
@@ -26,6 +28,12 @@ module ActionView
class_attribute :default_format
self.default_format = Mime::HTML
+ def self.inherited(base)
+ ActiveSupport::Deprecation.warn "Inheriting from ActionView::Template::Handler is deprecated. " <<
+ "Since Rails 3, all the API your template handler needs to implement is to respond to #call."
+ super
+ end
+
def self.call(template)
raise "Need to implement #{self.class.name}#call(template)"
end
@@ -35,7 +43,7 @@ module ActionView
end
end
end
-
+
TemplateHandlers = Template::Handlers
TemplateHandler = Template::Handler
end
diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb
index 84d6474dd1..4438199497 100644
--- a/actionpack/lib/action_view/template/handlers.rb
+++ b/actionpack/lib/action_view/template/handlers.rb
@@ -7,18 +7,14 @@ module ActionView #:nodoc:
autoload :Builder, 'action_view/template/handlers/builder'
def self.extended(base)
- base.register_default_template_handler :erb, ERB
- base.register_template_handler :rjs, RJS
- base.register_template_handler :builder, Builder
-
- # TODO: Depreciate old template extensions
- base.register_template_handler :rhtml, ERB
- base.register_template_handler :rxml, Builder
+ base.register_default_template_handler :erb, ERB.new
+ base.register_template_handler :rjs, RJS.new
+ base.register_template_handler :builder, Builder.new
end
@@template_handlers = {}
@@default_template_handlers = nil
-
+
def self.extensions
@@template_extensions ||= @@template_handlers.keys
end
@@ -48,7 +44,13 @@ module ActionView #:nodoc:
end
def handler_class_for_extension(extension)
- (extension && registered_template_handler(extension.to_sym)) || @@default_template_handlers
+ ActiveSupport::Deprecation.warn "handler_class_for_extension is deprecated. " <<
+ "Please use handler_for_extension instead", caller
+ handler_for_extension(extension)
+ end
+
+ def handler_for_extension(extension)
+ registered_template_handler(extension) || @@default_template_handlers
end
end
end
diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb
index a93cfca8aa..2c52cfd90e 100644
--- a/actionpack/lib/action_view/template/handlers/builder.rb
+++ b/actionpack/lib/action_view/template/handlers/builder.rb
@@ -1,11 +1,11 @@
module ActionView
module Template::Handlers
- class Builder < Template::Handler
- include Compilable
-
+ class Builder
+ # Default format used by Builder.
+ class_attribute :default_format
self.default_format = Mime::XML
- def compile(template)
+ def call(template)
require 'builder'
"xml = ::Builder::XmlMarkup.new(:indent => 2);" +
"self.output_buffer = xml.target!;" +
diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb
index ce609e01af..a36837afc8 100644
--- a/actionpack/lib/action_view/template/handlers/erb.rb
+++ b/actionpack/lib/action_view/template/handlers/erb.rb
@@ -1,6 +1,7 @@
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/string/output_safety'
-require "action_view/template"
+require 'action_view/template'
+require 'action_view/template/handler'
require 'erubis'
module ActionView
@@ -14,13 +15,7 @@ module ActionView
super(value.to_s)
end
alias :append= :<<
-
- def append_if_string=(value)
- if value.is_a?(String) && !value.is_a?(NonConcattingString)
- ActiveSupport::Deprecation.warn("<% %> style block helpers are deprecated. Please use <%= %>", caller)
- self << value
- end
- end
+ alias :safe_append= :safe_concat
end
class Template
@@ -45,45 +40,44 @@ module ActionView
end
end
- def add_stmt(src, code)
+ def add_expr_escaped(src, code)
if code =~ BLOCK_EXPR
- src << '@output_buffer.append_if_string= ' << code
+ src << "@output_buffer.safe_append= " << code
else
- super
+ src << "@output_buffer.safe_concat((" << code << ").to_s);"
end
end
- def add_expr_escaped(src, code)
- src << '@output_buffer.append= ' << escaped_expr(code) << ';'
- end
-
def add_postamble(src)
src << '@output_buffer.to_s'
end
end
- class ERB < Handler
- include Compilable
-
- ##
- # :singleton-method:
+ class ERB
# Specify trim mode for the ERB compiler. Defaults to '-'.
# See ERb documentation for suitable values.
- cattr_accessor :erb_trim_mode
+ class_attribute :erb_trim_mode
self.erb_trim_mode = '-'
+ # Default format used by ERB.
+ class_attribute :default_format
self.default_format = Mime::HTML
- cattr_accessor :erb_implementation
+ # Default implementation used.
+ class_attribute :erb_implementation
self.erb_implementation = Erubis
ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
- def self.handles_encoding?
+ def self.call(template)
+ new.call(template)
+ end
+
+ def handles_encoding?
true
end
- def compile(template)
+ def call(template)
if template.source.encoding_aware?
# First, convert to BINARY, so in case the encoding is
# wrong, we can still find an encoding tag
@@ -109,6 +103,7 @@ module ActionView
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
diff --git a/actionpack/lib/action_view/template/handlers/rjs.rb b/actionpack/lib/action_view/template/handlers/rjs.rb
index 128be5077c..9d71059134 100644
--- a/actionpack/lib/action_view/template/handlers/rjs.rb
+++ b/actionpack/lib/action_view/template/handlers/rjs.rb
@@ -1,17 +1,13 @@
module ActionView
module Template::Handlers
- class RJS < Template::Handler
- include Compilable
-
+ class RJS
+ # Default format used by RJS.
+ class_attribute :default_format
self.default_format = Mime::JS
- def compile(template)
+ def call(template)
"update_page do |page|;#{template.source}\nend"
end
-
- def default_format
- Mime::JS
- end
end
end
end
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
index c9e20ca14e..6c1063592f 100644
--- a/actionpack/lib/action_view/template/resolver.rb
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -5,9 +5,35 @@ require "action_view/template"
module ActionView
# = Action View Resolver
class Resolver
+ # Keeps all information about view path and builds virtual path.
+ class Path < String
+ attr_reader :name, :prefix, :partial, :virtual
+ alias_method :partial?, :partial
+
+ def initialize(name, prefix, partial)
+ @name, @prefix, @partial = name, prefix, partial
+ rebuild(@name, @prefix, @partial)
+ end
+
+ def rebuild(name, prefix, partial)
+ @virtual = ""
+ @virtual << "#{prefix}/" unless prefix.empty?
+ @virtual << (partial ? "_#{name}" : name)
+
+ self.replace(@virtual)
+ end
+ end
+
+ cattr_accessor :caching
+ self.caching = true
+
+ class << self
+ alias :caching? :caching
+ end
+
def initialize
- @cached = Hash.new { |h1,k1| h1[k1] =
- Hash.new { |h2,k2| h2[k2] = Hash.new { |h3, k3| h3[k3] = {} } } }
+ @cached = Hash.new { |h1,k1| h1[k1] = Hash.new { |h2,k2|
+ h2[k2] = Hash.new { |h3,k3| h3[k3] = Hash.new { |h4,k4| h4[k4] = {} } } } }
end
def clear_cache
@@ -15,68 +41,131 @@ module ActionView
end
# Normalizes the arguments and passes it on to find_template.
- def find_all(name, prefix=nil, partial=false, details={}, key=nil)
- cached(key, prefix, name, partial) do
+ 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
- def caching?
- @caching ||= !defined?(Rails.application) || Rails.application.config.cache_classes
- end
+ delegate :caching?, :to => "self.class"
# This is what child classes implement. No defaults are needed
# because Resolver guarantees that the arguments are present and
# normalized.
def find_templates(name, prefix, partial, details)
- raise NotImplementedError
+ raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details) method"
end
- def cached(key, prefix, name, partial)
- return yield unless key && caching?
- @cached[key][prefix][name][partial] ||= yield
+ # Helpers that builds a path. Useful for building virtual paths.
+ def build_path(name, prefix, partial)
+ Path.new(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 check if the resolver is fresher
+ # before returning it.
+ def cached(key, path_info, details, locals) #:nodoc:
+ name, prefix, partial = path_info
+ locals = sort_locals(locals)
+
+ if key && caching?
+ @cached[key][name][prefix][partial][locals] ||= decorate(yield, path_info, details, locals)
+ else
+ fresh = decorate(yield, path_info, details, locals)
+ return fresh unless key
+
+ scope = @cached[key][name][prefix][partial]
+ cache = scope[locals]
+ mtime = cache && cache.map(&:updated_at).max
+
+ if !mtime || fresh.empty? || fresh.any? { |t| t.updated_at > mtime }
+ scope[locals] = fresh
+ else
+ cache
+ end
+ 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
+
+ if :symbol.respond_to?("<=>")
+ def sort_locals(locals) #:nodoc:
+ locals.sort.freeze
+ end
+ else
+ def sort_locals(locals) #:nodoc:
+ locals = locals.map{ |l| l.to_s }
+ locals.sort!
+ locals.freeze
+ end
end
end
class PathResolver < Resolver
- EXTENSION_ORDER = [:locale, :formats, :handlers]
+ EXTENSIONS = [:locale, :formats, :handlers]
+ DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}"
- def to_s
- @path.to_s
+ def initialize(pattern=nil)
+ @pattern = pattern || DEFAULT_PATTERN
+ super()
end
- alias :to_path :to_s
- private
+ private
def find_templates(name, prefix, partial, details)
- path = build_path(name, prefix, partial, details)
- query(path, EXTENSION_ORDER.map { |ext| details[ext] }, details[:formats])
- end
-
- def build_path(name, prefix, partial, details)
- path = ""
- path << "#{prefix}/" unless prefix.empty?
- path << (partial ? "_#{name}" : name)
- path
+ path = build_path(name, prefix, partial)
+ extensions = Hash[EXTENSIONS.map { |ext| [ext, details[ext]] }.flatten(0)]
+ query(path, extensions, details[:formats])
end
def query(path, exts, formats)
- query = File.join(@path, path)
+ query = build_query(path, exts)
+ templates = []
+ sanitizer = Hash.new { |h,k| h[k] = Dir["#{File.dirname(k)}/*"] }
- exts.each do |ext|
- query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << ',}'
- end
+ Dir[query].each do |p|
+ next if File.directory?(p) || !sanitizer[p].include?(p)
- Dir[query].reject { |p| File.directory?(p) }.map do |p|
handler, format = extract_handler_and_format(p, formats)
-
contents = File.open(p, "rb") {|io| io.read }
- Template.new(contents, File.expand_path(p), handler,
- :virtual_path => path, :format => format)
+ templates << Template.new(contents, File.expand_path(p), handler,
+ :virtual_path => path.virtual, :format => format, :updated_at => mtime(p))
end
+
+ templates
+ end
+
+ # Helper for building query glob string based on resolver's pattern.
+ def build_query(path, exts)
+ query = @pattern.dup
+ query.gsub!(/\:prefix(\/)?/, path.prefix.empty? ? "" : "#{path.prefix}\\1") # prefix can be empty...
+ query.gsub!(/\:action/, path.partial? ? "_#{path.name}" : path.name)
+
+ exts.each { |ext, variants|
+ query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
+ }
+
+ query.gsub!(/\.{html,/, ".{html,text.html,")
+ query.gsub!(/\.{text,/, ".{text,text.plain,")
+
+ File.expand_path(query, @path)
+ end
+
+ # Returns the file mtime from the filesystem.
+ def mtime(p)
+ File.stat(p).mtime
end
# Extract handler and formats from path. If a format cannot be a found neither
@@ -85,26 +174,76 @@ module ActionView
def extract_handler_and_format(path, default_formats)
pieces = File.basename(path).split(".")
pieces.shift
-
- handler = Template.handler_class_for_extension(pieces.pop)
- format = pieces.last && Mime[pieces.last] && pieces.pop.to_sym
- format ||= handler.default_format if handler.respond_to?(:default_format)
- format ||= default_formats
-
+ handler = Template.handler_for_extension(pieces.pop)
+ format = pieces.last && Mime[pieces.last]
[handler, format]
end
end
+ # A resolver that loads files from the filesystem. It allows to set 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,rjs},}`
+ #
+ # FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}")
+ #
+ # This one allows you to keep files with different formats in seperated 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 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 have to be a valid glob string, and it allows you to use the
+ # following variables:
+ #
+ # * <tt>:prefix</tt> - usualy 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)
+ def initialize(path, pattern=nil)
raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver)
- super()
+ 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
+
+ # The same as FileSystemResolver but does not allow templates to store
+ # a virtual path since it is invalid for such resolvers.
+ class FallbackFileSystemResolver < FileSystemResolver
+ 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
index 51be831dfb..4261c3b5e2 100644
--- a/actionpack/lib/action_view/template/text.rb
+++ b/actionpack/lib/action_view/template/text.rb
@@ -25,10 +25,6 @@ module ActionView #:nodoc:
def formats
[@mime_type.to_sym]
end
-
- def partial?
- false
- end
end
end
end
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index 137281e5e9..3e2ddffa16 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -20,12 +20,12 @@ module ActionView
end
def initialize
+ super
self.class.controller_path = ""
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.env.delete('PATH_INFO')
-
@params = {}
end
end
@@ -44,7 +44,7 @@ module ActionView
include ActionView::Helpers
attr_accessor :controller, :output_buffer, :rendered
-
+
module ClassMethods
def tests(helper_class)
self.helper_class = helper_class
@@ -74,6 +74,11 @@ module ActionView
@helper_class ||= determine_default_helper_class(name)
end
+ def new(*)
+ include_helper_modules!
+ super
+ end
+
private
def include_helper_modules!
@@ -89,7 +94,6 @@ module ActionView
@output_buffer = ActiveSupport::SafeBuffer.new
@rendered = ''
- self.class.send(:include_helper_modules!)
make_test_case_available_to_view!
say_no_to_protect_against_forgery!
end
@@ -99,7 +103,7 @@ module ActionView
end
def render(options = {}, local_assigns = {}, &block)
- view.assign(_assigns)
+ view.assign(view_assigns)
@rendered << output = view.render(options, local_assigns, &block)
output
end
@@ -123,6 +127,7 @@ module ActionView
def say_no_to_protect_against_forgery!
_helpers.module_eval do
+ remove_method :protect_against_forgery? if method_defined?(:protect_against_forgery?)
def protect_against_forgery?
false
end
@@ -132,8 +137,10 @@ module ActionView
def make_test_case_available_to_view!
test_case_instance = self
_helpers.module_eval do
- define_method(:_test_case) { test_case_instance }
- private :_test_case
+ unless private_method_defined?(:_test_case)
+ define_method(:_test_case) { test_case_instance }
+ private :_test_case
+ end
end
end
@@ -149,47 +156,59 @@ module ActionView
# The instance of ActionView::Base that is used by +render+.
def view
@view ||= begin
- view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller)
- view.singleton_class.send :include, _helpers
- view.singleton_class.send :include, @controller._routes.url_helpers
- view.singleton_class.send :delegate, :alert, :notice, :to => "request.flash"
- view.extend(Locals)
- view.locals = self.locals
- view.output_buffer = self.output_buffer
- view
- end
+ view = @controller.view_context
+ view.singleton_class.send :include, _helpers
+ view.extend(Locals)
+ view.locals = self.locals
+ view.output_buffer = self.output_buffer
+ view
+ end
end
alias_method :_view, :view
- EXCLUDE_IVARS = %w{
+ INTERNAL_IVARS = %w{
+ @__name__
+ @__io__
@_assertion_wrapped
+ @_assertions
@_result
+ @_routes
@controller
@layouts
@locals
@method_name
@output_buffer
@partials
+ @passed
@rendered
@request
@routes
@templates
+ @options
@test_passed
@view
@view_context_class
}
- def _instance_variables
- instance_variables.map(&:to_s) - EXCLUDE_IVARS
+ def _user_defined_ivars
+ instance_variables.map(&:to_s) - 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 |var|
+ [var[1, var.length].to_sym, instance_variable_get(var)]
+ end]
end
def _assigns
- _instance_variables.inject({}) do |hash, var|
- name = var[1..-1].to_sym
- hash[name] = instance_variable_get(var)
- hash
- end
+ ActiveSupport::Deprecation.warn "ActionView::TestCase#_assigns is deprecated and will be removed in future versions. " <<
+ "Please use view_assigns instead."
+ view_assigns
end
def _routes
@@ -198,7 +217,7 @@ module ActionView
def method_missing(selector, *args)
if @controller.respond_to?(:_routes) &&
- @controller._routes.named_routes.helpers.include?(selector)
+ @controller._routes.named_routes.helpers.include?(selector)
@controller.__send__(selector, *args)
else
super
diff --git a/actionpack/lib/action_view/testing/resolvers.rb b/actionpack/lib/action_view/testing/resolvers.rb
index 578c56c6c4..773dfcbb1d 100644
--- a/actionpack/lib/action_view/testing/resolvers.rb
+++ b/actionpack/lib/action_view/testing/resolvers.rb
@@ -8,36 +8,43 @@ module ActionView #:nodoc:
class FixtureResolver < PathResolver
attr_reader :hash
- def initialize(hash = {})
- super()
+ def initialize(hash = {}, pattern=nil)
+ super(pattern)
@hash = hash
end
+ def to_s
+ @hash.keys.join(', ')
+ end
+
private
def query(path, exts, formats)
- query = Regexp.escape(path)
- exts.each do |ext|
- query << '(' << ext.map {|e| e && Regexp.escape(".#{e}") }.join('|') << '|)'
+ query = ""
+ EXTENSIONS.each do |ext|
+ query << '(' << exts[ext].map {|e| e && Regexp.escape(".#{e}") }.join('|') << '|)'
end
+ query = /^(#{Regexp.escape(path)})#{query}$/
templates = []
- @hash.select { |k,v| k =~ /^#{query}$/ }.each do |path, source|
- handler, format = extract_handler_and_format(path, formats)
- templates << Template.new(source, path, handler,
- :virtual_path => path, :format => format)
+ @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 < ActionView::PathResolver
+ 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/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb
index 19855490b4..981c023d38 100644
--- a/actionpack/test/abstract/abstract_controller_test.rb
+++ b/actionpack/test/abstract/abstract_controller_test.rb
@@ -30,14 +30,14 @@ module AbstractController
class RenderingController < AbstractController::Base
include ::AbstractController::Rendering
- def _prefix() end
+ def _prefixes
+ []
+ end
def render(options = {})
if options.is_a?(String)
options = {:_template_name => options}
end
-
- options[:_prefix] = _prefix
super
end
@@ -116,8 +116,8 @@ module AbstractController
name.underscore
end
- def _prefix
- self.class.prefix
+ def _prefixes
+ [self.class.prefix]
end
end
@@ -157,10 +157,10 @@ module AbstractController
private
def self.layout(formats)
begin
- find_template(name.underscore, {:formats => formats}, :_prefix => "layouts")
+ find_template(name.underscore, {:formats => formats}, :_prefixes => ["layouts"])
rescue ActionView::MissingTemplate
begin
- find_template("application", {:formats => formats}, :_prefix => "layouts")
+ find_template("application", {:formats => formats}, :_prefixes => ["layouts"])
rescue ActionView::MissingTemplate
end
end
diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb
index 232a1679e0..3bdde86291 100644
--- a/actionpack/test/abstract/callbacks_test.rb
+++ b/actionpack/test/abstract/callbacks_test.rb
@@ -2,27 +2,27 @@ 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
- result = controller.process(:index)
+ controller.process(:index)
assert_equal "Hello world", controller.response_body
end
end
@@ -31,22 +31,23 @@ module AbstractController
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
@@ -54,22 +55,22 @@ module AbstractController
class Callback2Overwrite < Callback2
before_filter :first, :except => :index
end
-
+
class TestCallbacks2 < ActiveSupport::TestCase
def setup
@controller = Callback2.new
end
test "before_filter works" do
- result = @controller.process(:index)
+ @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")
@@ -77,20 +78,20 @@ module AbstractController
test "before_filter with overwritten condition" do
@controller = Callback2Overwrite.new
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "", @controller.response_body
end
end
-
+
class Callback3 < ControllerWithCallbacks
before_filter do |c|
c.instance_variable_set("@text", "Hello world")
end
-
+
after_filter do |c|
c.instance_variable_set("@second", "Goodbye")
end
-
+
def index
self.response_body = @text
end
@@ -100,41 +101,41 @@ module AbstractController
def setup
@controller = Callback3.new
end
-
+
test "before_filter works with procs" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Hello world", @controller.response_body
end
-
+
test "after_filter works with procs" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Goodbye", @controller.instance_variable_get("@second")
- end
+ end
end
-
+
class CallbacksWithConditions < ControllerWithCallbacks
before_filter :list, :only => :index
before_filter :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
@@ -144,98 +145,99 @@ module AbstractController
@controller.process(:index)
assert_equal "Hello, World", @controller.response_body
end
-
+
test "when :only is specified, a before filter 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 filter is not triggered on that action" do
- result = @controller.process(:index)
- assert_nil @controller.instance_variable_get("@authenticated")
+ @controller.process(:index)
+ assert !@controller.instance_variable_defined?("@authenticated")
end
end
-
+
class CallbacksWithArrayConditions < ControllerWithCallbacks
before_filter :list, :only => [:index, :listy]
before_filter :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
end
-
+
class TestCallbacksWithArrayConditions < ActiveSupport::TestCase
def setup
@controller = CallbacksWithArrayConditions.new
end
test "when :only is specified with an array, a before filter is triggered on that action" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Hello, World", @controller.response_body
end
-
+
test "when :only is specified with an array, a before filter is not triggered on other actions" do
- result = @controller.process(:sekrit_data)
+ @controller.process(:sekrit_data)
assert_equal "true", @controller.response_body
end
-
+
test "when :except is specified with an array, an after filter is not triggered on that action" do
- result = @controller.process(:index)
- assert_nil @controller.instance_variable_get("@authenticated")
+ @controller.process(:index)
+ assert !@controller.instance_variable_defined?("@authenticated")
end
- end
-
+ end
+
class ChangedConditions < Callback2
before_filter :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
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Hello world", @controller.response_body
end
-
+
test "when a callback is modified in a child with :only, it does not work for other actions" do
- result = @controller.process(:not_index)
+ @controller.process(:not_index)
assert_equal "", @controller.response_body
end
end
-
+
class SetsResponseBody < ControllerWithCallbacks
before_filter :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
@@ -243,6 +245,27 @@ module AbstractController
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 args" do
+ controller = CallbacksWithArgs.new
+ controller.process(:index, " Howdy!")
+ assert_equal "Hello world Howdy!", controller.response_body
+ end
+ end
+
+
end
end
diff --git a/actionpack/test/abstract/helper_test.rb b/actionpack/test/abstract/helper_test.rb
index 15c27501f2..b28a5b5afb 100644
--- a/actionpack/test/abstract/helper_test.rb
+++ b/actionpack/test/abstract/helper_test.rb
@@ -4,7 +4,7 @@ ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers',
module AbstractController
module Testing
-
+
class ControllerWithHelpers < AbstractController::Base
include AbstractController::Rendering
include Helpers
@@ -13,13 +13,13 @@ module AbstractController
render :inline => "Module <%= included_method %>"
end
end
-
+
module HelperyTest
def included_method
"Included"
end
end
-
+
class AbstractHelpers < ControllerWithHelpers
helper(HelperyTest) do
def helpery_test
@@ -38,6 +38,10 @@ module AbstractController
end
end
+ class ::HelperyTestController < AbstractHelpers
+ clear_helpers
+ end
+
class AbstractHelpersBlock < ControllerWithHelpers
helper do
include ::AbstractController::Testing::HelperyTest
@@ -45,7 +49,6 @@ module AbstractController
end
class TestHelpers < ActiveSupport::TestCase
-
def setup
@controller = AbstractHelpers.new
end
@@ -74,8 +77,22 @@ module AbstractController
@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
index f580ad40f7..5ed6aa68b5 100644
--- a/actionpack/test/abstract/layouts_test.rb
+++ b/actionpack/test/abstract/layouts_test.rb
@@ -225,7 +225,7 @@ module AbstractControllerTests
end
test "when the layout is specified as a symbol and the method doesn't exist, raise an exception" do
- assert_raises(NoMethodError) { WithSymbolAndNoMethod.new.process(:index) }
+ 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
diff --git a/actionpack/test/abstract/render_test.rb b/actionpack/test/abstract/render_test.rb
index 25dc8bd804..b9293d1241 100644
--- a/actionpack/test/abstract/render_test.rb
+++ b/actionpack/test/abstract/render_test.rb
@@ -6,8 +6,8 @@ module AbstractController
class ControllerRenderer < AbstractController::Base
include AbstractController::Rendering
- def _prefix
- "renderer"
+ def _prefixes
+ %w[renderer]
end
self.view_paths = [ActionView::FixtureResolver.new(
diff --git a/actionpack/test/abstract/translation_test.rb b/actionpack/test/abstract/translation_test.rb
index 09ebfab85e..8ec50fd57a 100644
--- a/actionpack/test/abstract/translation_test.rb
+++ b/actionpack/test/abstract/translation_test.rb
@@ -7,19 +7,19 @@ class TranslationControllerTest < Test::Unit::TestCase
def setup
@controller = ActionController::Base.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
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 5be47f7c96..60534a9746 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -12,8 +12,16 @@ $:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers')
ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp')
-if defined?(Encoding.default_internal)
- Encoding.default_internal = "UTF-8"
+require 'active_support/core_ext/kernel/reporting'
+
+require 'active_support/core_ext/string/encoding'
+if "ruby".encoding_aware?
+ # 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
end
require 'test/unit'
@@ -28,25 +36,14 @@ require 'active_record'
require 'action_controller/caching'
require 'action_controller/caching/sweeping'
-begin
- require 'ruby-debug'
- Debugger.settings[:autoeval] = true
- Debugger.start
-rescue LoadError
- # Debugging disabled. `gem install ruby-debug` to enable.
-end
-
require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
module Rails
-end
-
-# Monkey patch the old routes initialization to be silenced.
-class ActionDispatch::Routing::DeprecatedMapper
- def initialize_with_silencer(*args)
- ActiveSupport::Deprecation.silence { initialize_without_silencer(*args) }
+ class << self
+ def env
+ @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "test")
+ end
end
- alias_method_chain :initialize, :silencer
end
ActiveSupport::Dependencies.hook!
@@ -120,14 +117,12 @@ module ActiveSupport
# Hold off drawing routes until all the possible controller classes
# have been loaded.
setup_once do
- SharedTestRoutes.draw do |map|
- # FIXME: match ':controller(/:action(/:id))'
- map.connect ':controller/:action/:id'
+ SharedTestRoutes.draw do
+ match ':controller(/:action)'
end
- ActionController::IntegrationTest.app.routes.draw do |map|
- # FIXME: match ':controller(/:action(/:id))'
- map.connect ':controller/:action/:id'
+ ActionDispatch::IntegrationTest.app.routes.draw do
+ match ':controller(/:action)'
end
end
end
@@ -165,9 +160,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
setup do
@routes = SharedTestRoutes
end
-end
-class ActionController::IntegrationTest < ActiveSupport::TestCase
def self.build_app(routes = nil)
RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware|
middleware.use "ActionDispatch::ShowExceptions"
@@ -218,7 +211,7 @@ class ActionController::IntegrationTest < ActiveSupport::TestCase
end
def with_autoload_path(path)
- path = File.join(File.dirname(__FILE__), "fixtures", path)
+ path = File.join(File.dirname(__FILE__), "fixtures", path)
if ActiveSupport::Dependencies.autoload_paths.include?(path)
yield
else
@@ -234,7 +227,7 @@ class ActionController::IntegrationTest < ActiveSupport::TestCase
end
# Temporary base class
-class Rack::TestCase < ActionController::IntegrationTest
+class Rack::TestCase < ActionDispatch::IntegrationTest
def self.testing(klass = nil)
if klass
@testing = "/#{klass.name.underscore}".sub!(/_controller$/, '')
@@ -276,11 +269,27 @@ class Rack::TestCase < ActionController::IntegrationTest
end
end
-class ActionController::Base
- def self.test_routes(&block)
- routes = ActionDispatch::Routing::RouteSet.new
- routes.draw(&block)
- include routes.url_helpers
+module ActionController
+ class Base
+ include ActionController::Testing
+ # This stub emulates the Railtie including the URL helpers from a Rails application
+ include SharedTestRoutes.url_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
+
+ setup do
+ @routes = SharedTestRoutes
+ end
end
end
@@ -297,25 +306,37 @@ module ActionView
end
end
-module ActionController
- class Base
- include ActionController::Testing
- end
+class Workshop
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+ attr_accessor :id
- Base.view_paths = FIXTURE_LOAD_PATH
+ def initialize(id)
+ @id = id
+ end
- class TestCase
- include ActionDispatch::TestProcess
+ def persisted?
+ id.present?
+ end
- setup do
- @routes = SharedTestRoutes
- end
+ def to_s
+ id.to_s
end
end
-# This stub emulates the Railtie including the URL helpers from a Rails application
-module ActionController
- class Base
- include SharedTestRoutes.url_helpers
+module ActionDispatch
+ class ShowExceptions
+ private
+ remove_method :public_path
+ def public_path
+ "#{FIXTURE_LOAD_PATH}/public"
+ end
+
+ remove_method :logger
+ # Silence logger
+ def logger
+ nil
+ end
end
end
+
diff --git a/actionpack/test/action_dispatch/routing/mapper_test.rb b/actionpack/test/action_dispatch/routing/mapper_test.rb
new file mode 100644
index 0000000000..e21b271907
--- /dev/null
+++ b/actionpack/test/action_dispatch/routing/mapper_test.rb
@@ -0,0 +1,58 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Routing
+ class MapperTest < ActiveSupport::TestCase
+ class FakeSet
+ attr_reader :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
+ end
+
+ def test_initialize
+ Mapper.new FakeSet.new
+ end
+
+ def test_map_slash
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.match '/', :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.match '/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.match '/*path', :to => 'pages#show', :as => :page
+ assert_equal '/*path', fakeset.conditions.first[:path_info]
+ end
+ end
+ end
+end
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index bdd1a0a15c..f0fb113860 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -1,6 +1,6 @@
require 'active_record_unit'
-class ActiveRecordStoreTest < ActionController::IntegrationTest
+class ActiveRecordStoreTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
def no_session_access
head :ok
@@ -23,6 +23,13 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
def call_reset_session
session[:foo]
reset_session
+ reset_session if params[:twice]
+ session[:foo] = "baz"
+ head :ok
+ end
+
+ def renew
+ env["rack.session.options"][:renew] = true
session[:foo] = "baz"
head :ok
end
@@ -64,6 +71,20 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
end
end
end
+
+ define_method("test_renewing_with_#{class_name}_store") do
+ with_store class_name do
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+
+ get '/renew'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+ end
+ end
+ end
end
def test_getting_nil_session_value
@@ -74,6 +95,17 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
end
end
+ def test_calling_reset_session_twice_does_not_raise_errors
+ with_test_route_set do
+ get '/call_reset_session', :twice => "true"
+ assert_response :success
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: "baz"', response.body
+ end
+ end
+
def test_setting_session_value_after_session_reset
with_test_route_set do
get '/set_session_value'
@@ -198,7 +230,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
def with_test_route_set(options = {})
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => 'active_record_store_test/test'
end
diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb
index cfd86d704d..7931da3741 100644
--- a/actionpack/test/activerecord/controller_runtime_test.rb
+++ b/actionpack/test/activerecord/controller_runtime_test.rb
@@ -37,6 +37,6 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase
wait
assert_equal 2, @logger.logged(:info).size
- assert_match /\(Views: [\d\.]+ms | ActiveRecord: [\d\.]+ms\)/, @logger.logged(:info)[1]
+ assert_match(/\(Views: [\d.]+ms | ActiveRecord: [\d.]+ms\)/, @logger.logged(:info)[1])
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb
index 90a1ef982c..f9e47d5118 100644
--- a/actionpack/test/activerecord/polymorphic_routes_test.rb
+++ b/actionpack/test/activerecord/polymorphic_routes_test.rb
@@ -25,6 +25,22 @@ class Series < ActiveRecord::Base
set_table_name 'projects'
end
+module Blog
+ class Post < ActiveRecord::Base
+ set_table_name 'projects'
+ end
+
+ class Blog < ActiveRecord::Base
+ set_table_name 'projects'
+ end
+
+ def self._railtie
+ o = Object.new
+ def o.railtie_name; "blog" end
+ o
+ end
+end
+
class PolymorphicRoutesTest < ActionController::TestCase
include SharedTestRoutes.url_helpers
self.default_url_options[:host] = 'example.com'
@@ -37,6 +53,38 @@ class PolymorphicRoutesTest < ActionController::TestCase
@tax = Tax.new
@fax = Fax.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_record
@@ -385,20 +433,36 @@ class PolymorphicRoutesTest < ActionController::TestCase
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 |map|
- map.resources :projects do |projects|
- projects.resources :tasks
- projects.resource :bid do |bid|
- bid.resources :tasks
+ set.draw do
+ resources :projects do
+ resources :tasks
+ resource :bid do
+ resources :tasks
end
end
- map.resources :taxes do |taxes|
- taxes.resources :faxes
- taxes.resource :bid
+ resources :taxes do
+ resources :faxes
+ resource :bid
end
- map.resources :series
+ resources :series
end
self.class.send(:include, @routes.url_helpers)
diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
index df50c3dc6f..99f09286ff 100644
--- a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
+++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
@@ -11,7 +11,7 @@ class RenderPartialWithRecordIdentificationController < ActionController::Base
render :partial => @topic.replies
end
- def render_with_named_scope
+ def render_with_scope
render :partial => Reply.base
end
@@ -62,8 +62,8 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase
assert_equal 'Birdman is better!', @response.body
end
- def test_rendering_partial_with_named_scope
- get :render_with_named_scope
+ def test_rendering_partial_with_scope
+ get :render_with_scope
assert_template 'replies/_reply'
assert_equal 'Birdman is better!Nuh uh!', @response.body
end
@@ -93,38 +93,6 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase
end
end
-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_has_many_through_association
- @developer = Developer.find(:first)
- render :partial => @developer.topics
- end
-
- def render_with_belongs_to_association
- @reply = Reply.find(1)
- render :partial => @reply.topic
- end
-
- def render_with_record
- @developer = Developer.find(:first)
- render :partial => @developer
- end
-
- def render_with_record_collection
- @developers = Developer.find(:all)
- render :partial => @developers
- end
-end
-
class Game < Struct.new(:name, :id)
extend ActiveModel::Naming
include ActiveModel::Conversion
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 53cdd358b4..7f3d943bba 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -2,34 +2,26 @@ require 'abstract_unit'
require 'action_controller/vendor/html-scanner'
require 'controller/fake_controllers'
-# a controller class to facilitate the tests
class ActionPackAssertionsController < ActionController::Base
- # this does absolutely nothing
def nothing() head :ok end
- # a standard template
def hello_world() render :template => "test/hello_world"; end
- # a standard template
def hello_xml_world() render :template => "test/hello_xml_world"; end
- # a standard template rendering PDF
def hello_xml_world_pdf
self.content_type = "application/pdf"
render :template => "test/hello_xml_world"
end
- # a standard template rendering PDF
def hello_xml_world_pdf_header
response.headers["Content-Type"] = "application/pdf; charset=utf-8"
render :template => "test/hello_xml_world"
end
- # a standard partial
def partial() render :partial => 'test/partial'; end
- # a redirect to an internal location
def redirect_internal() redirect_to "/nothing"; end
def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end
@@ -40,33 +32,28 @@ class ActionPackAssertionsController < ActionController::Base
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
- # a redirect to an external location
def redirect_external() redirect_to "http://www.rubyonrails.org"; end
- # a 404
def response404() head '404 AWOL' end
- # a 500
def response500() head '500 Sorry' end
- # a fictional 599
def response599() head '599 Whoah!' end
- # putting stuff in the flash
def flash_me
flash['hello'] = 'my name is inigo montoya...'
render :text => "Inconceivable!"
end
- # we have a flash, but nothing is in it
def flash_me_naked
flash.clear
render :text => "wow!"
end
- # assign some template instance variables
def assign_this
@howdy = "ho"
render :inline => "Mr. Henke"
@@ -84,61 +71,20 @@ class ActionPackAssertionsController < ActionController::Base
render :text => "Hello!", :content_type => Mime::RSS
end
- # puts something in the session
def session_stuffing
session['xmas'] = 'turkey'
render :text => "ho ho ho"
end
- # raises exception on get requests
- def raise_on_get
+ def raise_exception_on_get
raise "get" if request.get?
render :text => "request method: #{request.env['REQUEST_METHOD']}"
end
- # raises exception on post requests
- def raise_on_post
+ def raise_exception_on_post
raise "post" if request.post?
render :text => "request method: #{request.env['REQUEST_METHOD']}"
end
-
- def get_valid_record
- @record = Class.new do
- def valid?
- true
- end
-
- def errors
- Class.new do
- def full_messages; []; end
- end.new
- end
-
- end.new
-
- render :nothing => true
- end
-
-
- def get_invalid_record
- @record = Class.new do
-
- def valid?
- false
- end
-
- def errors
- Class.new do
- def full_messages; ['...stuff...']; end
- end.new
- end
- end.new
-
- render :nothing => true
- end
-
- # 911
- def rescue_action(e) raise; end
end
# Used to test that assert_response includes the exception message
@@ -181,48 +127,39 @@ module Admin
end
end
-# require "action_dispatch/test_process"
-
-# a test case to exercise the new capabilities TestRequest & TestResponse
class ActionPackAssertionsControllerTest < ActionController::TestCase
- # -- assertion-based testing ------------------------------------------------
def test_assert_tag_and_url_for
get :render_url
assert_tag :content => "/action_pack_assertions/flash_me"
end
- # test the get method, make sure the request really was a get
- def test_get
- assert_raise(RuntimeError) { get :raise_on_get }
- get :raise_on_post
+ 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
- # test the get method, make sure the request really was a get
- def test_post
- assert_raise(RuntimeError) { post :raise_on_post }
- post :raise_on_get
+ 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
-# the following test fails because the request_method is now cached on the request instance
-# test the get/post switch within one test action
-# def test_get_post_switch
-# post :raise_on_get
-# assert_equal @response.body, 'request method: POST'
-# get :raise_on_post
-# assert_equal @response.body, 'request method: GET'
-# post :raise_on_get
-# assert_equal @response.body, 'request method: POST'
-# get :raise_on_post
-# assert_equal @response.body, 'request method: GET'
-# end
-
- # test the redirection to a named route
- def test_assert_redirect_to_named_route
+ def test_redirect_to_named_route
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one
match ':controller/:action'
end
@@ -234,9 +171,17 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
end
end
+ def test_string_constraint
+ with_routing do |set|
+ set.draw do
+ match "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 |map|
+ set.draw do
match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one
match 'route_two', :to => 'action_pack_assertions#nothing', :id => 'two', :as => :route_two
match ':controller/:action'
@@ -258,10 +203,9 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
@controller = Admin::InnerModuleController.new
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module
- # match ':controller/:action'
- map.connect ':controller/:action/:id'
+ match ':controller/:action'
end
process :redirect_to_index
# redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}>
@@ -273,10 +217,9 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
@controller = Admin::InnerModuleController.new
with_routing do |set|
- set.draw do |map|
+ set.draw do
match '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level
- # match ':controller/:action'
- map.connect ':controller/:action/:id'
+ match ':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
@@ -288,11 +231,10 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
@controller = Admin::InnerModuleController.new
with_routing do |set|
- set.draw do |map|
+ set.draw do
# this controller exists in the admin namespace as well which is the only difference from previous test
match '/user/:id', :to => 'user#index', :as => :top_level
- # match ':controller/:action'
- map.connect ':controller/:action/:id'
+ match ':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
@@ -300,53 +242,44 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
end
end
- # -- standard request/response object testing --------------------------------
-
- # make sure that the template objects exist
- def test_template_objects_alive
+ def test_template_objects_exist
process :assign_this
- assert !@controller.instance_variable_get(:"@hi")
+ assert !@controller.instance_variable_defined?(:"@hi")
assert @controller.instance_variable_get(:"@howdy")
end
- # make sure we don't have template objects when we shouldn't
- def test_template_object_missing
+ def test_template_objects_missing
process :nothing
- assert_nil @controller.instance_variable_get(:@howdy)
+ assert !@controller.instance_variable_defined?(:@howdy)
end
- # check the empty flashing
- def test_flash_me_naked
+ def test_empty_flash
process :flash_me_naked
- assert_deprecated do
- assert !@response.has_flash?
- assert !@response.has_flash_with_contents?
- end
+ assert flash.empty?
end
- # check if we have flash objects
- def test_flash_haves
+ def test_flash_exist
process :flash_me
- assert_deprecated do
- assert @response.has_flash?
- assert @response.has_flash_with_contents?
- assert @response.has_flash_object?('hello')
- end
+ assert flash.any?
+ assert_present flash['hello']
end
- # ensure we don't have flash objects
- def test_flash_have_nots
+ def test_flash_does_not_exist
process :nothing
- assert_deprecated do
- assert !@response.has_flash?
- assert !@response.has_flash_with_contents?
- assert_nil @response.flash['hello']
- end
+ assert flash.empty?
end
+ def test_session_exist
+ process :session_stuffing
+ assert_equal session['xmas'], 'turkey'
+ end
- # check if we were rendered by a file-based template?
- def test_rendered_action
+ def session_does_not_exist
+ process :nothing
+ assert session.empty?
+ end
+
+ def test_render_template_action
process :nothing
assert_template nil
@@ -354,7 +287,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
assert_template 'hello_world'
end
- # check the redirection location
def test_redirection_location
process :redirect_internal
assert_equal 'http://test.host/nothing', @response.redirect_url
@@ -368,7 +300,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
assert_nil @response.redirect_url
end
- # check server errors
def test_server_error_response_code
process :response500
assert @response.server_error?
@@ -380,31 +311,23 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
assert !@response.server_error?
end
- # check a 404 response code
def test_missing_response_code
process :response404
assert @response.missing?
end
- # check client errors
def test_client_error_response_code
process :response404
assert @response.client_error?
end
- # check to see if our redirection matches a pattern
def test_redirect_url_match
process :redirect_external
assert @response.redirect?
- assert_deprecated do
- assert @response.redirect_url_match?("rubyonrails")
- assert @response.redirect_url_match?(/rubyonrails/)
- assert !@response.redirect_url_match?("phpoffrails")
- assert !@response.redirect_url_match?(/perloffrails/)
- end
+ assert_match(/rubyonrails/, @response.redirect_url)
+ assert !/perloffrails/.match(@response.redirect_url)
end
- # check for a redirection
def test_redirection
process :redirect_internal
assert @response.redirect?
@@ -416,14 +339,12 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
assert !@response.redirect?
end
- # check a successful response code
def test_successful_response_code
process :nothing
assert @response.success?
end
- # a basic check to make sure we have a TestResponse object
- def test_has_response
+ def test_response_object
process :nothing
assert_kind_of ActionController::TestResponse, @response
end
@@ -457,6 +378,11 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
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'
@@ -547,6 +473,14 @@ class AssertTemplateTest < ActionController::TestCase
assert_template :hello_planet
end
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
diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb
index 4f8ad23174..f63321c78b 100644
--- a/actionpack/test/controller/assert_select_test.rb
+++ b/actionpack/test/controller/assert_select_test.rb
@@ -15,10 +15,8 @@ class AssertSelectTest < ActionController::TestCase
class AssertSelectMailer < ActionMailer::Base
def test(html)
- recipients "test <test@test.host>"
- from "test@test.host"
- subject "Test e-mail"
- part :content_type=>"text/html", :body=>html
+ mail :body => html, :content_type => "text/html",
+ :subject => "Test e-mail", :from => "test@test.host", :to => "test <test@test.host>"
end
end
@@ -257,7 +255,7 @@ class AssertSelectTest < ActionController::TestCase
end
assert_raise(Assertion) {assert_select_rjs :insert, :top, "test2"}
end
-
+
def test_assert_select_rjs_for_redirect_to
render_rjs do |page|
page.redirect_to '/'
@@ -461,8 +459,8 @@ class AssertSelectTest < ActionController::TestCase
assert_select_rjs :remove, "test1"
- rescue Assertion
- assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message
+ rescue Assertion => e
+ assert_equal "No RJS statement that removes 'test1' was rendered.", e.message
end
def test_assert_select_rjs_for_remove_ignores_block
@@ -493,8 +491,8 @@ class AssertSelectTest < ActionController::TestCase
assert_select_rjs :show, "test1"
- rescue Assertion
- assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message
+ rescue Assertion => e
+ assert_equal "No RJS statement that shows 'test1' was rendered.", e.message
end
def test_assert_select_rjs_for_show_ignores_block
@@ -525,8 +523,8 @@ class AssertSelectTest < ActionController::TestCase
assert_select_rjs :hide, "test1"
- rescue Assertion
- assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message
+ rescue Assertion => e
+ assert_equal "No RJS statement that hides 'test1' was rendered.", e.message
end
def test_assert_select_rjs_for_hide_ignores_block
@@ -557,8 +555,8 @@ class AssertSelectTest < ActionController::TestCase
assert_select_rjs :toggle, "test1"
- rescue Assertion
- assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message
+ rescue Assertion => e
+ assert_equal "No RJS statement that toggles 'test1' was rendered.", e.message
end
def test_assert_select_rjs_for_toggle_ignores_block
@@ -731,7 +729,7 @@ EOF
end
def render_rjs(&block)
- @controller.response_with &block
+ @controller.response_with(&block)
get :rjs
end
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index ae270b751e..9c22a4e7e0 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -87,7 +87,7 @@ class RecordIdentifierController < ActionController::Base
end
class ControllerClassTests < ActiveSupport::TestCase
-
+
def test_controller_path
assert_equal 'empty', EmptyController.controller_path
assert_equal EmptyController.controller_path, EmptyController.new.controller_path
@@ -99,20 +99,6 @@ class ControllerClassTests < ActiveSupport::TestCase
assert_equal 'empty', EmptyController.controller_name
assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
end
-
- def test_filter_parameter_logging
- parameters = []
- config = mock(:config => mock(:filter_parameters => parameters))
- Rails.expects(:application).returns(config)
-
- assert_deprecated do
- Class.new(ActionController::Base) do
- filter_parameter_logging :password
- end
- end
-
- assert_equal [:password], parameters
- end
def test_record_identifier
assert_respond_to RecordIdentifierController.new, :dom_id
@@ -164,15 +150,15 @@ class PerformActionTest < ActionController::TestCase
rescue_action_in_public!
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"
+ assert_equal exception.message, "The action 'non_existent' could not be found for EmptyController"
end
-
+
def test_get_on_priv_should_show_selector
use_controller MethodMissingController
get :shouldnt_be_called
@@ -224,7 +210,7 @@ class UrlOptionsTest < ActionController::TestCase
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
+ end
def test_url_helpers_does_not_become_actions
with_routing do |set|
@@ -308,7 +294,7 @@ class EmptyUrlOptionsTest < ActionController::TestCase
@controller.request = @request
with_routing do |set|
- set.draw do |map|
+ set.draw do
resources :things
end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index c161bea945..01f3e8f2b6 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -16,6 +16,7 @@ end
class PageCachingTestController < CachingController
caches_page :ok, :no_content, :if => Proc.new { |c| !c.request.format.json? }
caches_page :found, :not_found
+ caches_page :about_me
def ok
@@ -47,6 +48,14 @@ class PageCachingTestController < CachingController
def trailing_slash
render :text => "Sneak attack"
end
+
+ def about_me
+ respond_to do |format|
+ format.html {render :text => 'I am html'}
+ format.xml {render :text => 'I am xml'}
+ end
+ end
+
end
class PageCachingTest < ActionController::TestCase
@@ -76,7 +85,7 @@ class PageCachingTest < ActionController::TestCase
def test_page_caching_resources_saves_to_correct_path_with_extension_even_if_default_route
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'posts.:format', :to => 'posts#index', :as => :formatted_posts
match '/', :to => 'posts#index', :as => :main
end
@@ -111,6 +120,13 @@ class PageCachingTest < ActionController::TestCase
assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html")
end
+ def test_should_obey_http_accept_attribute
+ @request.env['HTTP_ACCEPT'] = 'text/xml'
+ get :about_me
+ assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/about_me.xml")
+ assert_equal 'I am xml', @response.body
+ end
+
def test_should_cache_with_trailing_slash_on_url
@controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash/'
assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html")
@@ -140,6 +156,17 @@ class PageCachingTest < ActionController::TestCase
assert_page_not_cached :ok
end
+ def test_page_caching_directory_set_as_pathname
+ begin
+ ActionController::Base.page_cache_directory = Pathname.new(FILE_STORE_PATH)
+ get :ok
+ assert_response :ok
+ assert_page_cached :ok
+ ensure
+ ActionController::Base.page_cache_directory = FILE_STORE_PATH
+ end
+ end
+
private
def assert_page_cached(action, message = "#{action} should have been cached")
assert page_cached?(action), message
@@ -185,6 +212,7 @@ class ActionCachingTestController < CachingController
def with_layout
@cache_this = MockTime.now.to_f.to_s
+ @title = nil
render :text => @cache_this, :layout => true
end
@@ -240,7 +268,6 @@ class ActionCachingMockController
end
def request
- mocked_path = @mock_path
Object.new.instance_eval(<<-EVAL)
def path; '#{@mock_path}' end
def format; 'all' end
@@ -399,7 +426,6 @@ class ActionCacheTest < ActionController::TestCase
get :index
assert_response :success
- new_cached_time = content_to_cache
assert_not_equal cached_time, @response.body
end
@@ -452,7 +478,7 @@ class ActionCacheTest < ActionController::TestCase
def test_xml_version_of_resource_is_treated_as_different_cache
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':controller(/:action(.:format))'
end
@@ -533,6 +559,11 @@ class ActionCacheTest < ActionController::TestCase
assert_response 404
end
+ def test_four_oh_four_renders_content
+ get :four_oh_four
+ assert_equal "404'd!", @response.body
+ end
+
def test_simple_runtime_error_returns_500_for_multiple_requests
get :simple_runtime_error
assert_response 500
@@ -637,7 +668,7 @@ class FragmentCachingTest < ActionController::TestCase
@store.write('views/another_name', 'another_value')
@store.write('views/primalgrasp', 'will not expire ;-)')
- @controller.expire_fragment /name/
+ @controller.expire_fragment(/name/)
assert_nil @store.read('views/name')
assert_nil @store.read('views/another_name')
@@ -727,23 +758,23 @@ CACHED
def test_fragment_caching_in_partials
get :html_fragment_cached_with_partial
assert_response :success
- assert_match /Old fragment caching in a partial/, @response.body
- assert_match "Old fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial')
+ assert_match(/Old fragment caching in a partial/, @response.body)
+ assert_match("Old fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial'))
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')
+ 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'))
end
def test_fragment_caching_in_rjs_partials
xhr :get, :js_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/js_fragment_cached_with_partial')
+ 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/js_fragment_cached_with_partial'))
end
def test_html_formatted_fragment_caching
diff --git a/actionpack/test/controller/capture_test.rb b/actionpack/test/controller/capture_test.rb
index 47253f22b8..d78acb8ce8 100644
--- a/actionpack/test/controller/capture_test.rb
+++ b/actionpack/test/controller/capture_test.rb
@@ -6,21 +6,29 @@ class CaptureController < ActionController::Base
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
+
def rescue_action(e) raise end
end
@@ -62,8 +70,8 @@ class CaptureTest < ActionController::TestCase
end
def test_proper_block_detection
- @todo = "some todo"
get :proper_block_detection
+ assert_equal "some todo", @response.body
end
private
diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb
index 967107853b..9500c25a32 100644
--- a/actionpack/test/controller/content_type_test.rb
+++ b/actionpack/test/controller/content_type_test.rb
@@ -29,18 +29,18 @@ class OldContentTypeController < ActionController::Base
render :text => "hello world!"
end
- def render_default_for_rhtml
+ def render_default_for_erb
end
- def render_default_for_rxml
+ def render_default_for_builder
end
def render_default_for_rjs
end
- def render_change_for_rxml
+ def render_change_for_builder
response.content_type = Mime::HTML
- render :action => "render_default_for_rxml"
+ render :action => "render_default_for_builder"
end
def render_default_content_types_for_respond_to
@@ -108,23 +108,23 @@ class ContentTypeTest < ActionController::TestCase
assert_equal "utf-8", @response.charset, @response.headers.inspect
end
- def test_nil_default_for_rhtml
+ def test_nil_default_for_erb
OldContentTypeController.default_charset = nil
- get :render_default_for_rhtml
+ get :render_default_for_erb
assert_equal Mime::HTML, @response.content_type
assert_nil @response.charset, @response.headers.inspect
ensure
OldContentTypeController.default_charset = "utf-8"
end
- def test_default_for_rhtml
- get :render_default_for_rhtml
+ 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_rxml
- get :render_default_for_rxml
+ def test_default_for_builder
+ get :render_default_for_builder
assert_equal Mime::XML, @response.content_type
assert_equal "utf-8", @response.charset
end
@@ -135,8 +135,8 @@ class ContentTypeTest < ActionController::TestCase
assert_equal "utf-8", @response.charset
end
- def test_change_for_rxml
- get :render_change_for_rxml
+ def test_change_for_builder
+ get :render_change_for_builder
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-8", @response.charset
end
diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb
deleted file mode 100644
index 7e19bce3b7..0000000000
--- a/actionpack/test/controller/dispatcher_test.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-require 'abstract_unit'
-
-# Ensure deprecated dispatcher works
-class DeprecatedDispatcherTest < ActiveSupport::TestCase
- class DummyApp
- def call(env)
- [200, {}, 'response']
- end
- end
-
- def setup
- ActionDispatch::Callbacks.reset_callbacks(:prepare)
- ActionDispatch::Callbacks.reset_callbacks(:call)
- end
-
- def test_assert_deprecated_to_prepare
- a = nil
-
- assert_deprecated do
- ActionController::Dispatcher.to_prepare { a = 1 }
- end
-
- assert_nil a
- dispatch
- assert_equal 1, a
- end
-
- def test_assert_deprecated_before_dispatch
- a = nil
-
- assert_deprecated do
- ActionController::Dispatcher.before_dispatch { a = 1 }
- end
-
- assert_nil a
- dispatch
- assert_equal 1, a
- end
-
- def test_assert_deprecated_after_dispatch
- a = nil
-
- assert_deprecated do
- ActionController::Dispatcher.after_dispatch { a = 1 }
- end
-
- assert_nil a
- dispatch
- assert_equal 1, a
- end
-
- private
-
- def dispatch(cache_classes = true)
- @dispatcher ||= ActionDispatch::Callbacks.new(DummyApp.new, !cache_classes)
- @dispatcher.call({'rack.input' => StringIO.new('')})
- end
-
-end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 14f1bd797a..9e44e8e088 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -78,7 +78,8 @@ class FilterTest < ActionController::TestCase
end
class RenderingController < ActionController::Base
- before_filter :render_something_else
+ before_filter :before_filter_rendering
+ after_filter :unreached_after_filter
def show
@ran_action = true
@@ -86,9 +87,59 @@ class FilterTest < ActionController::TestCase
end
private
- def render_something_else
+ 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
@@ -314,6 +365,7 @@ class FilterTest < ActionController::TestCase
def initialize
@@execution_log = ""
+ super()
end
before_filter { |c| c.class.execution_log << " before procfilter " }
@@ -447,18 +499,34 @@ class FilterTest < ActionController::TestCase
class ::AppSweeper < ActionController::Caching::Sweeper; end
class SweeperTestController < ActionController::Base
- cache_sweeper :app_sweeper
+ cache_sweeper :app_sweeper
def show
render :text => 'hello world'
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_sweeper_should_not_block_rendering
response = test_process(SweeperTestController)
assert_equal 'hello world', response.body
end
def test_before_method_of_sweeper_should_always_return_true
- sweeper = ActionController::Caching::Sweeper.send(:new)
+ sweeper = ActionController::Caching::Sweeper.send(:new)
assert sweeper.before(TestController.new)
end
@@ -611,7 +679,7 @@ class FilterTest < ActionController::TestCase
end
def test_prepending_and_appending_around_filter
- controller = test_process(MixedFilterController)
+ test_process(MixedFilterController)
assert_equal " before aroundfilter before procfilter before appended aroundfilter " +
" after appended aroundfilter after procfilter after aroundfilter ",
MixedFilterController.execution_log
@@ -623,6 +691,32 @@ class FilterTest < ActionController::TestCase
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')
@@ -668,7 +762,7 @@ class FilterTest < ActionController::TestCase
assert_equal %w( ensure_login find_user ), assigns["ran_filter"]
test_process(ConditionalSkippingController, "login")
- assert_nil @controller.instance_variable_get("@ran_after_filter")
+ 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
@@ -704,6 +798,18 @@ class FilterTest < ActionController::TestCase
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
@@ -756,12 +862,12 @@ class ControllerWithSymbolAsFilter < PostsController
def without_exception
# Do stuff...
- 1 + 1
+ wtf = 1 + 1
yield
# Do stuff...
- 1 + 1
+ wtf += 1
end
end
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index 4be09f8c83..3569a2f213 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -209,7 +209,7 @@ class FlashTest < ActionController::TestCase
end
end
-class FlashIntegrationTest < ActionController::IntegrationTest
+class FlashIntegrationTest < ActionDispatch::IntegrationTest
SessionKey = '_myapp_session'
SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
@@ -255,7 +255,7 @@ class FlashIntegrationTest < ActionController::IntegrationTest
def with_test_route_set
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => FlashIntegrationTest::TestController
end
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 9b9657929f..9f0670ffdf 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -25,6 +25,32 @@ 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
+
module LocalAbcHelper
def a() end
def b() end
@@ -50,7 +76,7 @@ class HelperTest < ActiveSupport::TestCase
# Set default test helper.
self.test_helper = LocalAbcHelper
end
-
+
def test_deprecated_helper
assert_equal expected_helper_methods, missing_methods
assert_nothing_raised { @controller_class.helper TestHelper }
@@ -70,28 +96,45 @@ class HelperTest < ActiveSupport::TestCase
def call_controller(klass, action)
request = ActionController::TestRequest.new
- klass.action(action).call(request.env)
+ klass.action(action).call(request.env)
end
def test_helper_for_nested_controller
- assert_equal 'hello: Iz guuut!',
+ 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.map {|m| m.to_s}
@@ -135,17 +178,6 @@ class HelperTest < ActiveSupport::TestCase
assert methods.include?('foobar')
end
- def test_deprecation
- assert_deprecated do
- ActionController::Base.helpers_dir = "some/foo/bar"
- end
- assert_deprecated do
- assert_equal ["some/foo/bar"], ActionController::Base.helpers_dir
- end
- ensure
- ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__)
- end
-
private
def expected_helper_methods
TestHelper.instance_methods.map {|m| m.to_s }
@@ -192,7 +224,7 @@ class IsolatedHelpersTest < ActiveSupport::TestCase
def call_controller(klass, action)
request = ActionController::TestRequest.new
- klass.action(action).call(request.env)
+ klass.action(action).call(request.env)
end
def setup
diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb
index 23688ca584..01c650a494 100644
--- a/actionpack/test/controller/http_basic_authentication_test.rb
+++ b/actionpack/test/controller/http_basic_authentication_test.rb
@@ -13,7 +13,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
def display
render :text => 'Definitely Maybe'
end
-
+
def show
render :text => 'Only for loooooong credentials'
end
@@ -33,7 +33,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
request_http_basic_authentication("SuperSecret")
end
end
-
+
def authenticate_long_credentials
authenticate_or_request_with_http_basic do |username, password|
username == '1234567890123456789012345678901234567890' && password == '1234567890123456789012345678901234567890'
@@ -56,7 +56,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
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
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index 3dfccae3db..3054c1684c 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -13,7 +13,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
def display
render :text => 'Definitely Maybe'
end
-
+
def show
render :text => 'Only for loooooong credentials'
end
@@ -33,7 +33,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
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'
@@ -56,7 +56,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
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
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 5ee8e2b6ae..f0d62b0b13 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -8,7 +8,7 @@ class SessionTest < Test::Unit::TestCase
}
def setup
- @session = ActionController::Integration::Session.new(StubApp)
+ @session = ActionDispatch::Integration::Session.new(StubApp)
end
def test_https_bang_works_and_sets_truth_by_default
@@ -167,7 +167,7 @@ end
class IntegrationTestTest < Test::Unit::TestCase
def setup
- @test = ::ActionController::IntegrationTest.new(:default_test)
+ @test = ::ActionDispatch::IntegrationTest.new(:app)
@test.class.stubs(:fixture_table_names).returns([])
@session = @test.open_session
end
@@ -202,7 +202,7 @@ end
# Tests that integration tests don't call Controller test methods for processing.
# Integration tests have their own setup and teardown.
-class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest
+class IntegrationTestUsesCorrectClass < ActionDispatch::IntegrationTest
def self.fixture_table_names
[]
end
@@ -218,7 +218,7 @@ class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest
end
end
-class IntegrationProcessTest < ActionController::IntegrationTest
+class IntegrationProcessTest < ActionDispatch::IntegrationTest
class IntegrationController < ActionController::Base
def get
respond_to do |format|
@@ -427,7 +427,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
include set.url_helpers
end
- set.draw do |map|
+ set.draw do
match ':action', :to => controller
get 'get/:action', :to => controller
end
@@ -439,7 +439,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
end
end
-class MetalIntegrationTest < ActionController::IntegrationTest
+class MetalIntegrationTest < ActionDispatch::IntegrationTest
include SharedTestRoutes.url_helpers
class Poller
@@ -476,7 +476,7 @@ class MetalIntegrationTest < ActionController::IntegrationTest
end
end
-class ApplicationIntegrationTest < ActionController::IntegrationTest
+class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
def index
render :text => "index"
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index 165c61ffad..cafe2b9320 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -46,13 +46,13 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
def test_application_layout_is_default_when_no_controller_match
@controller = ProductController.new
get :hello
- assert_equal 'layout_test.rhtml hello.rhtml', @response.body
+ 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.rhtml hello.rhtml', @response.body
+ assert_equal 'item.erb hello.erb', @response.body
end
def test_third_party_template_library_auto_discovers_layout
@@ -65,13 +65,13 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
def test_namespaced_controllers_auto_detect_layouts1
@controller = ControllerNameSpace::NestedController.new
get :hello
- assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body
+ 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.rhtml', @response.body.strip
+ assert_equal 'multiple_extensions.html.erb hello.erb', @response.body.strip
end
end
@@ -79,7 +79,7 @@ class DefaultLayoutController < LayoutTest
end
class AbsolutePathLayoutController < LayoutTest
- layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.rhtml')
+ layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.erb')
end
class HasOwnLayoutController < LayoutTest
@@ -115,7 +115,7 @@ end
class LayoutSetInResponseTest < ActionController::TestCase
include ActionView::Template::Handlers
-
+
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
get :hello
@@ -127,7 +127,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
get :hello
assert_template :layout => "layouts/item"
end
-
+
def test_layout_only_exception_when_included
@controller = OnlyLayoutController.new
get :hello
@@ -137,7 +137,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_only_exception_when_excepted
@controller = OnlyLayoutController.new
get :goodbye
- assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'"
+ assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'"
end
def test_layout_except_exception_when_included
@@ -149,7 +149,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_except_exception_when_excepted
@controller = ExceptLayoutController.new
get :goodbye
- assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'"
+ assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'"
end
def test_layout_set_when_using_render
@@ -173,7 +173,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_absolute_pathed_layout
@controller = AbsolutePathLayoutController.new
get :hello
- assert_equal "layout_test.rhtml hello.rhtml", @response.body.strip
+ assert_equal "layout_test.erb hello.erb", @response.body.strip
end
end
@@ -184,7 +184,7 @@ class RenderWithTemplateOptionController < LayoutTest
end
class SetsNonExistentLayoutFile < LayoutTest
- layout "nofile.rhtml"
+ layout "nofile.erb"
end
class LayoutExceptionRaised < ActionController::TestCase
@@ -208,7 +208,7 @@ class LayoutStatusIsRenderedTest < ActionController::TestCase
end
end
-unless Config::CONFIG['host_os'] =~ /mswin|mingw/
+unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
class LayoutSymlinkedTest < LayoutTest
layout "symlinked/symlinked_layout"
end
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index 0a18741f0c..ddfa3df552 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -16,10 +16,6 @@ module Another
send_data "cool data", :filename => "file.txt"
end
- def xfile_sender
- send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH), :x_sendfile => true
- end
-
def file_sender
send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH)
end
@@ -28,10 +24,19 @@ module Another
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_page_cache
cache_page("Super soaker", "/index.html")
render :nothing => true
end
+
+ def with_exception
+ raise Exception
+ end
+
end
end
@@ -72,8 +77,8 @@ class ACLogSubscriberTest < ActionController::TestCase
get :show
wait
assert_equal 2, logs.size
- assert_match /Completed/, logs.last
- assert_match /200 OK/, logs.last
+ assert_match(/Completed/, logs.last)
+ assert_match(/200 OK/, logs.last)
end
def test_process_action_without_parameters
@@ -93,7 +98,7 @@ class ACLogSubscriberTest < ActionController::TestCase
def test_process_action_with_view_runtime
get :show
wait
- assert_match /\(Views: [\d\.]+ms\)/, logs[1]
+ assert_match(/\(Views: [\d.]+ms\)/, logs[1])
end
def test_process_action_with_filter_parameters
@@ -103,9 +108,9 @@ class ACLogSubscriberTest < ActionController::TestCase
wait
params = logs[1]
- assert_match /"amount"=>"\[FILTERED\]"/, params
- assert_match /"lifo"=>"\[FILTERED\]"/, params
- assert_match /"step"=>"1"/, params
+ assert_match(/"amount"=>"\[FILTERED\]"/, params)
+ assert_match(/"lifo"=>"\[FILTERED\]"/, params)
+ assert_match(/"step"=>"1"/, params)
end
def test_redirect_to
@@ -121,7 +126,7 @@ class ACLogSubscriberTest < ActionController::TestCase
wait
assert_equal 3, logs.size
- assert_match /Sent data file\.txt/, logs[1]
+ assert_match(/Sent data file\.txt/, logs[1])
end
def test_send_file
@@ -129,27 +134,30 @@ class ACLogSubscriberTest < ActionController::TestCase
wait
assert_equal 3, logs.size
- assert_match /Sent file/, logs[1]
- assert_match /test\/fixtures\/company\.rb/, logs[1]
+ assert_match(/Sent file/, logs[1])
+ assert_match(/test\/fixtures\/company\.rb/, logs[1])
end
- def test_send_xfile
- assert_deprecated { get :xfile_sender }
+ def test_with_fragment_cache
+ @controller.config.perform_caching = true
+ get :with_fragment_cache
wait
- assert_equal 3, logs.size
- assert_match /Sent file/, logs[1]
- assert_match /test\/fixtures\/company\.rb/, logs[1]
+ 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
+ def test_with_fragment_cache_and_percent_in_key
@controller.config.perform_caching = true
- get :with_fragment_cache
+ get :with_fragment_cache_and_percent_in_key
wait
assert_equal 4, logs.size
- assert_match /Exist fragment\? views\/foo/, logs[1]
- assert_match /Write fragment views\/foo/, logs[2]
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
ensure
@controller.config.perform_caching = true
end
@@ -160,12 +168,22 @@ class ACLogSubscriberTest < ActionController::TestCase
wait
assert_equal 3, logs.size
- assert_match /Write page/, logs[1]
- assert_match /\/index\.html/, logs[1]
+ assert_match(/Write page/, logs[1])
+ assert_match(/\/index\.html/, logs[1])
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 logs
@logs ||= @logger.logged(:info)
end
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index b5ce391b61..5debf96232 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -2,6 +2,14 @@ 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
@@ -36,7 +44,7 @@ class RespondToController < ActionController::Base
type.all { render :text => "Nothing" }
end
end
-
+
def json_xml_or_html
respond_to do |type|
type.json { render :text => 'JSON' }
@@ -44,7 +52,7 @@ class RespondToController < ActionController::Base
type.html { render :text => 'HTML' }
end
end
-
+
def forced_xml
request.format = :xml
@@ -89,7 +97,6 @@ class RespondToController < ActionController::Base
end
end
- Mime::Type.register("text/x-mobile", :mobile)
def custom_constant_handling
respond_to do |type|
@@ -126,7 +133,6 @@ class RespondToController < ActionController::Base
end
end
- Mime::Type.register_alias("text/html", :iphone)
def iphone_with_html_response_type
request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone"
@@ -160,16 +166,43 @@ class RespondToController < ActionController::Base
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
@@ -216,6 +249,16 @@ class RespondToControllerTest < ActionController::TestCase
assert_response 406
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
@@ -373,17 +416,17 @@ class RespondToControllerTest < ActionController::TestCase
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_rjs_type_skips_layout
@request.accept = "text/javascript"
@@ -487,6 +530,10 @@ class RespondWithController < ActionController::Base
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" }
@@ -518,7 +565,7 @@ class RespondWithController < ActionController::Base
def using_resource_with_action
respond_with(resource, :action => :foo) do |format|
- format.html { raise ActionView::MissingTemplate.new([], "foo/bar", {}, false) }
+ format.html { raise ActionView::MissingTemplate.new([], "bar", ["foo"], {}, false) }
end
end
@@ -552,6 +599,17 @@ class InheritedRespondWithController < RespondWithController
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
+end
+
class EmptyRespondWithController < ActionController::Base
def index
respond_with(Customer.new("david", 13))
@@ -564,10 +622,14 @@ class RespondWithControllerTest < ActionController::TestCase
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_using_resource
@@ -587,6 +649,18 @@ class RespondWithControllerTest < ActionController::TestCase
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_equal %Q[{"result":{"name":"david","id":13}}], @response.body
+ end
+
def test_using_resource_with_block
@request.accept = "*/*"
get :using_resource_with_block
@@ -709,6 +783,15 @@ class RespondWithControllerTest < ActionController::TestCase
assert_equal " ", @response.body
end
+ def test_using_resource_for_put_with_json_yields_ok_on_success
+ Customer.any_instance.stubs(:to_json).returns('{"name": "David"}')
+ @request.accept = "application/json"
+ put :using_resource
+ assert_equal "application/json", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "{}", @response.body
+ end
+
def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure
@request.accept = "application/xml"
errors = { :name => :invalid }
@@ -739,6 +822,16 @@ class RespondWithControllerTest < ActionController::TestCase
assert_equal " ", @response.body
end
+ def test_using_resource_for_delete_with_json_yields_ok_on_success
+ Customer.any_instance.stubs(:to_json).returns('{"name": "David"}')
+ Customer.any_instance.stubs(:destroyed?).returns(true)
+ @request.accept = "application/json"
+ delete :using_resource
+ assert_equal "application/json", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "{}", @response.body
+ end
+
def test_using_resource_for_delete_with_html_redirects_on_failure
with_test_route_set do
errors = { :name => :invalid }
@@ -784,8 +877,8 @@ class RespondWithControllerTest < ActionController::TestCase
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
+ assert_match(/<name>david<\/name>/, @response.body)
+ assert_match(/<name>jamis<\/name>/, @response.body)
end
def test_using_resource_with_action
@@ -834,6 +927,14 @@ class RespondWithControllerTest < ActionController::TestCase
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_no_double_render_is_raised
@request.accept = "text/html"
assert_raise ActionView::MissingTemplate do
@@ -876,7 +977,7 @@ class RespondWithControllerTest < ActionController::TestCase
private
def with_test_route_set
with_routing do |set|
- set.draw do |map|
+ set.draw do
resources :customers
resources :quiz_stores do
resources :customers
@@ -917,6 +1018,12 @@ class MimeControllerLayoutsTest < ActionController::TestCase
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
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index 8a06e8d2a0..3ca29f1bcf 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -24,4 +24,26 @@ module BareMetalTest
assert_equal "Hello world", string
end
end
+
+ class HeadController < ActionController::Metal
+ include ActionController::Head
+
+ def index
+ head :not_found
+ 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
+ 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/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb
index b98a22dfcc..5fd5946619 100644
--- a/actionpack/test/controller/new_base/content_negotiation_test.rb
+++ b/actionpack/test/controller/new_base/content_negotiation_test.rb
@@ -7,6 +7,10 @@ module ContentNegotiation
self.view_paths = [ActionView::FixtureResolver.new(
"content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!"
)]
+
+ def all
+ render :text => self.formats.inspect
+ end
end
class TestContentNegotiation < Rack::TestCase
@@ -14,5 +18,10 @@ module ContentNegotiation
get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*"
assert_body "Hello world */*!"
end
+
+ test "Not all mimes are converted to symbol" do
+ get "/content_negotiation/basic/all", {}, "HTTP_ACCEPT" => "text/plain, mime/another"
+ assert_body '[:text, "mime/another"]'
+ end
end
end
diff --git a/actionpack/test/controller/new_base/content_type_test.rb b/actionpack/test/controller/new_base/content_type_test.rb
index 33c2e442f0..8ba30944f5 100644
--- a/actionpack/test/controller/new_base/content_type_test.rb
+++ b/actionpack/test/controller/new_base/content_type_test.rb
@@ -42,10 +42,16 @@ module ContentType
class ExplicitContentTypeTest < Rack::TestCase
test "default response is HTML and UTF8" do
- get "/content_type/base"
+ with_routing do |set|
+ set.draw do
+ match ':controller', :action => 'index'
+ end
- assert_body "Hello world!"
- assert_header "Content-Type", "text/html; charset=utf-8"
+ 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
diff --git a/actionpack/test/controller/new_base/etag_test.rb b/actionpack/test/controller/new_base/etag_test.rb
deleted file mode 100644
index 51bfb2278a..0000000000
--- a/actionpack/test/controller/new_base/etag_test.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-require 'abstract_unit'
-
-module Etags
- class BasicController < ActionController::Base
- self.view_paths = [ActionView::FixtureResolver.new(
- "etags/basic/base.html.erb" => "Hello from without_layout.html.erb",
- "layouts/etags.html.erb" => "teh <%= yield %> tagz"
- )]
-
- def without_layout
- render :action => "base"
- end
-
- def with_layout
- render :action => "base", :layout => "etags"
- end
- end
-
- class EtagTest < Rack::TestCase
- describe "Rendering without any special etag options returns an etag that is an MD5 hash of its text"
-
- test "an action without a layout" do
- get "/etags/basic/without_layout"
-
- body = "Hello from without_layout.html.erb"
- assert_body body
- assert_header "Etag", etag_for(body)
- assert_status 200
- end
-
- test "an action with a layout" do
- get "/etags/basic/with_layout"
-
- body = "teh Hello from without_layout.html.erb tagz"
- assert_body body
- assert_header "Etag", etag_for(body)
- assert_status 200
- end
-
- private
-
- def etag_for(text)
- %("#{Digest::MD5.hexdigest(text)}")
- end
- end
-end
diff --git a/actionpack/test/controller/new_base/middleware_test.rb b/actionpack/test/controller/new_base/middleware_test.rb
index 26a66c91a6..ccef060863 100644
--- a/actionpack/test/controller/new_base/middleware_test.rb
+++ b/actionpack/test/controller/new_base/middleware_test.rb
@@ -25,8 +25,25 @@ module MiddlewareTest
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
@@ -67,6 +84,11 @@ module MiddlewareTest
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"]
diff --git a/actionpack/test/controller/new_base/render_action_test.rb b/actionpack/test/controller/new_base/render_action_test.rb
index d92e9c4bf2..aa44e0b282 100644
--- a/actionpack/test/controller/new_base/render_action_test.rb
+++ b/actionpack/test/controller/new_base/render_action_test.rb
@@ -83,6 +83,9 @@ module RenderAction
end
class RenderLayoutTest < Rack::TestCase
+ def setup
+ end
+
describe "Both <controller_path>.html.erb and application.html.erb are missing"
test "rendering with layout => true" do
diff --git a/actionpack/test/controller/new_base/render_implicit_action_test.rb b/actionpack/test/controller/new_base/render_implicit_action_test.rb
index 90cc7933ff..9f69d20329 100644
--- a/actionpack/test/controller/new_base/render_implicit_action_test.rb
+++ b/actionpack/test/controller/new_base/render_implicit_action_test.rb
@@ -6,10 +6,10 @@ module RenderImplicitAction
"render_implicit_action/simple/hello_world.html.erb" => "Hello world!",
"render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!"
)]
-
+
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"
diff --git a/actionpack/test/controller/new_base/render_layout_test.rb b/actionpack/test/controller/new_base/render_layout_test.rb
index 372fb66b88..bb2a953536 100644
--- a/actionpack/test/controller/new_base/render_layout_test.rb
+++ b/actionpack/test/controller/new_base/render_layout_test.rb
@@ -71,7 +71,7 @@ module ControllerLayouts
self.view_paths = [ActionView::FixtureResolver.new(
"layouts/application.html.erb" => "<html><%= yield %></html>",
"controller_layouts/mismatch_format/index.js.rjs" => "page[:test].ext",
- "controller_layouts/mismatch_format/implicit.rjs" => "page[:test].ext"
+ "controller_layouts/mismatch_format/implicit.rjs" => "page[:test].ext"
)]
def explicit
diff --git a/actionpack/test/controller/new_base/render_once_test.rb b/actionpack/test/controller/new_base/render_once_test.rb
new file mode 100644
index 0000000000..175abf8a7e
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_once_test.rb
@@ -0,0 +1,86 @@
+require 'abstract_unit'
+
+module RenderTemplate
+ class RenderOnceController < ActionController::Base
+ layout false
+
+ RESOLVER = ActionView::FixtureResolver.new(
+ "test/a.html.erb" => "a",
+ "test/b.html.erb" => "<>",
+ "test/c.html.erb" => "c",
+ "test/one.html.erb" => "<%= render :once => 'result' %>",
+ "test/two.html.erb" => "<%= render :once => 'result' %>",
+ "test/three.html.erb" => "<%= render :once => 'result' %>",
+ "test/result.html.erb" => "YES!",
+ "other/result.html.erb" => "NO!",
+ "layouts/test.html.erb" => "l<%= yield %>l"
+ )
+
+ self.view_paths = [RESOLVER]
+
+ def _prefixes
+ %w(test)
+ end
+
+ def multiple
+ render :once => %w(a b c)
+ end
+
+ def once
+ render :once => %w(one two three)
+ end
+
+ def duplicate
+ render :once => %w(a a a)
+ end
+
+ def with_layout
+ render :once => %w(a b c), :layout => "test"
+ end
+
+ def with_prefix
+ render :once => "result", :prefixes => %w(other)
+ end
+
+ def with_nil_prefix
+ render :once => "test/result", :prefixes => []
+ end
+ end
+
+ module Tests
+ def test_mutliple_arguments_get_all_rendered
+ get :multiple
+ assert_response "a\n<>\nc"
+ end
+
+ def test_referenced_templates_get_rendered_once
+ get :once
+ assert_response "YES!\n\n"
+ end
+
+ def test_duplicated_templates_get_rendered_once
+ get :duplicate
+ assert_response "a"
+ end
+
+ def test_layout_wraps_all_rendered_templates
+ get :with_layout
+ assert_response "la\n<>\ncl"
+ end
+
+ def test_with_prefix_option
+ get :with_prefix
+ assert_response "NO!"
+ end
+
+ def test_with_nil_prefix_option
+ get :with_nil_prefix
+ assert_response "YES!"
+ end
+ end
+
+ class TestRenderOnce < Rack::TestCase
+ testing RenderTemplate::RenderOnceController
+ include Tests
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb
index 1a1b36a65e..83b0d039ad 100644
--- a/actionpack/test/controller/new_base/render_partial_test.rb
+++ b/actionpack/test/controller/new_base/render_partial_test.rb
@@ -1,27 +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/_basic.html.erb" => "BasicPartial!",
+ "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>",
+ "render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>",
+ "render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>",
+ "render_partial/basic/_final.json.erb" => "{ final: json }",
+ "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>",
+ "render_partial/basic/_overriden.html.erb" => "ParentPartial!",
+ "render_partial/child/_overriden.html.erb" => "OverridenPartial!"
)]
-
+
+ def html_with_json_inside_json
+ render :action => "with_json"
+ end
+
def changing
@test_unchanged = 'hello'
render :action => "basic"
- end
+ end
+
+ def overriden
+ @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 :overriden
+ assert_response("goodbyeOverridenPartial!goodbye")
+ 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
index 70cebbfd89..584f2d772c 100644
--- a/actionpack/test/controller/new_base/render_template_test.rb
+++ b/actionpack/test/controller/new_base/render_template_test.rb
@@ -4,17 +4,26 @@ 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>' %>"
+ "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>' %>",
+ "test/with_json.html.erb" => "<%= render :template => 'test/with_json.json' %>",
+ "test/with_json.json.erb" => "<%= render :template => 'test/final' %>",
+ "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
@@ -42,6 +51,14 @@ module RenderTemplate
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
end
class TestWithoutLayout < Rack::TestCase
@@ -87,6 +104,23 @@ module RenderTemplate
assert_body "Hello <strong>this is raw</strong>"
assert_status 200
+
+ get :with_implicit_raw
+
+ assert_body "Hello <strong>this is also raw</strong>"
+ 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 exceprts the code" do
+ get :with_error
+ assert_status 500
+ assert_match "undefined local variable or method `idontexist'", response.body
end
end
@@ -123,10 +157,14 @@ module RenderTemplate
describe "Rendering with :template using implicit or explicit layout"
test "rendering with implicit layout" do
- get "/render_template/with_layout"
+ with_routing do |set|
+ set.draw { match ':controller', :action => :index }
- assert_body "Hello from basic.html.erb, I'm here!"
- assert_status 200
+ 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
diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb
index d985d9f9ad..d6062bfa8c 100644
--- a/actionpack/test/controller/new_base/render_test.rb
+++ b/actionpack/test/controller/new_base/render_test.rb
@@ -6,7 +6,11 @@ module Render
"render/blank_render/index.html.erb" => "Hello world!",
"render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>",
"render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>",
- "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>"
+ "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>",
+ "render/blank_render/overriden_with_own_view_paths_appended.html.erb" => "parent content",
+ "render/blank_render/overriden_with_own_view_paths_prepended.html.erb" => "parent content",
+ "render/blank_render/overriden.html.erb" => "parent content",
+ "render/child_render/overriden.html.erb" => "child content"
)]
def index
@@ -21,6 +25,15 @@ module Render
render :action => "access_action_name"
end
+ def overriden_with_own_view_paths_appended
+ end
+
+ def overriden_with_own_view_paths_prepended
+ end
+
+ def overriden
+ end
+
private
def secretz
@@ -35,17 +48,34 @@ module Render
end
end
+ class ChildRenderController < BlankRenderController
+ append_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_appended.html.erb" => "child content")
+ prepend_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_prepended.html.erb" => "child content")
+ end
+
class RenderTest < Rack::TestCase
test "render with blank" do
- get "/render/blank_render"
+ with_routing do |set|
+ set.draw do
+ match ":controller", :action => 'index'
+ end
- assert_body "Hello world!"
- assert_status 200
+ get "/render/blank_render"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
end
test "rendering more than once raises an exception" do
- assert_raises(AbstractController::DoubleRenderError) do
- get "/render/double_render", {}, "action_dispatch.show_exceptions" => false
+ with_routing do |set|
+ set.draw do
+ match ":controller", :action => 'index'
+ end
+
+ assert_raises(AbstractController::DoubleRenderError) do
+ get "/render/double_render", {}, "action_dispatch.show_exceptions" => false
+ end
end
end
end
@@ -65,7 +95,7 @@ module Render
end
end
end
-
+
class TestVariousObjectsAvailableInView < Rack::TestCase
test "The request object is accessible in the view" do
get "/render/blank_render/access_request"
@@ -82,4 +112,26 @@ module Render
assert_body "Controller Name: blank_render"
end
end
+
+ class TestViewInheritance < Rack::TestCase
+ test "Template from child controller gets picked over parent one" do
+ get "/render/child_render/overriden"
+ assert_body "child content"
+ end
+
+ test "Template from child controller with custom view_paths prepended gets picked over parent one" do
+ get "/render/child_render/overriden_with_own_view_paths_prepended"
+ assert_body "child content"
+ end
+
+ test "Template from child controller with custom view_paths appended gets picked over parent one" do
+ get "/render/child_render/overriden_with_own_view_paths_appended"
+ assert_body "child content"
+ end
+
+ test "Template from parent controller gets picked if missing in child controller" do
+ get "/render/child_render/index"
+ assert_body "Hello world!"
+ end
+ end
end
diff --git a/actionpack/test/controller/new_base/render_text_test.rb b/actionpack/test/controller/new_base/render_text_test.rb
index 0e6f51c998..06d500cca7 100644
--- a/actionpack/test/controller/new_base/render_text_test.rb
+++ b/actionpack/test/controller/new_base/render_text_test.rb
@@ -3,7 +3,7 @@ require 'abstract_unit'
module RenderText
class SimpleController < ActionController::Base
self.view_paths = [ActionView::FixtureResolver.new]
-
+
def index
render :text => "hello david"
end
@@ -14,24 +14,24 @@ module RenderText
"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
@@ -39,23 +39,23 @@ module RenderText
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"
@@ -66,16 +66,24 @@ module RenderText
describe "Rendering text using render :text"
test "rendering text from a action with default options renders the text with the layout" do
- get "/render_text/simple"
- assert_body "hello david"
- assert_status 200
+ with_routing do |set|
+ set.draw { match ':controller', :action => 'index' }
+
+ get "/render_text/simple"
+ assert_body "hello david"
+ assert_status 200
+ end
end
test "rendering text from a action with default options renders the text without the layout" do
- get "/render_text/with_layout"
+ with_routing do |set|
+ set.draw { match ':controller', :action => 'index' }
- assert_body "hello david"
- assert_status 200
+ 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
diff --git a/actionpack/test/controller/new_base/render_xml_test.rb b/actionpack/test/controller/new_base/render_xml_test.rb
index d044738a78..b8527a943d 100644
--- a/actionpack/test/controller/new_base/render_xml_test.rb
+++ b/actionpack/test/controller/new_base/render_xml_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
module RenderXml
-
+
# This has no layout and it works
class BasicController < ActionController::Base
self.view_paths = [ActionView::FixtureResolver.new(
diff --git a/actionpack/test/controller/output_escaping_test.rb b/actionpack/test/controller/output_escaping_test.rb
index 43a8c05cda..f6913a2138 100644
--- a/actionpack/test/controller/output_escaping_test.rb
+++ b/actionpack/test/controller/output_escaping_test.rb
@@ -3,7 +3,7 @@ require 'abstract_unit'
class OutputEscapingTest < ActiveSupport::TestCase
test "escape_html shouldn't die when passed nil" do
- assert ERB::Util.h(nil).blank?
+ assert_blank ERB::Util.h(nil)
end
test "escapeHTML should escape strings" do
diff --git a/actionpack/test/controller/record_identifier_test.rb b/actionpack/test/controller/record_identifier_test.rb
index 835a0e970b..f3e5ff8a47 100644
--- a/actionpack/test/controller/record_identifier_test.rb
+++ b/actionpack/test/controller/record_identifier_test.rb
@@ -1,30 +1,5 @@
require 'abstract_unit'
-
-class Comment
- 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 comment' : "comment ##{@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
+require 'controller/fake_models'
class RecordIdentifierTest < Test::Unit::TestCase
include ActionController::RecordIdentifier
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index 441bc47908..92d4a6d98b 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -3,24 +3,6 @@ require 'abstract_unit'
class WorkshopsController < ActionController::Base
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
-
class RedirectController < ActionController::Base
def simple_redirect
redirect_to :action => "hello_world"
@@ -99,6 +81,19 @@ class RedirectController < ActionController::Base
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 rescue_errors(e) raise e end
def rescue_action(e) raise end
@@ -232,7 +227,7 @@ class RedirectTest < ActionController::TestCase
def test_redirect_to_record
with_routing do |set|
- set.draw do |map|
+ set.draw do
resources :workshops
match ':controller/:action'
end
@@ -252,6 +247,31 @@ class RedirectTest < ActionController::TestCase
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
+ match ':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
diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb
index 5958b18d80..fc604a2db3 100644
--- a/actionpack/test/controller/render_json_test.rb
+++ b/actionpack/test/controller/render_json_test.rb
@@ -9,6 +9,10 @@ class RenderJsonTest < ActionController::TestCase
hash.except!(*options[:except]) if options[:except]
hash
end
+
+ def to_json(options = {})
+ super :except => [:c, :e]
+ end
end
class TestController < ActionController::Base
@@ -22,6 +26,10 @@ class RenderJsonTest < ActionController::TestCase
render :json => nil
end
+ def render_json_render_to_string
+ render :text => render_to_string(:json => '[]')
+ end
+
def render_json_hello_world
render :json => ActiveSupport::JSON.encode(:hello => 'world')
end
@@ -49,6 +57,10 @@ class RenderJsonTest < ActionController::TestCase
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
@@ -68,6 +80,12 @@ class RenderJsonTest < ActionController::TestCase
assert_equal 'application/json', @response.content_type
end
+ def test_render_json_render_to_string
+ get :render_json_render_to_string
+ assert_equal '[]', @response.body
+ end
+
+
def test_render_json
get :render_json_hello_world
assert_equal '{"hello":"world"}', @response.body
@@ -109,4 +127,9 @@ class RenderJsonTest < ActionController::TestCase
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
index dfc4f2db8c..eda777e7a7 100644
--- a/actionpack/test/controller/render_other_test.rb
+++ b/actionpack/test/controller/render_other_test.rb
@@ -120,6 +120,7 @@ class RenderOtherTest < ActionController::TestCase
private
def default_render
+ @alternate_default_render ||= nil
if @alternate_default_render
@alternate_default_render.call
else
@@ -224,15 +225,15 @@ class RenderOtherTest < ActionController::TestCase
get :update_page_with_instance_variables
assert_template nil
assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"]
- assert_match /balance/, @response.body
- assert_match /\$37/, @response.body
+ assert_match(/balance/, @response.body)
+ assert_match(/\$37/, @response.body)
end
def test_update_page_with_view_method
get :update_page_with_view_method
assert_template nil
assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"]
- assert_match /2 people/, @response.body
+ assert_match(/2 people/, @response.body)
end
def test_should_render_html_formatted_partial_with_rjs
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index a57a12f271..be492152f2 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -7,7 +7,7 @@ module Fun
# :ported:
def hello_world
end
-
+
def nested_partial_with_form_builder
render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}, Proc.new {})
end
@@ -99,11 +99,6 @@ class TestController < ActionController::Base
render :template => "test/hello_world"
end
- def render_hello_world_with_etag_set
- response.etag = "hello_world"
- render :template => "test/hello_world"
- end
-
# :ported: compatibility
def render_hello_world_with_forward_slash
render :template => "/test/hello_world"
@@ -130,6 +125,10 @@ class TestController < ActionController::Base
render :action => "hello_world"
end
+ def render_action_upcased_hello_world
+ render :action => "Hello_world"
+ end
+
def render_action_hello_world_as_string
render "hello_world"
end
@@ -276,6 +275,7 @@ class TestController < ActionController::Base
# :ported:
def builder_layout_test
+ @name = nil
render :action => "hello", :layout => "layouts/builder"
end
@@ -327,6 +327,7 @@ class TestController < ActionController::Base
end
def default_render
+ @alternate_default_render ||= nil
if @alternate_default_render
@alternate_default_render.call
else
@@ -339,14 +340,17 @@ class TestController < ActionController::Base
end
def layout_test_with_different_layout
+ @variable_for_layout = nil
render :action => "hello_world", :layout => "standard"
end
def layout_test_with_different_layout_and_string_action
+ @variable_for_layout = nil
render "hello_world", :layout => "standard"
end
def layout_test_with_different_layout_and_symbol_action
+ @variable_for_layout = nil
render :hello_world, :layout => "standard"
end
@@ -355,6 +359,7 @@ class TestController < ActionController::Base
end
def layout_overriding_layout
+ @variable_for_layout = nil
render :action => "hello_world", :layout => "standard"
end
@@ -488,6 +493,10 @@ class TestController < ActionController::Base
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
@@ -639,6 +648,7 @@ class TestController < ActionController::Base
private
def determine_layout
+ @variable_for_layout ||= nil
case action_name
when "hello_world", "layout_test", "rendering_without_layout",
"rendering_nothing_on_layout", "render_text_hello_world",
@@ -736,6 +746,12 @@ class RenderTest < ActionController::TestCase
assert_template "test/hello_world"
end
+ def test_render_action_upcased
+ assert_raise ActionView::MissingTemplate do
+ get :render_action_upcased_hello_world
+ end
+ end
+
# :ported:
def test_render_action_hello_world_as_string
get :render_action_hello_world_as_string
@@ -1016,7 +1032,7 @@ class RenderTest < ActionController::TestCase
assert_equal " ", @response.body
end
- def test_render_to_string
+ def test_render_to_string_not_deprecated
assert_not_deprecated { get :hello_in_a_string }
assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
end
@@ -1113,20 +1129,20 @@ class RenderTest < ActionController::TestCase
def test_head_with_location_header
get :head_with_location_header
- assert @response.body.blank?
+ assert_blank @response.body
assert_equal "/foo", @response.headers["Location"]
assert_response :ok
end
def test_head_with_location_object
with_routing do |set|
- set.draw do |map|
+ set.draw do
resources :customers
match ':controller/:action'
end
get :head_with_location_object
- assert @response.body.blank?
+ assert_blank @response.body
assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"]
assert_response :ok
end
@@ -1134,11 +1150,18 @@ class RenderTest < ActionController::TestCase
def test_head_with_custom_header
get :head_with_custom_header
- assert @response.body.blank?
+ assert_blank @response.body
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_blank @response.body
+ 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
@@ -1234,7 +1257,7 @@ class RenderTest < ActionController::TestCase
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
@@ -1368,119 +1391,6 @@ class ExpiresInRenderTest < ActionController::TestCase
end
end
-
-class EtagRenderTest < ActionController::TestCase
- tests TestController
-
- def setup
- super
- @request.host = "www.nextangle.com"
- @expected_bang_etag = etag_for(expand_key([:foo, 123]))
- end
-
- def test_render_blank_body_shouldnt_set_etag
- get :blank_response
- assert !@response.etag?
- end
-
- def test_render_200_should_set_etag
- get :render_hello_world_from_variable
- assert_equal etag_for("hello david"), @response.headers['ETag']
- assert_equal "max-age=0, private, must-revalidate", @response.headers['Cache-Control']
- end
-
- def test_render_against_etag_request_should_304_when_match
- @request.if_none_match = etag_for("hello david")
- get :render_hello_world_from_variable
- assert_equal 304, @response.status.to_i
- assert @response.body.empty?
- end
-
- def test_render_against_etag_request_should_have_no_content_length_when_match
- @request.if_none_match = etag_for("hello david")
- get :render_hello_world_from_variable
- assert !@response.headers.has_key?("Content-Length")
- end
-
- def test_render_against_etag_request_should_200_when_no_match
- @request.if_none_match = etag_for("hello somewhere else")
- get :render_hello_world_from_variable
- assert_equal 200, @response.status.to_i
- assert !@response.body.empty?
- end
-
- def test_render_should_not_set_etag_when_last_modified_has_been_specified
- get :render_hello_world_with_last_modified_set
- assert_equal 200, @response.status.to_i
- assert_not_nil @response.last_modified
- assert_nil @response.etag
- assert @response.body.present?
- end
-
- def test_render_with_etag
- get :render_hello_world_from_variable
- expected_etag = etag_for('hello david')
- assert_equal expected_etag, @response.headers['ETag']
- @response = ActionController::TestResponse.new
-
- @request.if_none_match = expected_etag
- get :render_hello_world_from_variable
- assert_equal 304, @response.status.to_i
-
- @response = ActionController::TestResponse.new
- @request.if_none_match = "\"diftag\""
- get :render_hello_world_from_variable
- assert_equal 200, @response.status.to_i
- end
-
- def render_with_404_shouldnt_have_etag
- get :render_custom_code
- assert_nil @response.headers['ETag']
- end
-
- def test_etag_should_not_be_changed_when_already_set
- get :render_hello_world_with_etag_set
- assert_equal etag_for("hello_world"), @response.headers['ETag']
- end
-
- def test_etag_should_govern_renders_with_layouts_too
- 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
- assert_equal etag_for("<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n"), @response.headers['ETag']
- end
-
- def test_etag_with_bang_should_set_etag
- get :conditional_hello_with_bangs
- assert_equal @expected_bang_etag, @response.headers["ETag"]
- assert_response :success
- end
-
- def test_etag_with_bang_should_obey_if_none_match
- @request.if_none_match = @expected_bang_etag
- get :conditional_hello_with_bangs
- assert_response :not_modified
- end
-
- def test_etag_with_public_true_should_set_header
- get :conditional_hello_with_public_header
- assert_equal "public", @response.headers['Cache-Control']
- end
-
- def test_etag_with_public_true_should_set_header_and_retain_other_headers
- get :conditional_hello_with_public_header_and_expires_at
- assert_equal "max-age=60, public", @response.headers['Cache-Control']
- end
-
- protected
- def etag_for(text)
- %("#{Digest::MD5.hexdigest(text)}")
- end
-
- def expand_key(args)
- ActiveSupport::Cache.expand_cache_key(args)
- end
-end
-
class LastModifiedRenderTest < ActionController::TestCase
tests TestController
@@ -1499,7 +1409,7 @@ class LastModifiedRenderTest < ActionController::TestCase
@request.if_modified_since = @last_modified
get :conditional_hello
assert_equal 304, @response.status.to_i
- assert @response.body.blank?, @response.body
+ assert_blank @response.body
assert_equal @last_modified, @response.headers['Last-Modified']
end
@@ -1514,7 +1424,7 @@ class LastModifiedRenderTest < ActionController::TestCase
@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.blank?
+ assert_present @response.body
assert_equal @last_modified, @response.headers['Last-Modified']
end
diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb
index 4bf867fa41..ec4dc848ff 100644
--- a/actionpack/test/controller/render_xml_test.rb
+++ b/actionpack/test/controller/render_xml_test.rb
@@ -70,10 +70,9 @@ class RenderXmlTest < ActionController::TestCase
def test_rendering_with_object_location_should_set_header_with_url_for
with_routing do |set|
- set.draw do |map|
+ set.draw do
resources :customers
- # match ':controller/:action'
- map.connect ':controller/:action/:id'
+ match ':controller/:action'
end
get :render_with_object_location
diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb
index 0a39feb7fe..e624f11773 100644
--- a/actionpack/test/controller/request/test_request_test.rb
+++ b/actionpack/test/controller/request/test_request_test.rb
@@ -29,8 +29,7 @@ class ActionController::TestRequestTest < ActiveSupport::TestCase
end
def test_session_id_different_on_each_call
- prev_id =
assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id])
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index be05ef6167..d520b5e512 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'digest/sha1'
+require 'active_support/core_ext/string/strip'
# common controller actions
module RequestForgeryProtectionActions
@@ -11,12 +12,28 @@ module RequestForgeryProtectionActions
render :inline => "<%= button_to('New', '/') {} %>"
end
+ def external_form
+ render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>"
+ end
+
+ def external_form_without_protection
+ render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>"
+ end
+
def unsafe
render :text => 'pwn'
end
def meta
- render :inline => "<%= csrf_meta_tag %>"
+ render :inline => "<%= csrf_meta_tags %>"
+ end
+
+ def external_form_for
+ render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>"
+ end
+
+ def form_for_without_protection
+ render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>"
end
def rescue_action(e) raise e end
@@ -28,6 +45,16 @@ class RequestForgeryProtectionController < ActionController::Base
protect_from_forgery :only => %w(index meta)
end
+class RequestForgeryProtectionControllerUsingOldBehaviour < ActionController::Base
+ include RequestForgeryProtectionActions
+ protect_from_forgery :only => %w(index meta)
+
+ def handle_unverified_request
+ raise(ActionController::InvalidAuthenticityToken)
+ end
+end
+
+
class FreeCookieController < RequestForgeryProtectionController
self.allow_forgery_protection = false
@@ -50,153 +77,92 @@ end
# common test methods
module RequestForgeryProtectionTests
- def teardown
- ActionController::Base.request_forgery_protection_token = nil
- end
-
-
- def test_should_render_form_with_token_tag
- get :index
- assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
- end
-
- def test_should_render_button_to_with_token_tag
- get :show_button
- assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
- end
-
- def test_should_allow_get
- get :index
- assert_response :success
- end
-
- def test_should_allow_post_without_token_on_unsafe_action
- post :unsafe
- assert_response :success
- end
-
- def test_should_not_allow_html_post_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html }
- end
-
- def test_should_not_allow_html_put_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html }
- end
-
- def test_should_not_allow_html_delete_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html }
- end
+ def setup
+ @token = "cf50faa3fe97702ca1ae"
- def test_should_allow_api_formatted_post_without_token
- assert_nothing_raised do
- post :index, :format => 'xml'
- end
+ ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
+ ActionController::Base.request_forgery_protection_token = :authenticity_token
end
- def test_should_not_allow_api_formatted_put_without_token
- assert_nothing_raised do
- put :index, :format => 'xml'
- end
- end
- def test_should_allow_api_formatted_delete_without_token
- assert_nothing_raised do
- delete :index, :format => 'xml'
+ def test_should_render_form_with_token_tag
+ assert_not_blocked do
+ get :index
end
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
end
- def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- post :index, :format => 'xml'
+ def test_should_render_button_to_with_token_tag
+ assert_not_blocked do
+ get :show_button
end
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
end
- def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- put :index, :format => 'xml'
- end
+ def test_should_allow_get
+ assert_not_blocked { get :index }
end
- def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- delete :index, :format => 'xml'
- end
+ def test_should_allow_post_without_token_on_unsafe_action
+ assert_not_blocked { post :unsafe }
end
- def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
- post :index, :format => 'xml'
- end
+ def test_should_not_allow_post_without_token
+ assert_blocked { post :index }
end
- def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
- put :index, :format => 'xml'
- end
+ def test_should_not_allow_post_without_token_irrespective_of_format
+ assert_blocked { post :index, :format=>'xml' }
end
- def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
- delete :index, :format => 'xml'
- end
+ def test_should_not_allow_put_without_token
+ assert_blocked { put :index }
end
- def test_should_allow_xhr_post_without_token
- assert_nothing_raised { xhr :post, :index }
+ def test_should_not_allow_delete_without_token
+ assert_blocked { delete :index }
end
- def test_should_allow_xhr_put_without_token
- assert_nothing_raised { xhr :put, :index }
+ def test_should_not_allow_xhr_post_without_token
+ assert_blocked { xhr :post, :index }
end
- def test_should_allow_xhr_delete_without_token
- assert_nothing_raised { xhr :delete, :index }
+ def test_should_allow_post_with_token
+ assert_not_blocked { post :index, :authenticity_token => @token }
end
- def test_should_allow_xhr_post_with_encoded_form_content_type_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_nothing_raised { xhr :post, :index }
+ def test_should_allow_put_with_token
+ assert_not_blocked { put :index, :authenticity_token => @token }
end
- def test_should_allow_post_with_token
- post :index, :authenticity_token => @token
- assert_response :success
+ def test_should_allow_delete_with_token
+ assert_not_blocked { delete :index, :authenticity_token => @token }
end
- def test_should_allow_put_with_token
- put :index, :authenticity_token => @token
- assert_response :success
+ def test_should_allow_post_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { post :index }
end
- def test_should_allow_delete_with_token
- delete :index, :authenticity_token => @token
- assert_response :success
+ def test_should_allow_delete_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { delete :index }
end
- def test_should_allow_post_with_xml
- @request.env['CONTENT_TYPE'] = Mime::XML.to_s
- post :index, :format => 'xml'
- assert_response :success
+ def test_should_allow_put_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { put :index }
end
- def test_should_allow_put_with_xml
- @request.env['CONTENT_TYPE'] = Mime::XML.to_s
- put :index, :format => 'xml'
+ def assert_blocked
+ session[:something_like_user_id] = 1
+ yield
+ assert_nil session[:something_like_user_id], "session values are still present"
assert_response :success
end
- def test_should_allow_delete_with_xml
- @request.env['CONTENT_TYPE'] = Mime::XML.to_s
- delete :index, :format => 'xml'
+ def assert_not_blocked
+ assert_nothing_raised { yield }
assert_response :success
end
end
@@ -205,21 +171,23 @@ end
class RequestForgeryProtectionControllerTest < ActionController::TestCase
include RequestForgeryProtectionTests
- def setup
- @controller = RequestForgeryProtectionController.new
- @request = ActionController::TestRequest.new
- @request.format = :html
- @response = ActionController::TestResponse.new
- @token = "cf50faa3fe97702ca1ae"
-
- ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
- ActionController::Base.request_forgery_protection_token = :authenticity_token
- end
test 'should emit a csrf-token meta tag' do
ActiveSupport::SecureRandom.stubs(:base64).returns(@token + '<=?')
get :meta
- assert_equal %(<meta name="csrf-param" content="authenticity_token"/>\n<meta name="csrf-token" content="cf50faa3fe97702ca1ae&lt;=?"/>), @response.body
+ assert_equal <<-METAS.strip_heredoc.chomp, @response.body
+ <meta name="csrf-param" content="authenticity_token"/>
+ <meta name="csrf-token" content="cf50faa3fe97702ca1ae&lt;=?"/>
+ METAS
+ end
+end
+
+class RequestForgeryProtectionControllerUsingOldBehaviourTest < ActionController::TestCase
+ include RequestForgeryProtectionTests
+ def assert_blocked
+ assert_raises(ActionController::InvalidAuthenticityToken) do
+ yield
+ end
end
end
@@ -251,17 +219,27 @@ class FreeCookieControllerTest < ActionController::TestCase
test 'should not emit a csrf-token meta tag' do
get :meta
- assert @response.body.blank?
+ assert_blank @response.body
end
end
+
+
+
+
class CustomAuthenticityParamControllerTest < ActionController::TestCase
def setup
+ ActionController::Base.request_forgery_protection_token = :custom_token_name
+ super
+ end
+
+ def teardown
ActionController::Base.request_forgery_protection_token = :authenticity_token
+ super
end
def test_should_allow_custom_token
- post :index, :authenticity_token => 'foobar'
+ post :index, :custom_token_name => 'foobar'
assert_response :ok
end
end
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index a24de62b19..c445285538 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -1,19 +1,5 @@
require 'abstract_unit'
-module ActionDispatch
- class ShowExceptions
- private
- def public_path
- "#{FIXTURE_LOAD_PATH}/public"
- end
-
- # Silence logger
- def logger
- nil
- end
- end
-end
-
class RescueController < ActionController::Base
class NotAuthorized < StandardError
end
@@ -149,7 +135,7 @@ class RescueController < ActionController::Base
def missing_template
end
-
+
def io_error_in_view
raise ActionView::TemplateError.new(nil, {}, IOError.new('this is io error'))
end
@@ -311,7 +297,7 @@ class RescueControllerTest < ActionController::TestCase
end
end
-class RescueTest < ActionController::IntegrationTest
+class RescueTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
class RecordInvalid < StandardError
def message
@@ -371,7 +357,7 @@ class RescueTest < ActionController::IntegrationTest
private
def with_test_routing
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'foo', :to => ::RescueTest::TestController.action(:foo)
match 'invalid', :to => ::RescueTest::TestController.action(:invalid)
match 'b00m', :to => ::RescueTest::TestController.action(:b00m)
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index 6c8f470fba..acb4617a60 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -1,5 +1,6 @@
-require 'active_support/core_ext/object/try'
require 'abstract_unit'
+require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/object/with_options'
class ResourcesController < ActionController::Base
def index() render :nothing => true end
@@ -32,36 +33,6 @@ module Backoffice
end
class ResourcesTest < ActionController::TestCase
- def test_should_arrange_actions
- resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {
- :collection => { :rss => :get, :reorder => :post, :csv => :post },
- :member => { :rss => :get, :atom => :get, :upload => :post, :fix => :post },
- :new => { :preview => :get, :draft => :get }}, {})
-
- assert_resource_methods [:rss], resource, :collection, :get
- assert_resource_methods [:csv, :reorder], resource, :collection, :post
- assert_resource_methods [:edit, :rss, :atom], resource, :member, :get
- assert_resource_methods [:upload, :fix], resource, :member, :post
- assert_resource_methods [:new, :preview, :draft], resource, :new, :get
- end
-
- def test_should_resource_controller_name_equal_resource_name_by_default
- resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {}, {})
- assert_equal 'messages', resource.controller
- end
-
- def test_should_resource_controller_name_equal_controller_option
- resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {:controller => 'posts'}, {})
- assert_equal 'posts', resource.controller
- end
-
- def test_should_all_singleton_paths_be_the_same
- [ :path, :nesting_path_prefix, :member_path ].each do |method|
- resource = ActionDispatch::Routing::DeprecatedMapper::SingletonResource.new(:messages, {:path_prefix => 'admin'}, {})
- assert_equal 'admin/messages', resource.send(method)
- end
- end
-
def test_default_restful_routes
with_restful_routing :messages do
assert_simply_restful_for :messages
@@ -69,9 +40,9 @@ class ResourcesTest < ActionController::TestCase
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' }
+ 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,
@@ -89,7 +60,7 @@ class ResourcesTest < ActionController::TestCase
end
collection_methods.each do |action, method|
- assert_recognizes(options.merge(:action => action),
+ assert_recognizes(options.merge(:action => action.to_s),
:path => "/messages/#{path_names[action] || action}",
:method => method)
end
@@ -112,12 +83,6 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_override_paths_for_default_restful_actions
- resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {
- :path_names => {:new => 'nuevo', :edit => 'editar'}}, {})
- assert_equal resource.new_path, "#{resource.path}/nuevo"
- end
-
def test_multiple_default_restful_routes
with_restful_routing :messages, :comments do
assert_simply_restful_for :messages
@@ -131,7 +96,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_irregular_id_with_no_requirements_should_raise_error
+ 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
@@ -141,25 +106,25 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_irregular_id_with_requirements_should_pass
+ def test_irregular_id_with_constraints_should_pass
expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'}
- with_restful_routing(:messages, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}) do
+ 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_requirements
+ 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', :requirements => {:thread_id => /[0-9]\.[0-9]\.[0-9]/} do
+ 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_requirements_should_get_passed_to_member_actions
+ 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}, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}) do
+ 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
@@ -178,7 +143,7 @@ class ResourcesTest < ActionController::TestCase
end
def test_with_name_prefix
- with_restful_routing :messages, :name_prefix => 'post_' do
+ with_restful_routing :messages, :as => 'post_messages' do
assert_simply_restful_for :messages, :name_prefix => 'post_'
end
end
@@ -186,7 +151,16 @@ class ResourcesTest < ActionController::TestCase
def test_with_collection_actions
actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete }
- with_restful_routing :messages, :collection => actions do
+ 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
+ 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)
@@ -204,7 +178,18 @@ class ResourcesTest < ActionController::TestCase
def test_with_collection_actions_and_name_prefix
actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete }
- with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions do
+ 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
+ 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)
@@ -222,7 +207,16 @@ class ResourcesTest < ActionController::TestCase
def test_with_collection_actions_and_name_prefix_and_member_action_with_same_name
actions = { 'a' => :get }
- with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions, :member => actions do
+ 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)
@@ -240,7 +234,18 @@ class ResourcesTest < ActionController::TestCase
def test_with_collection_action_and_name_prefix_and_formatted
actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete }
- with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions do
+ 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
+ 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)
@@ -274,7 +279,7 @@ class ResourcesTest < ActionController::TestCase
def test_with_member_action_and_requirement
expected_options = {:controller => 'messages', :action => 'mark', :id => '1.1.1'}
- with_restful_routing(:messages, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}, :member => { :mark => :get }) do
+ 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
@@ -296,31 +301,18 @@ class ResourcesTest < ActionController::TestCase
end
end
- # def test_member_when_changed_default_restful_actions_and_path_names_not_specified
- # default_path_names = ActionController::Base.resources_path_names
- # ActionController::Base.resources_path_names = {:new => 'nuevo', :edit => 'editar'}
- #
- # with_restful_routing :messages do
- # new_options = { :action => 'new', :controller => 'messages' }
- # new_path = "/messages/nuevo"
- # edit_options = { :action => 'edit', :id => '1', :controller => 'messages' }
- # edit_path = "/messages/1/editar"
- #
- # assert_restful_routes_for :messages do |options|
- # assert_recognizes(options.merge(new_options), :path => new_path, :method => :get)
- # end
- #
- # assert_restful_routes_for :messages do |options|
- # assert_recognizes(options.merge(edit_options), :path => edit_path, :method => :get)
- # end
- # end
- # ensure
- # ActionController::Base.resources_path_names = default_path_names
- # end
-
def test_with_two_member_actions_with_same_method
[:put, :post].each do |method|
- with_restful_routing :messages, :member => { :mark => method, :unmark => method } do
+ 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}"
@@ -337,7 +329,19 @@ class ResourcesTest < ActionController::TestCase
end
def test_array_as_collection_or_member_method_value
- with_restful_routing :messages, :collection => { :search => [:get, :post] }, :member => { :toggle => [:get, :post] } do
+ 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)
@@ -350,7 +354,13 @@ class ResourcesTest < ActionController::TestCase
end
def test_with_new_action
- with_restful_routing :messages, :new => { :preview => :post } do
+ 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|
@@ -364,7 +374,15 @@ class ResourcesTest < ActionController::TestCase
end
def test_with_new_action_with_name_prefix
- with_restful_routing :messages, :new => { :preview => :post }, :path_prefix => '/threads/:thread_id', :name_prefix => 'thread_' do
+ 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|
@@ -378,7 +396,15 @@ class ResourcesTest < ActionController::TestCase
end
def test_with_formatted_new_action_with_name_prefix
- with_restful_routing :messages, :new => { :preview => :post }, :path_prefix => '/threads/:thread_id', :name_prefix => 'thread_' do
+ 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|
@@ -401,7 +427,13 @@ class ResourcesTest < ActionController::TestCase
end
end
- with_restful_routing :messages, :new => { :new => :any } do
+ 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)
@@ -411,10 +443,10 @@ class ResourcesTest < ActionController::TestCase
def test_nested_restful_routes
with_routing do |set|
- set.draw do |map|
- map.resources :threads do |map|
- map.resources :messages do |map|
- map.resources :comments
+ set.draw do
+ resources :threads do
+ resources :messages do
+ resources :comments
end
end
end
@@ -431,32 +463,12 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_nested_restful_routes_with_overwritten_defaults
- with_routing do |set|
- set.draw do |map|
- map.resources :threads do |map|
- map.resources :messages, :name_prefix => nil do |map|
- map.resources :comments, :name_prefix => nil
- end
- end
- end
-
- assert_simply_restful_for :threads
- assert_simply_restful_for :messages,
- :path_prefix => 'threads/1/',
- :options => { :thread_id => '1' }
- assert_simply_restful_for :comments,
- :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 |map|
- map.resources :threads, :shallow => true do |map|
- map.resources :messages do |map|
- map.resources :comments
+ set.draw do
+ resources :threads, :shallow => true do
+ resources :messages do
+ resources :comments
end
end
end
@@ -478,11 +490,11 @@ class ResourcesTest < ActionController::TestCase
def test_shallow_nested_restful_routes_with_namespaces
with_routing do |set|
- set.draw do |map|
- map.namespace :backoffice do |map|
- map.namespace :admin do |map|
- map.resources :products, :shallow => true do |map|
- map.resources :images
+ set.draw do
+ namespace :backoffice do
+ namespace :admin do
+ resources :products, :shallow => true do
+ resources :images
end
end
end
@@ -531,9 +543,9 @@ class ResourcesTest < ActionController::TestCase
def test_should_create_nested_singleton_resource_routes
with_routing do |set|
- set.draw do |map|
- map.resource :admin, :controller => 'admin' do |admin|
- admin.resource :account
+ set.draw do
+ resource :admin, :controller => 'admin' do
+ resource :account
end
end
@@ -542,69 +554,15 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_resource_has_many_should_become_nested_resources
- with_routing do |set|
- set.draw do |map|
- map.resources :messages, :has_many => [ :comments, :authors ]
- end
-
- assert_simply_restful_for :messages
- assert_simply_restful_for :comments, :name_prefix => "message_", :path_prefix => 'messages/1/', :options => { :message_id => '1' }
- assert_simply_restful_for :authors, :name_prefix => "message_", :path_prefix => 'messages/1/', :options => { :message_id => '1' }
- end
- end
-
- def test_resources_has_many_hash_should_become_nested_resources
- with_routing do |set|
- set.draw do |map|
- map.resources :threads, :has_many => { :messages => [ :comments, { :authors => :threads } ] }
- 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/1/', :options => { :thread_id => '1', :message_id => '1' }
- assert_simply_restful_for :authors, :name_prefix => "thread_message_", :path_prefix => 'threads/1/messages/1/', :options => { :thread_id => '1', :message_id => '1' }
- assert_simply_restful_for :threads, :name_prefix => "thread_message_author_", :path_prefix => 'threads/1/messages/1/authors/1/', :options => { :thread_id => '1', :message_id => '1', :author_id => '1' }
- end
- end
-
- def test_shallow_resource_has_many_should_become_shallow_nested_resources
- with_routing do |set|
- set.draw do |map|
- map.resources :messages, :has_many => [ :comments, :authors ], :shallow => true
- end
-
- assert_simply_restful_for :messages, :shallow => true
- assert_simply_restful_for :comments, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' }
- assert_simply_restful_for :authors, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' }
- end
- end
-
- def test_resource_has_one_should_become_nested_resources
- with_routing do |set|
- set.draw do |map|
- map.resources :messages, :has_one => :logo
- end
-
- assert_simply_restful_for :messages
- assert_singleton_restful_for :logo, :name_prefix => 'message_', :path_prefix => 'messages/1/', :options => { :message_id => '1' }
- end
- end
-
- def test_shallow_resource_has_one_should_become_shallow_nested_resources
- with_routing do |set|
- set.draw do |map|
- map.resources :messages, :has_one => :logo, :shallow => true
- end
-
- assert_simply_restful_for :messages, :shallow => true
- assert_singleton_restful_for :logo, :name_prefix => 'message_', :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' }
- end
- end
-
def test_singleton_resource_with_member_action
[:put, :post].each do |method|
- with_singleton_resources :account, :member => { :reset => method } do
+ 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|
@@ -620,7 +578,14 @@ class ResourcesTest < ActionController::TestCase
def test_singleton_resource_with_two_member_actions_with_same_method
[:put, :post].each do |method|
- with_singleton_resources :account, :member => { :reset => method, :disable => method } do
+ 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}"
@@ -638,9 +603,9 @@ class ResourcesTest < ActionController::TestCase
def test_should_nest_resources_in_singleton_resource
with_routing do |set|
- set.draw do |map|
- map.resource :account do |account|
- account.resources :messages
+ set.draw do
+ resource :account do
+ resources :messages
end
end
@@ -649,11 +614,13 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_should_nest_resources_in_singleton_resource_with_path_prefix
+ def test_should_nest_resources_in_singleton_resource_with_path_scope
with_routing do |set|
- set.draw do |map|
- map.resource(:account, :path_prefix => ':site_id') do |account|
- account.resources :messages
+ set.draw do
+ scope ':site_id' do
+ resource(:account) do
+ resources :messages
+ end
end
end
@@ -664,9 +631,9 @@ class ResourcesTest < ActionController::TestCase
def test_should_nest_singleton_resource_in_resources
with_routing do |set|
- set.draw do |map|
- map.resources :threads do |thread|
- thread.resource :admin, :controller => 'admin'
+ set.draw do
+ resources :threads do
+ resource :admin, :controller => 'admin'
end
end
@@ -691,52 +658,18 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_should_not_allow_invalid_head_method_for_member_routes
- with_routing do |set|
- assert_raise(ArgumentError) do
- set.draw do |map|
- map.resources :messages, :member => {:something => :head}
- end
- end
- end
- end
-
- def test_should_not_allow_invalid_http_methods_for_member_routes
+ def test_new_style_named_routes_for_resource
with_routing do |set|
- assert_raise(ArgumentError) do
- set.draw do |map|
- map.resources :messages, :member => {:something => :invalid}
+ set.draw do
+ scope '/threads/:thread_id' do
+ resources :messages, :as => 'thread_messages' do
+ get :search, :on => :collection
+ match :preview, :on => :new
+ end
end
end
- end
- end
-
- def test_resource_action_separator
- with_routing do |set|
- set.draw do |map|
- map.resources :messages, :collection => {:search => :get}, :new => {:preview => :any}, :name_prefix => 'thread_', :path_prefix => '/threads/:thread_id'
- map.resource :account, :member => {:login => :get}, :new => {:preview => :any}, :name_prefix => 'admin_', :path_prefix => '/admin'
- end
-
- action_separator = ActionController::Base.resource_action_separator
assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :options => { :thread_id => '1' }
- assert_named_route "/threads/1/messages#{action_separator}search", "search_thread_messages_path", {}
- assert_named_route "/threads/1/messages/new", "new_thread_message_path", {}
- assert_named_route "/threads/1/messages/new#{action_separator}preview", "preview_new_thread_message_path", {}
- assert_singleton_restful_for :account, :name_prefix => 'admin_', :path_prefix => 'admin/'
- assert_named_route "/admin/account#{action_separator}login", "login_admin_account_path", {}
- assert_named_route "/admin/account/new", "new_admin_account_path", {}
- assert_named_route "/admin/account/new#{action_separator}preview", "preview_new_admin_account_path", {}
- end
- end
-
- def test_new_style_named_routes_for_resource
- with_routing do |set|
- set.draw do |map|
- map.resources :messages, :collection => {:search => :get}, :new => {:preview => :any}, :name_prefix => 'thread_', :path_prefix => '/threads/:thread_id'
- 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", {}
@@ -745,8 +678,13 @@ class ResourcesTest < ActionController::TestCase
def test_new_style_named_routes_for_singleton_resource
with_routing do |set|
- set.draw do |map|
- map.resource :account, :member => {:login => :get}, :new => {:preview => :any}, :name_prefix => 'admin_', :path_prefix => '/admin'
+ set.draw do
+ scope '/admin' do
+ resource :account, :as => :admin_account do
+ get :login, :on => :member
+ match :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", {}
@@ -757,48 +695,22 @@ class ResourcesTest < ActionController::TestCase
def test_resources_in_namespace
with_routing do |set|
- set.draw do |map|
- map.namespace :backoffice do |backoffice|
- backoffice.resources :products
- end
- end
-
- assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/'
- end
- end
-
- def test_resource_has_many_in_namespace
- with_routing do |set|
- set.draw do |map|
- map.namespace :backoffice do |backoffice|
- backoffice.resources :products, :has_many => :tags
- end
- end
-
- assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/'
- assert_simply_restful_for :tags, :controller => "backoffice/tags", :name_prefix => "backoffice_product_", :path_prefix => 'backoffice/products/1/', :options => { :product_id => '1' }
- end
- end
-
- def test_resource_has_one_in_namespace
- with_routing do |set|
- set.draw do |map|
- map.namespace :backoffice do |backoffice|
- backoffice.resources :products, :has_one => :manufacturer
+ set.draw do
+ namespace :backoffice do
+ resources :products
end
end
assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/'
- assert_singleton_restful_for :manufacturer, :controller => "backoffice/manufacturers", :name_prefix => 'backoffice_product_', :path_prefix => 'backoffice/products/1/', :options => { :product_id => '1' }
end
end
def test_resources_in_nested_namespace
with_routing do |set|
- set.draw do |map|
- map.namespace :backoffice do |backoffice|
- backoffice.namespace :admin do |admin|
- admin.resources :products
+ set.draw do
+ namespace :backoffice do
+ namespace :admin do
+ resources :products
end
end
end
@@ -809,8 +721,10 @@ class ResourcesTest < ActionController::TestCase
def test_resources_using_namespace
with_routing do |set|
- set.draw do |map|
- map.resources :products, :namespace => "backoffice/"
+ set.draw do
+ namespace :backoffice, :path => nil, :as => nil do
+ resources :products
+ end
end
assert_simply_restful_for :products, :controller => "backoffice/products"
@@ -819,10 +733,10 @@ class ResourcesTest < ActionController::TestCase
def test_nested_resources_using_namespace
with_routing do |set|
- set.draw do |map|
- map.namespace :backoffice do |backoffice|
- backoffice.resources :products do |products|
- products.resources :images
+ set.draw do
+ namespace :backoffice do
+ resources :products do
+ resources :images
end
end
end
@@ -833,11 +747,11 @@ class ResourcesTest < ActionController::TestCase
def test_nested_resources_in_nested_namespace
with_routing do |set|
- set.draw do |map|
- map.namespace :backoffice do |backoffice|
- backoffice.namespace :admin do |admin|
- admin.resources :products do |products|
- products.resources :images
+ set.draw do
+ namespace :backoffice do
+ namespace :admin do
+ resources :products do
+ resources :images
end
end
end
@@ -854,21 +768,24 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes({:controller => "messages", :action => "index"}, "/messages/")
end
- with_restful_routing :messages, :as => 'reviews' do
- assert_simply_restful_for :messages, :as => 'reviews'
- assert_recognizes({:controller => "messages", :action => "index"}, "/reviews")
- assert_recognizes({:controller => "messages", :action => "index"}, "/reviews/")
+ 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 |map|
- map.resources :products do |products|
- products.resources :product_reviews, :as => 'reviews', :controller => 'messages'
+ set.draw do
+ resources :products do
+ resources :product_reviews, :path => 'reviews', :controller => 'messages'
end
- map.resources :tutors do |tutors|
- tutors.resources :tutor_reviews, :as => 'reviews', :controller => 'comments'
+ resources :tutors do
+ resources :tutor_reviews, :path => 'reviews', :controller => 'comments'
end
end
@@ -877,17 +794,22 @@ class ResourcesTest < ActionController::TestCase
end
end
- def test_with_path_segment_path_prefix_requirements
+ def test_with_path_segment_path_prefix_constraints
expected_options = {:controller => 'messages', :action => 'show', :thread_id => '1.1.1', :id => '1'}
- with_restful_routing :messages, :as => 'comments',:path_prefix => '/thread/:thread_id', :requirements => { :thread_id => /[0-9]\.[0-9]\.[0-9]/ } do
+ 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 |map|
- map.resources :products, :only => :show
+ set.draw do
+ resources :products, :only => :show
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
@@ -897,8 +819,8 @@ class ResourcesTest < ActionController::TestCase
def test_singleton_resource_has_only_show_action
with_routing do |set|
- set.draw do |map|
- map.resource :account, :only => :show
+ set.draw do
+ resource :account, :only => :show
end
assert_singleton_resource_allowed_routes('accounts', {}, :show, [:index, :new, :create, :edit, :update, :destroy])
@@ -908,8 +830,8 @@ class ResourcesTest < ActionController::TestCase
def test_resource_does_not_have_destroy_action
with_routing do |set|
- set.draw do |map|
- map.resources :products, :except => :destroy
+ set.draw do
+ resources :products, :except => :destroy
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
@@ -919,8 +841,8 @@ class ResourcesTest < ActionController::TestCase
def test_singleton_resource_does_not_have_destroy_action
with_routing do |set|
- set.draw do |map|
- map.resource :account, :except => :destroy
+ set.draw do
+ resource :account, :except => :destroy
end
assert_singleton_resource_allowed_routes('accounts', {}, [:new, :create, :show, :edit, :update], :destroy)
@@ -930,8 +852,8 @@ class ResourcesTest < ActionController::TestCase
def test_resource_has_only_create_action_and_named_route
with_routing do |set|
- set.draw do |map|
- map.resources :products, :only => :create
+ set.draw do
+ resources :products, :only => :create
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy])
@@ -943,8 +865,8 @@ class ResourcesTest < ActionController::TestCase
def test_resource_has_only_update_action_and_named_route
with_routing do |set|
- set.draw do |map|
- map.resources :products, :only => :update
+ set.draw do
+ resources :products, :only => :update
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy])
@@ -956,8 +878,8 @@ class ResourcesTest < ActionController::TestCase
def test_resource_has_only_destroy_action_and_named_route
with_routing do |set|
- set.draw do |map|
- map.resources :products, :only => :destroy
+ set.draw do
+ resources :products, :only => :destroy
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update])
@@ -969,8 +891,8 @@ class ResourcesTest < ActionController::TestCase
def test_singleton_resource_has_only_create_action_and_named_route
with_routing do |set|
- set.draw do |map|
- map.resource :account, :only => :create
+ set.draw do
+ resource :account, :only => :create
end
assert_singleton_resource_allowed_routes('accounts', {}, :create, [:new, :show, :edit, :update, :destroy])
@@ -982,8 +904,8 @@ class ResourcesTest < ActionController::TestCase
def test_singleton_resource_has_only_update_action_and_named_route
with_routing do |set|
- set.draw do |map|
- map.resource :account, :only => :update
+ set.draw do
+ resource :account, :only => :update
end
assert_singleton_resource_allowed_routes('accounts', {}, :update, [:new, :create, :show, :edit, :destroy])
@@ -995,8 +917,8 @@ class ResourcesTest < ActionController::TestCase
def test_singleton_resource_has_only_destroy_action_and_named_route
with_routing do |set|
- set.draw do |map|
- map.resource :account, :only => :destroy
+ set.draw do
+ resource :account, :only => :destroy
end
assert_singleton_resource_allowed_routes('accounts', {}, :destroy, [:new, :create, :show, :edit, :update])
@@ -1008,8 +930,10 @@ class ResourcesTest < ActionController::TestCase
def test_resource_has_only_collection_action
with_routing do |set|
- set.draw do |map|
- map.resources :products, :except => :all, :collection => { :sale => :get }
+ 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])
@@ -1022,8 +946,10 @@ class ResourcesTest < ActionController::TestCase
def test_resource_has_only_member_action
with_routing do |set|
- set.draw do |map|
- map.resources :products, :except => :all, :member => { :preview => :get }
+ 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])
@@ -1036,8 +962,12 @@ class ResourcesTest < ActionController::TestCase
def test_singleton_resource_has_only_member_action
with_routing do |set|
- set.draw do |map|
- map.resource :account, :except => :all, :member => { :signup => :get }
+ 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])
@@ -1050,9 +980,11 @@ class ResourcesTest < ActionController::TestCase
def test_nested_resource_has_only_show_and_member_action
with_routing do |set|
- set.draw do |map|
- map.resources :products, :only => [:index, :show] do |product|
- product.resources :images, :member => { :thumbnail => :get }, :only => :show
+ set.draw do
+ resources :products, :only => [:index, :show] do
+ resources :images, :only => :show do
+ get :thumbnail, :on => :member
+ end
end
end
@@ -1066,9 +998,9 @@ class ResourcesTest < ActionController::TestCase
def test_nested_resource_does_not_inherit_only_option
with_routing do |set|
- set.draw do |map|
- map.resources :products, :only => :show do |product|
- product.resources :images, :except => :destroy
+ set.draw do
+ resources :products, :only => :show do
+ resources :images, :except => :destroy
end
end
@@ -1079,9 +1011,9 @@ class ResourcesTest < ActionController::TestCase
def test_nested_resource_does_not_inherit_only_option_by_default
with_routing do |set|
- set.draw do |map|
- map.resources :products, :only => :show do |product|
- product.resources :images
+ set.draw do
+ resources :products, :only => :show do
+ resources :images
end
end
@@ -1092,9 +1024,9 @@ class ResourcesTest < ActionController::TestCase
def test_nested_resource_does_not_inherit_except_option
with_routing do |set|
- set.draw do |map|
- map.resources :products, :except => :show do |product|
- product.resources :images, :only => :destroy
+ set.draw do
+ resources :products, :except => :show do
+ resources :images, :only => :destroy
end
end
@@ -1105,9 +1037,9 @@ class ResourcesTest < ActionController::TestCase
def test_nested_resource_does_not_inherit_except_option_by_default
with_routing do |set|
- set.draw do |map|
- map.resources :products, :except => :show do |product|
- product.resources :images
+ set.draw do
+ resources :products, :except => :show do
+ resources :images
end
end
@@ -1118,8 +1050,8 @@ class ResourcesTest < ActionController::TestCase
def test_default_singleton_restful_route_uses_get
with_routing do |set|
- set.draw do |map|
- map.resource :product
+ set.draw do
+ resource :product
end
assert_routing '/product', :controller => 'products', :action => 'show'
@@ -1135,15 +1067,41 @@ class ResourcesTest < ActionController::TestCase
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 { |map| map.resources(*args) }
+ 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 { |map| map.resource(*args) }
+ set.draw {resource(*args) }
yield
end
end
@@ -1385,7 +1343,7 @@ class ResourcesTest < ActionController::TestCase
end
def distinct_routes? (r1, r2)
- if r1.conditions == r2.conditions and r1.requirements == r2.requirements then
+ if r1.conditions == r2.conditions and r1.constraints == r2.constraints then
if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then
return false
end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index fc85b01394..18cf944f46 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -2,6 +2,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
require 'active_support/dependencies'
+require 'active_support/core_ext/object/with_options'
class MilestonesController < ActionController::Base
def index() head :ok end
@@ -9,14 +10,22 @@ class MilestonesController < ActionController::Base
def rescue_action(e) raise e end
end
-ROUTING = ActionController::Routing
+ROUTING = ActionDispatch::Routing
+
+module RoutingTestHelpers
+ def url_for(set, options, recall = nil)
+ set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall))
+ end
+end
# See RFC 3986, section 3.3 for allowed path characters.
class UriReservedCharactersRoutingTest < Test::Unit::TestCase
+ include RoutingTestHelpers
+
def setup
- @set = ActionController::Routing::RouteSet.new
- @set.draw do |map|
- map.connect ':controller/:action/:variable/*additional'
+ @set = ActionDispatch::Routing::RouteSet.new
+ @set.draw do
+ match ':controller/:action/:variable/*additional'
end
safe, unsafe = %w(: @ & = + $ , ;), %w(^ ? # [ ])
@@ -27,27 +36,31 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase
end
def test_route_generation_escapes_unsafe_path_characters
- @set.generate(:controller => "content", :action => "act#{@segment}ion", :variable => "variable", :additional => "foo")
assert_equal "/content/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2",
- @set.generate(:controller => "content",
- :action => "act#{@segment}ion",
- :variable => "var#{@segment}iable",
- :additional => ["add#{@segment}itional-1", "add#{@segment}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"] }
+ :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", @set.generate(:controller => "content",
- :action => "action",
- :variable => "variable",
- :additional => [1, 2])
+ assert_equal "/content/action/variable/1/2",
+ url_for(@set, {
+ :controller => "content",
+ :action => "action",
+ :variable => "variable",
+ :additional => [1, 2]
+ })
end
end
@@ -67,10 +80,12 @@ class MockController
end
class LegacyRouteSetTests < Test::Unit::TestCase
+ include RoutingTestHelpers
+
attr_reader :rs
def setup
- @rs = ::ActionController::Routing::RouteSet.new
+ @rs = ::ActionDispatch::Routing::RouteSet.new
end
def teardown
@@ -78,80 +93,83 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def test_default_setup
- @rs.draw {|m| m.connect ':controller/:action/:id' }
+ @rs.draw { match '/: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 => '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', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10)
+ assert_equal '/admin/user/show/10', url_for(rs, { :controller => 'admin/user', :action => 'show', :id => 10 })
- assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
- assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :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', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
- assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {: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 {|m| m.connect '/:controller/:action/:id'}
+ @rs.draw { match '/:controller(/:action(/:id))'}
test_default_setup
end
def test_time_recognition
# We create many routes to make situation more realistic
- @rs = ::ActionController::Routing::RouteSet.new
- @rs.draw { |map|
- map.frontpage '', :controller => 'search', :action => 'new'
- map.resources :videos do |video|
- video.resources :comments
- video.resource :file, :controller => 'video_file'
- video.resource :share, :controller => 'video_shares'
- video.resource :abuse, :controller => 'video_abuses'
+ @rs = ::ActionDispatch::Routing::RouteSet.new
+ @rs.draw {
+ root :to => "search#new", :as => "frontpage"
+ resources :videos do
+ resources :comments
+ resource :file, :controller => 'video_file'
+ resource :share, :controller => 'video_shares'
+ resource :abuse, :controller => 'video_abuses'
end
- map.resources :abuses, :controller => 'video_abuses'
- map.resources :video_uploads
- map.resources :video_visits
+ resources :abuses, :controller => 'video_abuses'
+ resources :video_uploads
+ resources :video_visits
- map.resources :users do |user|
- user.resource :settings
- user.resources :videos
+ resources :users do
+ resource :settings
+ resources :videos
end
- map.resources :channels do |channel|
- channel.resources :videos, :controller => 'channel_videos'
+ resources :channels do
+ resources :videos, :controller => 'channel_videos'
end
- map.resource :session
- map.resource :lost_password
- map.search 'search', :controller => 'search'
- map.resources :pages
- map.connect ':controller/:action/:id'
+ resource :session
+ resource :lost_password
+ match 'search' => 'search#index', :as => 'search'
+ resources :pages
+ match ':controller/:action/:id'
}
end
def test_route_with_colon_first
- rs.draw do |map|
- map.connect '/:controller/:action/:id', :action => 'index', :id => nil
- map.connect ':url', :controller => 'tiny_url', :action => 'translate'
+ rs.draw do
+ match '/:controller/:action/:id', :action => 'index', :id => nil
+ match ':url', :controller => 'tiny_url', :action => 'translate'
end
end
def test_route_with_regexp_for_controller
- rs.draw do |map|
- map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match ':controller/:admintoken(/:action(/:id))', :controller => /admin\/.+/
+ match '/: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', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index")
- assert_equal '/content/foo', rs.generate(:controller => "content", :action => "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 |map|
- map.connect ':controller/:action/:id', :controller => /admin\/(accounts|users)/
+ rs.draw do
+ match '/: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"))
@@ -159,100 +177,97 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def test_route_with_regexp_and_dot
- rs.draw do |map|
- map.connect ':controller/:action/:file',
- :controller => /admin|user/,
- :action => /upload|download/,
- :defaults => {:file => nil},
- :requirements => {:file => %r{[^/]+(\.[^/]+)?}}
+ rs.draw do
+ match ':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',
- rs.generate(:controller => "user", :action => "download", :file => "file")
- assert_equal(
- {:controller => "user", :action => "download", :file => "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',
- rs.generate(
- :controller => "user", :action => "download", :file => "file.jpg")
- assert_equal(
- {:controller => "user", :action => "download", :file => "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 |map|
- map.home '', :controller => 'content', :action => 'list'
+ rs.draw do
+ root :to => 'content#list', :as => 'home'
end
- x = setup_for_named_route
- assert_equal("http://test.host/",
- x.send(:home_url))
+ assert_equal("http://test.host/", setup_for_named_route.send(:home_url))
end
def test_named_route_with_option
- rs.draw do |map|
- map.page 'page/:title', :controller => 'content', :action => 'show_page'
+ rs.draw do
+ match 'page/:title' => 'content#show_page', :as => 'page'
end
- x = setup_for_named_route
+
assert_equal("http://test.host/page/new%20stuff",
- x.send(:page_url, :title => 'new stuff'))
+ setup_for_named_route.send(:page_url, :title => 'new stuff'))
end
def test_named_route_with_default
- rs.draw do |map|
- map.page 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage'
+ rs.draw do
+ match 'page/:title' => 'content#show_page', :title => 'AboutPage', :as => 'page'
end
- x = setup_for_named_route
- assert_equal("http://test.host/page/AboutRails",
- x.send(:page_url, :title => "AboutRails"))
- end
-
- def test_named_route_with_name_prefix
- rs.draw do |map|
- map.page 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_'
- end
- x = setup_for_named_route
- assert_equal("http://test.host/page",
- x.send(:my_page_url))
+ 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 |map|
- map.page 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my'
+ rs.draw do
+ scope "my" do
+ match 'page' => 'content#show_page', :as => 'page'
+ end
end
- x = setup_for_named_route
+
assert_equal("http://test.host/my/page",
- x.send(:page_url))
+ setup_for_named_route.send(:page_url))
end
def test_named_route_with_blank_path_prefix
- rs.draw do |map|
- map.page 'page', :controller => 'content', :action => 'show_page', :path_prefix => ''
+ rs.draw do
+ scope "" do
+ match 'page' => 'content#show_page', :as => 'page'
+ end
end
- x = setup_for_named_route
+
assert_equal("http://test.host/page",
- x.send(:page_url))
+ setup_for_named_route.send(:page_url))
end
def test_named_route_with_nested_controller
- rs.draw do |map|
- map.users 'admin/user', :controller => 'admin/user', :action => 'index'
+ rs.draw do
+ match 'admin/user' => 'admin/user#index', :as => "users"
end
- x = setup_for_named_route
+
assert_equal("http://test.host/admin/user",
- x.send(:users_url))
+ setup_for_named_route.send(:users_url))
end
def test_optimised_named_route_with_host
- rs.draw do |map|
- map.pages 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
+ rs.draw do
+ match 'page' => 'content#show_page', :as => 'pages', :host => 'foo.com'
end
- x = setup_for_named_route
- x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once
- x.send(:pages_url)
+ 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
@@ -260,263 +275,229 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def test_named_route_without_hash
- rs.draw do |map|
- map.normal ':controller/:action/:id'
+ rs.draw do
+ match ':controller/:action/:id', :as => 'normal'
end
end
def test_named_route_root
- rs.draw do |map|
- map.root :controller => "hello"
+ rs.draw do
+ root :to => "hello#index"
end
- x = setup_for_named_route
- assert_equal("http://test.host/", x.send(:root_url))
- assert_equal("/", x.send(:root_path))
+ 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_with_regexps
- rs.draw do |map|
- map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show',
+ rs.draw do
+ match 'page/:year/:month/:day/:title' => 'page#show', :as => 'article',
:year => /\d+/, :month => /\d+/, :day => /\d+/
- map.connect ':controller/:action/:id'
+ match ':controller/:action/:id'
end
- x = setup_for_named_route
- # assert_equal(
- # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false},
- # x.send(:article_url, :title => 'hi')
- # )
- assert_equal(
- "http://test.host/page/2005/6/10/hi",
- x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
- )
+
+ 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 {|m| m.connect ':controller/:action/:id' }
+ @rs.draw { match ':controller/:action/:id' }
- assert_equal '/admin/stuff/show/10', rs.generate(
- {:controller => 'stuff', :action => 'show', :id => 10},
- {:controller => 'admin/user', :action => 'index'}
- )
+ 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 |map|
- map.path 'file/*path', :controller => 'content', :action => 'show_file'
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match 'file/*path' => 'content#show_file', :as => 'path'
+ match ':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]
+ 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]
+ assert_equal 'hello world/how are you?', results[:path]
end
def test_paths_slashes_unescaped_with_ordered_parameters
- rs.draw do |map|
- map.path '/file/*path', :controller => 'content'
+ rs.draw do
+ match '/file/*path' => 'content#index', :as => 'path'
end
# No / to %2F in URI, only for query params.
- x = setup_for_named_route
- assert_equal("/file/hello/world", x.send(:path_path, ['hello', 'world']))
+ 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 |map|
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match ':controller/:action/:id'
end
assert_raise(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
end
- def test_paths_do_not_accept_defaults
- assert_raise(ActionController::RoutingError) do
- rs.draw do |map|
- map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default)
- map.connect ':controller/:action/:id'
- end
- end
-
- rs.draw do |map|
- map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => []
- map.connect ':controller/:action/:id'
+ def test_should_list_options_diff_when_routing_constraints_dont_match
+ rs.draw do
+ match 'post/:id' => 'post#show', :constraints => { :id => /\d+/ }, :as => 'post'
end
- end
-
- def test_should_list_options_diff_when_routing_requirements_dont_match
- rs.draw do |map|
- map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
+ assert_raise(ActionController::RoutingError) do
+ url_for(rs, { :controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post" })
end
- assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") }
end
def test_dynamic_path_allowed
- rs.draw do |map|
- map.connect '*path', :controller => 'content', :action => 'show_file'
+ rs.draw do
+ match '*path' => 'content#show_file'
end
- assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo))
+ 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 |map|
- map.connect '*path', :controller => 'content', :action => 'show_file'
+ rs.draw do
+ match '*path' => 'content#show_file'
end
- assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => %w(pages boo))
+ assert_equal '/pages/boo',
+ url_for(rs, {}, { :controller => 'content', :action => 'show_file', :path => %w(pages boo) })
end
def test_backwards
- rs.draw do |map|
- map.connect 'page/:id/:action', :controller => 'pages', :action => 'show'
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match 'page/:id(/:action)' => 'pages#show'
+ match ':controller(/:action(/:id))'
end
- assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'})
- assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show')
- assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo')
+ 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 |map|
- map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match 'page(/:id)' => 'content#show_page', :id => 1
+ match ':controller/:action/:id'
end
- assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page')
- assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1)
- assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1')
- assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10)
+ 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"))
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 |map|
- map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match 'page/:id' => 'content#show_page', :id => 1
+ match ':controller/:action/:id'
end
- assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo')
- assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo"))
+ 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 = "\321\202\320\265\320\272\321\201\321\202" # 'text' in Russian
token.force_encoding(Encoding::BINARY) if token.respond_to?(:force_encoding)
escaped_token = CGI::escape(token)
- assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token)
- assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_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 {|m| m.connect ':controller/:action/:id' }
- assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
+ @rs.draw { match ':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 |map|
- map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
+ rs.draw do
+ match 'post/:id' => 'post#show', :constraints => {:id => /\d+/}, :as => 'post'
end
- assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10)
+ assert_equal '/post/10', url_for(rs, { :controller => 'post', :action => 'show', :id => 10 })
assert_raise ActionController::RoutingError do
- rs.generate(:controller => 'post', :action => 'show')
+ url_for(rs, { :controller => 'post', :action => 'show' })
end
end
def test_both_requirement_and_optional
- rs.draw do |map|
- map.blog('test/:year', :controller => 'post', :action => 'show',
+ rs.draw do
+ match('test(/:year)' => 'post#show', :as => 'blog',
:defaults => { :year => nil },
- :requirements => { :year => /\d{4}/ }
+ :constraints => { :year => /\d{4}/ }
)
- map.connect ':controller/:action/:id'
+ match ':controller/:action/:id'
end
- assert_equal '/test', rs.generate(:controller => 'post', :action => 'show')
- assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil)
+ assert_equal '/test', url_for(rs, { :controller => 'post', :action => 'show' })
+ assert_equal '/test', url_for(rs, { :controller => 'post', :action => 'show', :year => nil })
- x = setup_for_named_route
- assert_equal("http://test.host/test",
- x.send(:blog_url))
+ assert_equal("http://test.host/test", setup_for_named_route.send(:blog_url))
end
def test_set_to_nil_forgets
- rs.draw do |map|
- map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match 'pages(/:year(/:month(/:day)))' => 'content#list_pages', :month => nil, :day => nil
+ match ':controller/:action/:id'
end
assert_equal '/pages/2005',
- rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005)
+ url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005 })
assert_equal '/pages/2005/6',
- rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6)
+ url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005, :month => 6 })
assert_equal '/pages/2005/6/12',
- rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12)
+ url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12 })
assert_equal '/pages/2005/6/4',
- rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
+ url_for(rs, { :day => 4 }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' })
assert_equal '/pages/2005/6',
- rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
+ url_for(rs, { :day => nil }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' })
assert_equal '/pages/2005',
- rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
+ url_for(rs, { :day => nil, :month => nil }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' })
end
- def test_url_with_no_action_specified
- rs.draw do |map|
- map.connect '', :controller => 'content'
- map.connect ':controller/:action/:id'
+ def test_root_url_generation_with_controller_and_action
+ rs.draw do
+ root :to => "content#index"
end
- assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
- assert_equal '/', rs.generate(:controller => 'content')
+ assert_equal '/', url_for(rs, { :controller => 'content', :action => 'index' })
+ assert_equal '/', url_for(rs, { :controller => 'content' })
end
- def test_named_url_with_no_action_specified
- rs.draw do |map|
- map.home '', :controller => 'content'
- map.connect ':controller/:action/:id'
+ def test_named_root_url_generation_with_controller_and_action
+ rs.draw do
+ root :to => "content#index", :as => 'home'
end
- assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
- assert_equal '/', rs.generate(:controller => 'content')
+ assert_equal '/', url_for(rs, { :controller => 'content', :action => 'index' })
+ assert_equal '/', url_for(rs, { :controller => 'content' })
- x = setup_for_named_route
- assert_equal("http://test.host/",
- x.send(:home_url))
- end
-
- def test_url_generated_when_forgetting_action
- [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash|
- rs.draw do |map|
- map.home '', hash
- map.connect ':controller/:action/:id'
- end
- assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
- assert_equal '/', rs.generate({:controller => 'content'})
- assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
- end
+ assert_equal("http://test.host/", setup_for_named_route.send(:home_url))
end
def test_named_route_method
- rs.draw do |map|
- map.categories 'categories', :controller => 'content', :action => 'categories'
- map.connect ':controller/:action/:id'
+ rs.draw do
+ match 'categories' => 'content#categories', :as => 'categories'
+ match ':controller(/:action(/:id))'
end
- assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories')
- assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
+ 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
@@ -525,23 +506,26 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def test_nil_defaults
- rs.draw do |map|
- map.connect 'journal',
- :controller => 'content',
- :action => 'list_journal',
+ rs.draw do
+ match 'journal' => 'content#list_journal',
:date => nil, :user_id => nil
- map.connect ':controller/:action/:id'
+ match ':controller/:action/:id'
end
- assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil)
+ 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 |r|
- r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
- r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
- r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put }
- r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete }
+ rs.draw do
+ match '/match' => 'books#get', :via => :get
+ match '/match' => 'books#post', :via => :post
+ match '/match' => 'books#put', :via => :put
+ match '/match' => 'books#delete', :via => :delete
end
end
@@ -554,9 +538,9 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def test_recognize_array_of_methods
- rs.draw do |r|
- r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] }
- r.connect '/match', :controller => 'books', :action => 'not_get_or_post'
+ rs.draw do
+ match '/match' => 'books#get_or_post', :via => [:get, :post]
+ match '/match' => 'books#not_get_or_post'
end
params = rs.recognize_path("/match", :method => :post)
@@ -567,11 +551,11 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def test_subpath_recognized
- rs.draw do |r|
- r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
- r.connect '/items/:id/:action', :controller => 'subpath_books'
- r.connect '/posts/new/:action', :controller => 'subpath_books'
- r.connect '/posts/:id', :controller => 'subpath_books', :action => "show"
+ rs.draw do
+ match '/books/:id/edit' => 'subpath_books#edit'
+ match '/items/:id/:action' => 'subpath_books'
+ match '/posts/new/:action' => 'subpath_books'
+ match '/posts/:id' => 'subpath_books#show'
end
hash = rs.recognize_path "/books/17/edit"
@@ -592,36 +576,35 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def test_subpath_generated
- rs.draw do |r|
- r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
- r.connect '/items/:id/:action', :controller => 'subpath_books'
- r.connect '/posts/new/:action', :controller => 'subpath_books'
+ rs.draw do
+ match '/books/:id/edit' => 'subpath_books#edit'
+ match '/items/:id/:action' => 'subpath_books'
+ match '/posts/new/:action' => 'subpath_books'
end
- assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit")
- assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete")
- assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview")
+ 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_requirements_raises_exception_with_violated_requirements
- rs.draw do |r|
- r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/}
+ def test_failed_constraints_raises_exception_with_violated_constraints
+ rs.draw do
+ match 'foos/:id' => 'foos#show', :as => 'foo_with_requirement', :constraints => { :id => /\d+/ }
end
- x = setup_for_named_route
assert_raise(ActionController::RoutingError) do
- x.send(:foo_with_requirement_url, "I am Against the requirements")
+ setup_for_named_route.send(:foo_with_requirement_url, "I am Against the constraints")
end
end
def test_routes_changed_correctly_after_clear
- rs = ::ActionController::Routing::RouteSet.new
- rs.draw do |r|
- r.connect 'ca', :controller => 'ca', :action => "aa"
- r.connect 'cb', :controller => 'cb', :action => "ab"
- r.connect 'cc', :controller => 'cc', :action => "ac"
- r.connect ':controller/:action/:id'
- r.connect ':controller/:action/:id.:format'
+ rs = ::ActionDispatch::Routing::RouteSet.new
+ rs.draw do
+ match 'ca' => 'ca#aa'
+ match 'cb' => 'cb#ab'
+ match 'cc' => 'cc#ac'
+ match ':controller/:action/:id'
+ match ':controller/:action/:id.:format'
end
hash = rs.recognize_path "/cc"
@@ -629,22 +612,23 @@ class LegacyRouteSetTests < Test::Unit::TestCase
assert_not_nil hash
assert_equal %w(cc ac), [hash[:controller], hash[:action]]
- rs.draw do |r|
- r.connect 'cb', :controller => 'cb', :action => "ab"
- r.connect 'cc', :controller => 'cc', :action => "ac"
- r.connect ':controller/:action/:id'
- r.connect ':controller/:action/:id.:format'
+ rs.draw do
+ match 'cb' => 'cb#ab'
+ match 'cc' => 'cc#ac'
+ match ':controller/:action/:id'
+ match ':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
@@ -656,30 +640,30 @@ class RouteSetTest < ActiveSupport::TestCase
def default_route_set
@default_route_set ||= begin
set = ROUTING::RouteSet.new
- set.draw do |map|
- map.connect '/:controller/:action/:id/'
+ set.draw do
+ match '/:controller(/:action(/:id))'
end
set
end
end
def test_generate_extras
- set.draw { |m| m.connect ':controller/:action/:id' }
+ set.draw { match ':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 { |m| m.connect ':controller/:action/:id' }
+ set.draw { match ':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 |map|
- map.connect ':controller/:action/:id.:format'
- map.connect ':controller/:action/:id'
+ set.draw do
+ match ':controller/:action/:id.:format'
+ match ':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
@@ -687,17 +671,18 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_generate_not_first
- set.draw do |map|
- map.connect ':controller/:action/:id.:format'
- map.connect ':controller/:action/:id'
+ set.draw do
+ match ':controller/:action/:id.:format'
+ match ':controller/:action/:id'
end
- assert_equal "/foo/bar/15?this=hello", set.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello")
+ 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 |map|
- map.connect ':controller/:action/:id.:format'
- map.connect ':controller/:action/:id'
+ set.draw do
+ match ':controller/:action/:id.:format'
+ match ':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
@@ -705,44 +690,44 @@ class RouteSetTest < ActiveSupport::TestCase
def test_draw
assert_equal 0, set.routes.size
- set.draw do |map|
- map.connect '/hello/world', :controller => 'a', :action => 'b'
+ set.draw do
+ match '/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 |map|
- map.connect '/users/index', :controller => :users, :action => :index
+ set.draw do
+ match '/users/index' => 'users#index'
end
- params = set.recognize_path('/users/index', :method => :get)
+ set.recognize_path('/users/index', :method => :get)
assert_equal 1, set.routes.size
end
def test_named_draw
assert_equal 0, set.routes.size
- set.draw do |map|
- map.hello '/hello/world', :controller => 'a', :action => 'b'
+ set.draw do
+ match '/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_later_named_routes_take_precedence
- set.draw do |map|
- map.hello '/hello/world', :controller => 'a', :action => 'b'
- map.hello '/hello', :controller => 'a', :action => 'b'
+ set.draw do
+ match '/hello/world' => 'a#b', :as => 'hello'
+ match '/hello' => 'a#b', :as => 'hello'
end
assert_equal set.routes.last, set.named_routes[:hello]
end
def setup_named_route_test
- set.draw do |map|
- map.show '/people/:id', :controller => 'people', :action => 'show'
- map.index '/people', :controller => 'people', :action => 'index'
- map.multi '/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi'
- map.users '/admin/users', :controller => 'admin/users', :action => 'index'
+ set.draw do
+ match '/people(/:id)' => 'people#show', :as => 'show'
+ match '/people' => 'people#index', :as => 'index'
+ match '/people/go/:foo/:bar/joe(/:id)' => 'people#multi', :as => 'multi'
+ match '/admin/users' => 'admin/users#index', :as => "users"
end
MockController.build(set.url_helpers).new
@@ -752,15 +737,15 @@ class RouteSetTest < ActiveSupport::TestCase
controller = setup_named_route_test
assert_equal(
- { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false },
+ { :controller => 'people', :action => 'show', :id => 5, :use_route => "show", :only_path => false },
controller.send(:hash_for_show_url, :id => 5))
assert_equal(
- { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false },
+ { :controller => 'people', :action => 'index', :use_route => "index", :only_path => false },
controller.send(:hash_for_index_url))
assert_equal(
- { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true },
+ { :controller => 'people', :action => 'show', :id => 5, :use_route => "show", :only_path => true },
controller.send(:hash_for_show_path, :id => 5)
)
end
@@ -776,7 +761,7 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "http://test.host/admin/users", controller.send(:users_url)
assert_equal '/admin/users', controller.send(:users_path)
- assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'})
+ assert_equal '/admin/users', url_for(set, controller.send(:hash_for_users_url), { :controller => 'users', :action => 'index' })
end
def test_named_route_url_method_with_anchor
@@ -841,30 +826,23 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_draw_default_route
- set.draw do |map|
- map.connect '/:controller/:action/:id'
+ set.draw do
+ match '/:controller/:action/:id'
end
assert_equal 1, set.routes.size
- assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10)
- assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10)
+ 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_draw_default_route_with_default_controller
- set.draw do |map|
- map.connect '/:controller/:action/:id', :controller => 'users'
- end
- assert_equal({:controller => 'users', :action => 'index'}, set.recognize_path('/'))
- end
-
def test_route_with_parameter_shell
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/
- map.connect '/:controller/:action/:id'
+ set.draw do
+ match 'page/:id' => 'pages#show', :id => /\d+/
+ match '/:controller(/:action(/:id))'
end
assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages'))
@@ -875,76 +853,66 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
end
- def test_route_requirements_with_anchor_chars_are_invalid
- assert_raise ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/
+ def test_route_constraints_on_request_object_with_anchors_are_valid
+ assert_nothing_raised do
+ set.draw do
+ match '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 |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/
+ set.draw do
+ match 'page/:id' => 'pages#show', :id => /^\d+/
end
end
assert_raise ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/
+ set.draw do
+ match 'page/:id' => 'pages#show', :id => /\A\d+/
end
end
assert_raise ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/
+ set.draw do
+ match 'page/:id' => 'pages#show', :id => /\d+$/
end
end
assert_raise ArgumentError do
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/
+ set.draw do
+ match 'page/:id' => 'pages#show', :id => /\d+\Z/
end
end
- end
-
- def test_route_requirements_with_invalid_http_method_is_invalid
assert_raise ArgumentError do
- set.draw do |map|
- map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid}
+ set.draw do
+ match 'page/:id' => 'pages#show', :id => /\d+\z/
end
end
end
- def test_route_requirements_with_options_method_condition_is_valid
+ def test_route_constraints_with_options_method_condition_is_valid
assert_nothing_raised do
- set.draw do |map|
- map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :options}
- end
- end
- end
-
- def test_route_requirements_with_head_method_condition_is_invalid
- assert_raise ArgumentError do
- set.draw do |map|
- map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head}
+ set.draw do
+ match 'valid/route' => 'pages#show', :via => :options
end
end
end
def test_recognize_with_encoded_id_and_regex
- set.draw do |map|
- map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+]+/
+ set.draw do
+ match '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_conditions
- set.draw do |map|
- map.with_options(:controller => "people") do |people|
- people.people "/people", :action => "index", :conditions => { :method => :get }
- people.connect "/people", :action => "create", :conditions => { :method => :post }
- people.person "/people/:id", :action => "show", :conditions => { :method => :get }
- people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
- people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete }
- 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"
+ delete "/people/:id" => "people#destroy"
end
params = set.recognize_path("/people", :method => :get)
@@ -953,10 +921,10 @@ class RouteSetTest < ActiveSupport::TestCase
params = set.recognize_path("/people", :method => :post)
assert_equal("create", params[:action])
- params = set.recognize_path("/people", :method => :put)
+ params = set.recognize_path("/people/5", :method => :put)
assert_equal("update", params[:action])
- assert_raise(ActionController::RoutingError) {
+ assert_raise(ActionController::UnknownHttpMethod) {
set.recognize_path("/people", :method => :bacon)
}
@@ -978,10 +946,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_recognize_with_alias_in_conditions
- set.draw do |map|
- map.people "/people", :controller => 'people', :action => "index",
- :conditions => { :method => :get }
- map.root :people
+ set.draw do
+ match "/people" => 'people#index', :as => 'people', :via => :get
+ root :to => "people#index"
end
params = set.recognize_path("/people", :method => :get)
@@ -994,9 +961,8 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_typo_recognition
- set.draw do |map|
- map.connect 'articles/:year/:month/:day/:title',
- :controller => 'articles', :action => 'permalink',
+ set.draw do
+ match 'articles/:year/:month/:day/:title' => 'articles#permalink',
:year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/
end
@@ -1010,22 +976,20 @@ class RouteSetTest < ActiveSupport::TestCase
def test_routing_traversal_does_not_load_extra_classes
assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
- set.draw do |map|
- map.connect '/profile', :controller => 'profile'
+ set.draw do
+ match '/profile' => 'profile#index'
end
- params = set.recognize_path("/profile") rescue nil
+ set.recognize_path("/profile") rescue nil
assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
end
def test_recognize_with_conditions_and_format
- set.draw do |map|
- map.with_options(:controller => "people") do |people|
- people.person "/people/:id", :action => "show", :conditions => { :method => :get }
- people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
- people.connect "/people/:id.:_format", :action => "show", :conditions => { :method => :get }
- end
+ set.draw do
+ get "people/:id" => "people#show", :as => "person"
+ put "people/:id" => "people#update"
+ get "people/:id(.:format)" => "people#show"
end
params = set.recognize_path("/people/5", :method => :get)
@@ -1038,21 +1002,21 @@ class RouteSetTest < ActiveSupport::TestCase
params = set.recognize_path("/people/5.png", :method => :get)
assert_equal("show", params[:action])
assert_equal("5", params[:id])
- assert_equal("png", params[:_format])
+ assert_equal("png", params[:format])
end
def test_generate_with_default_action
- set.draw do |map|
- map.connect "/people", :controller => "people"
- map.connect "/people/list", :controller => "people", :action => "list"
+ set.draw do
+ match "/people", :controller => "people", :action => "index"
+ match "/people/list", :controller => "people", :action => "list"
end
- url = set.generate(:controller => "people", :action => "list")
+ url = url_for(set, { :controller => "people", :action => "list" })
assert_equal "/people/list", url
end
def test_root_map
- set.draw { |map| map.root :controller => "people" }
+ set.draw { root :to => 'people#index' }
params = set.recognize_path("", :method => :get)
assert_equal("people", params[:controller])
@@ -1060,10 +1024,10 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_namespace
- set.draw do |map|
+ set.draw do
- map.namespace 'api' do |api|
- api.route 'inventory', :controller => "products", :action => 'inventory'
+ namespace 'api' do
+ match 'inventory' => 'products#inventory'
end
end
@@ -1074,12 +1038,10 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_namespaced_root_map
- set.draw do |map|
-
- map.namespace 'api' do |api|
- api.root :controller => "products"
+ set.draw do
+ namespace 'api' do
+ root :to => 'products#index'
end
-
end
params = set.recognize_path("/api", :method => :get)
@@ -1088,9 +1050,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_namespace_with_path_prefix
- set.draw do |map|
- map.namespace 'api', :path_prefix => 'prefix' do |api|
- api.route 'inventory', :controller => "products", :action => 'inventory'
+ set.draw do
+ scope :module => "api", :path => "prefix" do
+ match 'inventory' => 'products#inventory'
end
end
@@ -1100,9 +1062,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_namespace_with_blank_path_prefix
- set.draw do |map|
- map.namespace 'api', :path_prefix => '' do |api|
- api.route 'inventory', :controller => "products", :action => 'inventory'
+ set.draw do
+ scope :module => "api", :path => "" do
+ match 'inventory' => 'products#inventory'
end
end
@@ -1112,128 +1074,129 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_generate_changes_controller_module
- set.draw { |map| map.connect ':controller/:action/:id' }
+ set.draw { match ':controller/:action/:id' }
current = { :controller => "bling/bloop", :action => "bap", :id => 9 }
- url = set.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current)
- assert_equal "/foo/bar/baz/7", url
- end
- # def test_id_is_not_impossibly_sticky
- # set.draw do |map|
- # map.connect 'foo/:number', :controller => "people", :action => "index"
- # map.connect ':controller/:action/:id'
- # end
- #
- # url = set.generate({:controller => "people", :action => "index", :number => 3},
- # {:controller => "people", :action => "index", :id => "21"})
- # assert_equal "/foo/3", url
- # end
+ 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 |map|
- map.connect ':controller/:id/:action'
+ set.draw do
+ match ':controller/:id/:action'
end
- url = set.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"})
+ 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 |map|
- map.connect 'about', :controller => "welcome", :action => "about"
- map.connect ':controller/:action/:id'
+ set.draw do
+ match 'about' => "welcome#about"
+ match ':controller/:action/:id'
end
- url = set.generate({:controller => "welcome", :action => "about"},
- {:controller => "welcome", :action => "get", :id => "7"})
+ url = url_for(set, { :controller => "welcome", :action => "about" },
+ { :controller => "welcome", :action => "get", :id => "7" })
+
assert_equal "/about", url
end
def test_generate
- set.draw { |map| map.connect ':controller/:action/:id' }
+ set.draw { match ':controller/:action/:id' }
args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
- assert_equal "/foo/bar/7?x=y", set.generate(args)
+ 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 { |map| map.connect ':controller/:action/:id', :path_prefix => 'my' }
+ set.draw do
+ scope "my" do
+ match ':controller(/:action(/:id))'
+ end
+ end
args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
- assert_equal "/my/foo/bar/7?x=y", set.generate(args)
+ assert_equal "/my/foo/bar/7?x=y", url_for(set, args)
end
def test_generate_with_blank_path_prefix
- set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => '' }
+ set.draw do
+ scope "" do
+ match ':controller(/:action(/:id))'
+ end
+ end
args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
- assert_equal "/foo/bar/7?x=y", set.generate(args)
+ assert_equal "/foo/bar/7?x=y", url_for(set, args)
end
def test_named_routes_are_never_relative_to_modules
- set.draw do |map|
- map.connect "/connection/manage/:action", :controller => 'connection/manage'
- map.connect "/connection/connection", :controller => "connection/connection"
- map.family_connection "/connection", :controller => "connection"
+ set.draw do
+ match "/connection/manage(/:action)" => 'connection/manage#index'
+ match "/connection/connection" => "connection/connection#index"
+ match '/connection' => 'connection#index', :as => 'family_connection'
end
- url = set.generate({:controller => "connection"}, {:controller => 'connection/manage'})
+ url = url_for(set, { :controller => "connection" }, { :controller => 'connection/manage' })
assert_equal "/connection/connection", url
- url = set.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'})
+ 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 |map|
- map.connect ':controller/:action/:id'
+ set.draw do
+ match ':controller(/:action(/:id))'
end
- assert_equal '/books', set.generate(
+ 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 |map|
- map.connect 'show_weblog/:parameter', :controller => 'weblog', :action => 'show'
- map.connect ':controller/:action/:id'
+ set.draw do
+ match 'show_weblog/:parameter' => 'weblog#show'
+ match ':controller(/:action(/:id))'
end
- assert_equal '/weblog/edit?parameter=1', set.generate(
+ 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 |map|
- map.connect '/posts.:format', :controller => 'posts'
+ set.draw do
+ match '/posts(.:format)' => 'posts#index'
end
- assert_equal '/posts', set.generate(
+ assert_equal '/posts', url_for(set,
{:controller => 'posts'},
{:controller => 'posts', :action => 'index', :format => 'xml'}
)
- assert_equal '/posts.xml', set.generate(
+ 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 { |map| map.connect 'projects/:project_id/:controller/:action' }
- assert_equal '/projects/1/weblog/show', set.generate(
- {:action => 'show', :project_id => 1},
- {:controller => 'weblog', :action => 'show', :project_id => '1'})
+ set.draw { match '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 |map|
- map.resources :projects do |project|
- project.milestones 'milestones', :controller => 'milestones', :action => 'index'
+ set.draw do
+ resources :projects do
+ member do
+ match 'milestones' => 'milestones#index', :as => 'milestones'
+ end
end
end
@@ -1244,9 +1207,9 @@ class RouteSetTest < ActiveSupport::TestCase
def test_setting_root_in_namespace_using_symbol
assert_nothing_raised do
- set.draw do |map|
- map.namespace :admin do |admin|
- admin.root :controller => 'home'
+ set.draw do
+ namespace :admin do
+ root :to => "home#index"
end
end
end
@@ -1254,51 +1217,47 @@ class RouteSetTest < ActiveSupport::TestCase
def test_setting_root_in_namespace_using_string
assert_nothing_raised do
- set.draw do |map|
- map.namespace 'admin' do |admin|
- admin.root :controller => 'home'
+ set.draw do
+ namespace 'admin' do
+ root :to => "home#index"
end
end
end
end
- def test_route_requirements_with_unsupported_regexp_options_must_error
+ def test_route_constraints_with_unsupported_regexp_options_must_error
assert_raise ArgumentError do
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => /(david|jamis)/m}
+ set.draw do
+ match 'page/:name' => 'pages#show',
+ :constraints => { :name => /(david|jamis)/m }
end
end
end
- def test_route_requirements_with_supported_options_must_not_error
+ def test_route_constraints_with_supported_options_must_not_error
assert_nothing_raised do
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => /(david|jamis)/i}
+ set.draw do
+ match 'page/:name' => 'pages#show',
+ :constraints => { :name => /(david|jamis)/i }
end
end
assert_nothing_raised do
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
+ set.draw do
+ match 'page/:name' => 'pages#show',
+ :constraints => { :name => / # Desperately overcommented regexp
( #Either
david #The Creator
| #Or
jamis #The Deployer
- )/x}
+ )/x }
end
end
end
def test_route_requirement_recognize_with_ignore_case
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => /(david|jamis)/i}
+ set.draw do
+ match '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
@@ -1308,26 +1267,24 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_route_requirement_generate_with_ignore_case
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => /(david|jamis)/i}
+ set.draw do
+ match 'page/:name' => 'pages#show',
+ :constraints => {:name => /(david|jamis)/i}
end
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
+ url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'david' })
assert_equal "/page/david", url
assert_raise ActionController::RoutingError do
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
+ url_for(set, { :controller => 'pages', :action => 'show', :name => 'davidjamis' })
end
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
+ 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 |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
+ set.draw do
+ match 'page/:name' => 'pages#show',
+ :constraints => {:name => / # Desperately overcommented regexp
( #Either
david #The Creator
| #Or
@@ -1344,33 +1301,10 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
- def test_route_requirement_generate_with_extended_syntax
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
- ( #Either
- david #The Creator
- | #Or
- jamis #The Deployer
- )/x}
- end
-
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
- assert_equal "/page/david", url
- assert_raise ActionController::RoutingError do
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
- end
- assert_raise ActionController::RoutingError do
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
- end
- end
-
- def test_route_requirement_generate_with_xi_modifiers
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {:name => / # Desperately overcommented regexp
+ def test_route_requirement_with_xi_modifiers
+ set.draw do
+ match 'page/:name' => 'pages#show',
+ :constraints => {:name => / # Desperately overcommented regexp
( #Either
david #The Creator
| #Or
@@ -1378,98 +1312,83 @@ class RouteSetTest < ActiveSupport::TestCase
)/xi}
end
- url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
- assert_equal "/page/JAMIS", url
- end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'},
+ set.recognize_path('/page/JAMIS'))
- def test_route_requirement_recognize_with_xi_modifiers
- set.draw do |map|
- map.connect 'page/:name', :controller => 'pages',
- :action => 'show',
- :requirements => {: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 |map|
- map.connect 'unnamed', :controller => :pages, :action => :show, :name => :as_symbol
- map.named 'named', :controller => :pages, :action => :show, :name => :as_symbol
+ set.draw do
+ match 'unnamed', :controller => :pages, :action => :show, :name => :as_symbol
+ match '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 |map|
- map.connect '/', :controller => 'foo'
- map.connect '/hello', :controller => 'bar'
+ set.draw do
+ match '/' => 'foo#index'
+ match '/hello' => 'bar#index'
end
- assert_equal '/', set.generate(:controller => 'foo')
- assert_equal '/hello', set.generate(:controller => 'bar')
+ 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 |map|
- map.connect '/cars/:action/:person/:car/', :controller => 'cars'
+ set.draw do
+ match '/cars/:action/:person/:car/', :controller => 'cars'
end
- assert_equal '/cars/buy/1/2', set.generate(:controller => 'cars', :action => 'buy', :person => '1', :car => '2')
+ 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 |map|
- map.connect '/books/:action.rss', :controller => 'books'
+ set.draw do
+ match '/books/:action.rss', :controller => 'books'
end
- assert_equal '/books/list.rss', set.generate(:controller => 'books', :action => 'list')
+ 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 |map|
- map.connect '/books/:action.:format', :controller => 'books'
+ set.draw do
+ match '/books(/:action(.:format))', :controller => 'books'
end
- assert_equal '/books/list.rss', set.generate(:controller => 'books', :action => 'list', :format => 'rss')
- assert_equal '/books/list.xml', set.generate(:controller => 'books', :action => 'list', :format => 'xml')
- assert_equal '/books/list', set.generate(:controller => 'books', :action => 'list')
- assert_equal '/books', set.generate(:controller => 'books', :action => 'index')
+ 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 => "list"}, set.recognize_path('/books/list'))
assert_equal({:controller => "books", :action => "index"}, set.recognize_path('/books'))
end
def test_slashes_are_implied
- ['/:controller/:action/:id/', '/:controller/:action/:id',
- ':controller/:action/:id', '/:controller/:action/:id/'
- ].each do |path|
- @set = nil
- set.draw { |map| map.connect(path) }
+ @set = nil
+ set.draw { match("/:controller(/:action(/:id))") }
- assert_equal '/content', set.generate(:controller => 'content', :action => 'index')
- assert_equal '/content/list', set.generate(:controller => 'content', :action => 'list')
- assert_equal '/content/show/1', set.generate(:controller => 'content', :action => 'show', :id => '1')
+ 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
+ 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
@@ -1493,102 +1412,102 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_default_route_should_omit_default_action
- assert_equal '/accounts', default_route_set.generate({:controller => 'accounts', :action => 'index'})
+ 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', default_route_set.generate({:controller => 'accounts', :action => 'index', :id => '20'})
+ 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', default_route_set.generate({:controller => 'accounts', :action => 'list_all'})
+ 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', default_route_set.generate(expected, expected)
+ 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', default_route_set.generate(expected, expected)
+ assert_equal '/pages/show/hello+world', url_for(default_route_set, expected)
end
def test_build_empty_query_string
- assert_uri_equal '/foo', default_route_set.generate({:controller => 'foo'})
+ assert_uri_equal '/foo', url_for(default_route_set, { :controller => 'foo' })
end
def test_build_query_string_with_nil_value
- assert_uri_equal '/foo', default_route_set.generate({:controller => 'foo', :x => nil})
+ 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', default_route_set.generate({:controller => 'foo', :x => '1', :y => '2'})
+ 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', default_route_set.generate({:controller => 'foo', :x => 1, :y => 2})
+ 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', default_route_set.generate({:controller => 'foo', :x => 'hello world', :y => 'goodbye world'})
+ 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[]=1&x[]=2', default_route_set.generate({:controller => 'foo', :x => [1, 2]})
+ 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', default_route_set.generate({:controller => 'foo', :x => 'hello world'})
+ 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 |map|
- map.connect 'dummy/page/:page', :controller => 'dummy'
- map.connect 'dummy/dots/page.:page', :controller => 'dummy', :action => 'dots'
- map.connect 'ibocorp/:page', :controller => 'ibocorp',
- :requirements => { :page => /\d+/ },
- :defaults => { :page => 1 }
+ set.draw do
+ match 'dummy/page/:page' => 'dummy#show'
+ match 'dummy/dots/page.:page' => 'dummy#dots'
+ match 'ibocorp(/:page)' => 'ibocorp#show',
+ :constraints => { :page => /\d+/ },
+ :defaults => { :page => 1 }
- map.connect ':controller/:action/:id'
+ match ':controller/:action/:id'
end
- assert_equal '/ibocorp', set.generate({:controller => 'ibocorp', :page => 1})
+ 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 |map|
- map.connect "blog/", :controller => "blog", :action => "index"
+ set.draw do
+ match "blog/", :controller => "blog", :action => "index"
- map.connect "blog/:year/:month/:day",
- :controller => "blog",
- :action => "show_date",
- :requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/ },
- :day => nil, :month => nil
+ match "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
- map.connect "blog/show/:id", :controller => "blog", :action => "show", :id => /\d+/
- map.connect "blog/:controller/:action/:id"
- map.connect "*anything", :controller => "blog", :action => "unknown_request"
+ match "blog/show/:id", :controller => "blog", :action => "show", :id => /\d+/
+ match "blog/:controller/:action(/:id)"
+ match "*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"}, set.recognize_path("/blog/2004"))
- assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12"}, set.recognize_path("/blog/2004/12"))
+ 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"))
+ 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", set.generate({:day => 25}, last_request))
- assert_equal("/blog/2005", set.generate({:year => 2005}, last_request))
- assert_equal("/blog/show/123", set.generate({:action => "show" , :id => 123}, last_request))
- assert_equal("/blog/2006", set.generate({:year => 2006}, last_request))
- assert_equal("/blog/2006", set.generate({:year => 2006, :month => nil}, 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
@@ -1604,76 +1523,67 @@ class RouteSetTest < ActiveSupport::TestCase
end
class RackMountIntegrationTests < ActiveSupport::TestCase
+ include RoutingTestHelpers
+
Model = Struct.new(:to_param)
- Mapping = lambda { |map|
- map.namespace :admin do |admin|
- admin.resources :users
+ Mapping = lambda {
+ namespace :admin do
+ resources :users, :posts
end
- map.namespace 'api' do |api|
- api.root :controller => 'users'
+ namespace 'api' do
+ root :to => 'users#index'
end
- map.connect 'blog/:year/:month/:day',
- :controller => 'posts',
- :action => 'show_date',
- :requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/},
- :day => nil,
- :month => nil
+ match '/blog(/:year(/:month(/:day)))' => 'posts#show_date',
+ :constraints => {
+ :year => /(19|20)\d\d/,
+ :month => /[01]?\d/,
+ :day => /[0-3]?\d/
+ },
+ :day => nil,
+ :month => nil
- map.blog('archive/:year', :controller => 'archive', :action => 'index',
+ match 'archive/:year', :controller => 'archive', :action => 'index',
:defaults => { :year => nil },
- :requirements => { :year => /\d{4}/ }
- )
+ :constraints => { :year => /\d{4}/ },
+ :as => "blog"
- map.resources :people
- map.connect 'legacy/people', :controller => 'people', :action => 'index', :legacy => 'true'
+ resources :people
+ match 'legacy/people' => "people#index", :legacy => "true"
- map.connect 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol
- map.connect 'id_default/:id', :controller => 'foo', :action => 'id_default', :id => 1
- map.connect 'get_or_post', :controller => 'foo', :action => 'get_or_post', :conditions => { :method => [:get, :post] }
- map.connect 'optional/:optional', :controller => 'posts', :action => 'index'
- map.project 'projects/:project_id', :controller => 'project'
- map.connect 'clients', :controller => 'projects', :action => 'index'
+ match 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol
+ match 'id_default(/:id)' => "foo#id_default", :id => 1
+ match 'get_or_post' => "foo#get_or_post", :via => [:get, :post]
+ match 'optional/:optional' => "posts#index"
+ match 'projects/:project_id' => "project#index", :as => "project"
+ match 'clients' => "projects#index"
- map.connect 'ignorecase/geocode/:postalcode', :controller => 'geocode',
- :action => 'show', :postalcode => /hx\d\d-\d[a-z]{2}/i
- map.geocode 'extended/geocode/:postalcode', :controller => 'geocode',
- :action => 'show',:requirements => {
+ match 'ignorecase/geocode/:postalcode' => 'geocode#show', :postalcode => /hx\d\d-\d[a-z]{2}/i
+ match 'extended/geocode/:postalcode' => 'geocode#show',:constraints => {
:postalcode => /# Postcode format
\d{5} #Prefix
(-\d{4})? #Suffix
/x
- }
+ }, :as => "geocode"
- map.connect '', :controller => 'news', :format => nil
- map.connect 'news.:format', :controller => 'news'
+ match 'news(.:format)' => "news#index"
- map.connect 'comment/:id/:action', :controller => 'comments', :action => 'show'
- map.connect 'ws/:controller/:action/:id', :ws => true
- map.connect 'account/:action', :controller => :account, :action => :subscription
- map.connect 'pages/:page_id/:controller/:action/:id'
- map.connect ':controller/ping', :action => 'ping'
- map.connect ':controller/:action/:id'
+ match 'comment/:id(/:action)' => "comments#show"
+ match 'ws/:controller(/:action(/:id))', :ws => true
+ match 'account(/:action)' => "account#subscription"
+ match 'pages/:page_id/:controller(/:action(/:id))'
+ match ':controller/ping', :action => 'ping'
+ match ':controller(/:action(/:id))(.:format)'
+ root :to => "news#index"
}
def setup
- @routes = ActionController::Routing::RouteSet.new
+ @routes = ActionDispatch::Routing::RouteSet.new
@routes.draw(&Mapping)
end
- def test_add_route
- @routes.clear!
-
- assert_raise(ActionController::RoutingError) do
- @routes.draw do |map|
- map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default)
- map.connect ':controller/:action/:id'
- end
- end
- 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))
@@ -1689,8 +1599,8 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
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'}, @routes.recognize_path('/blog/2009', :method => :get))
- assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => '01'}, @routes.recognize_path('/blog/2009/01', :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'))
@@ -1710,7 +1620,7 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
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 => '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) }
@@ -1743,126 +1653,118 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
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', :format => nil}, @routes.recognize_path('/', :method => :get))
+ 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
- assert_equal '/admin/users', @routes.generate(:use_route => 'admin_users')
- assert_equal '/admin/users', @routes.generate(:controller => 'admin/users')
- assert_equal '/admin/users', @routes.generate(:controller => 'admin/users', :action => 'index')
- assert_equal '/admin/users', @routes.generate({:action => 'index'}, {:controller => 'admin/users'})
- assert_equal '/admin/users', @routes.generate({:controller => 'users', :action => 'index'}, {:controller => 'admin/accounts'})
- assert_equal '/people', @routes.generate({:controller => '/people', :action => 'index'}, {:controller => 'admin/accounts'})
-
- assert_equal '/admin/posts', @routes.generate({:controller => 'admin/posts'})
- assert_equal '/admin/posts/new', @routes.generate({:controller => 'admin/posts', :action => 'new'})
-
- assert_equal '/blog/2009', @routes.generate(:controller => 'posts', :action => 'show_date', :year => 2009)
- assert_equal '/blog/2009/1', @routes.generate(:controller => 'posts', :action => 'show_date', :year => 2009, :month => 1)
- assert_equal '/blog/2009/1/1', @routes.generate(:controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1)
-
- assert_equal '/archive/2010', @routes.generate(:controller => 'archive', :action => 'index', :year => '2010')
- assert_equal '/archive', @routes.generate(:controller => 'archive', :action => 'index')
- assert_equal '/archive?year=january', @routes.generate(:controller => 'archive', :action => 'index', :year => 'january')
-
- assert_equal '/people', @routes.generate(:use_route => 'people')
- assert_equal '/people', @routes.generate(:use_route => 'people', :controller => 'people', :action => 'index')
- assert_equal '/people.xml', @routes.generate(:use_route => 'people', :controller => 'people', :action => 'index', :format => 'xml')
- assert_equal '/people', @routes.generate({:use_route => 'people', :controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'index'})
- assert_equal '/people', @routes.generate(:controller => 'people')
- assert_equal '/people', @routes.generate(:controller => 'people', :action => 'index')
- assert_equal '/people', @routes.generate({:action => 'index'}, {:controller => 'people'})
- assert_equal '/people', @routes.generate({:action => 'index'}, {:controller => 'people', :action => 'show', :id => '1'})
- assert_equal '/people', @routes.generate({:controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'show', :id => '1'})
- assert_equal '/people', @routes.generate({}, {:controller => 'people', :action => 'index'})
- assert_equal '/people/1', @routes.generate({:controller => 'people', :action => 'show'}, {:controller => 'people', :action => 'show', :id => '1'})
- assert_equal '/people/new', @routes.generate(:use_route => 'new_person')
- assert_equal '/people/new', @routes.generate(:controller => 'people', :action => 'new')
- assert_equal '/people/1', @routes.generate(:use_route => 'person', :id => '1')
- assert_equal '/people/1', @routes.generate(:controller => 'people', :action => 'show', :id => '1')
- assert_equal '/people/1.xml', @routes.generate(:controller => 'people', :action => 'show', :id => '1', :format => 'xml')
- assert_equal '/people/1', @routes.generate(:controller => 'people', :action => 'show', :id => 1)
- assert_equal '/people/1', @routes.generate(:controller => 'people', :action => 'show', :id => Model.new('1'))
- assert_equal '/people/1', @routes.generate({:action => 'show', :id => '1'}, {:controller => 'people', :action => 'index'})
- assert_equal '/people/1', @routes.generate({:action => 'show', :id => 1}, {:controller => 'people', :action => 'show', :id => '1'})
- # assert_equal '/people', @routes.generate({:controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'index', :id => '1'})
- assert_equal '/people', @routes.generate({:controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'show', :id => '1'})
- assert_equal '/people/1', @routes.generate({}, {:controller => 'people', :action => 'show', :id => '1'})
- assert_equal '/people/1', @routes.generate({:controller => 'people', :action => 'show'}, {:controller => 'people', :action => 'index', :id => '1'})
- assert_equal '/people/1/edit', @routes.generate(:controller => 'people', :action => 'edit', :id => '1')
- assert_equal '/people/1/edit.xml', @routes.generate(:controller => 'people', :action => 'edit', :id => '1', :format => 'xml')
- assert_equal '/people/1/edit', @routes.generate(:use_route => 'edit_person', :id => '1')
- assert_equal '/people/1?legacy=true', @routes.generate(:controller => 'people', :action => 'show', :id => '1', :legacy => 'true')
- assert_equal '/people?legacy=true', @routes.generate(:controller => 'people', :action => 'index', :legacy => 'true')
-
- assert_equal '/id_default/2', @routes.generate(:controller => 'foo', :action => 'id_default', :id => '2')
- assert_equal '/id_default', @routes.generate(:controller => 'foo', :action => 'id_default', :id => '1')
- assert_equal '/id_default', @routes.generate(:controller => 'foo', :action => 'id_default', :id => 1)
- assert_equal '/id_default', @routes.generate(:controller => 'foo', :action => 'id_default')
- assert_equal '/optional/bar', @routes.generate(:controller => 'posts', :action => 'index', :optional => 'bar')
- assert_equal '/posts', @routes.generate(:controller => 'posts', :action => 'index')
-
- assert_equal '/project', @routes.generate({:controller => 'project', :action => 'index'})
- assert_equal '/projects/1', @routes.generate({:controller => 'project', :action => 'index', :project_id => '1'})
- assert_equal '/projects/1', @routes.generate({:controller => 'project', :action => 'index'}, {:project_id => '1'})
- assert_raise(ActionController::RoutingError) { @routes.generate({:use_route => 'project', :controller => 'project', :action => 'index'}) }
- assert_equal '/projects/1', @routes.generate({:use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1'})
- assert_equal '/projects/1', @routes.generate({:use_route => 'project', :controller => 'project', :action => 'index'}, {:project_id => '1'})
-
- assert_equal '/clients', @routes.generate(:controller => 'projects', :action => 'index')
- assert_equal '/clients?project_id=1', @routes.generate(:controller => 'projects', :action => 'index', :project_id => '1')
- assert_equal '/clients', @routes.generate({:controller => 'projects', :action => 'index'}, {:project_id => '1'})
- assert_equal '/clients', @routes.generate({:action => 'index'}, {:controller => 'projects', :action => 'index', :project_id => '1'})
-
- assert_equal '/comment/20', @routes.generate({:id => 20}, {:controller => 'comments', :action => 'show'})
- assert_equal '/comment/20', @routes.generate(:controller => 'comments', :id => 20, :action => 'show')
- assert_equal '/comments/boo', @routes.generate(:controller => 'comments', :action => 'boo')
-
- assert_equal '/ws/posts/show/1', @routes.generate(:controller => 'posts', :action => 'show', :id => '1', :ws => true)
- assert_equal '/ws/posts', @routes.generate(:controller => 'posts', :action => 'index', :ws => true)
-
- assert_equal '/account', @routes.generate(:controller => 'account', :action => 'subscription')
- assert_equal '/account/billing', @routes.generate(:controller => 'account', :action => 'billing')
-
- assert_equal '/pages/1/notes/show/1', @routes.generate(:page_id => '1', :controller => 'notes', :action => 'show', :id => '1')
- assert_equal '/pages/1/notes/list', @routes.generate(:page_id => '1', :controller => 'notes', :action => 'list')
- assert_equal '/pages/1/notes', @routes.generate(:page_id => '1', :controller => 'notes', :action => 'index')
- assert_equal '/pages/1/notes', @routes.generate(:page_id => '1', :controller => 'notes')
- assert_equal '/notes', @routes.generate(:page_id => nil, :controller => 'notes')
- assert_equal '/notes', @routes.generate(:controller => 'notes')
- assert_equal '/notes/print', @routes.generate(:controller => 'notes', :action => 'print')
- assert_equal '/notes/print', @routes.generate({}, {:controller => 'notes', :action => 'print'})
-
- assert_equal '/notes/index/1', @routes.generate({:controller => 'notes'}, {:controller => 'notes', :id => '1'})
- assert_equal '/notes/index/1', @routes.generate({:controller => 'notes'}, {:controller => 'notes', :id => '1', :foo => 'bar'})
- assert_equal '/notes/index/1', @routes.generate({:controller => 'notes'}, {:controller => 'notes', :id => '1'})
- assert_equal '/notes/index/1', @routes.generate({:action => 'index'}, {:controller => 'notes', :id => '1'})
- assert_equal '/notes/index/1', @routes.generate({}, {:controller => 'notes', :id => '1'})
- assert_equal '/notes/show/1', @routes.generate({}, {:controller => 'notes', :action => 'show', :id => '1'})
- assert_equal '/notes/index/1', @routes.generate({:controller => 'notes', :id => '1'}, {:foo => 'bar'})
- assert_equal '/posts', @routes.generate({:controller => 'posts'}, {:controller => 'notes', :action => 'show', :id => '1'})
- assert_equal '/notes/list', @routes.generate({:action => 'list'}, {:controller => 'notes', :action => 'show', :id => '1'})
-
- assert_equal '/posts/ping', @routes.generate(:controller => 'posts', :action => 'ping')
- assert_equal '/posts/show/1', @routes.generate(:controller => 'posts', :action => 'show', :id => '1')
- assert_equal '/posts', @routes.generate(:controller => 'posts')
- assert_equal '/posts', @routes.generate(:controller => 'posts', :action => 'index')
- assert_equal '/posts', @routes.generate({:controller => 'posts'}, {:controller => 'posts', :action => 'index'})
- assert_equal '/posts/create', @routes.generate({:action => 'create'}, {:controller => 'posts'})
- assert_equal '/posts?foo=bar', @routes.generate(:controller => 'posts', :foo => 'bar')
- assert_equal '/posts?foo[]=bar&foo[]=baz', @routes.generate(:controller => 'posts', :foo => ['bar', 'baz'])
- assert_equal '/posts?page=2', @routes.generate(:controller => 'posts', :page => 2)
- assert_equal '/posts?q[foo][a]=b', @routes.generate(:controller => 'posts', :q => { :foo => { :a => 'b'}})
-
- assert_equal '/', @routes.generate(:controller => 'news', :action => 'index')
- assert_equal '/', @routes.generate(:controller => 'news', :action => 'index', :format => nil)
- assert_equal '/news.rss', @routes.generate(:controller => 'news', :action => 'index', :format => 'rss')
-
-
- assert_raise(ActionController::RoutingError) { @routes.generate({:action => 'index'}) }
+ assert_equal '/admin/users', url_for(@routes, { :use_route => 'admin_users' })
+ assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users' })
+ assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users', :action => 'index' })
+ assert_equal '/admin/users', url_for(@routes, { :action => 'index' }, { :controller => 'admin/users' })
+ assert_equal '/admin/users', url_for(@routes, { :controller => 'users', :action => 'index' }, { :controller => 'admin/accounts' })
+ assert_equal '/people', url_for(@routes, { :controller => '/people', :action => 'index' }, { :controller => 'admin/accounts' })
+
+ assert_equal '/admin/posts', url_for(@routes, { :controller => 'admin/posts' })
+ assert_equal '/admin/posts/new', url_for(@routes, { :controller => 'admin/posts', :action => 'new' })
+
+ assert_equal '/blog/2009', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009 })
+ assert_equal '/blog/2009/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1 })
+ assert_equal '/blog/2009/1/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1 })
+
+ assert_equal '/archive/2010', url_for(@routes, { :controller => 'archive', :action => 'index', :year => '2010' })
+ assert_equal '/archive', url_for(@routes, { :controller => 'archive', :action => 'index' })
+ assert_equal '/archive?year=january', url_for(@routes, { :controller => 'archive', :action => 'index', :year => 'january' })
+
+ assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' })
+ assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people' })
+ assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' })
+ assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' })
+ assert_equal '/people', url_for(@routes, {}, { :controller => 'people', :action => 'index' })
+ assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'show', :id => '1' })
+ assert_equal '/people/new', url_for(@routes, { :use_route => 'new_person' })
+ assert_equal '/people/new', url_for(@routes, { :controller => 'people', :action => 'new' })
+ assert_equal '/people/1', url_for(@routes, { :use_route => 'person', :id => '1' })
+ assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1' })
+ assert_equal '/people/1.xml', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :format => 'xml' })
+ assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => 1 })
+ assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => Model.new('1') })
+ assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => '1' }, { :controller => 'people', :action => 'index' })
+ assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => 1 }, { :controller => 'people', :action => 'show', :id => '1' })
+ assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' })
+ assert_equal '/people/1', url_for(@routes, {}, { :controller => 'people', :action => 'show', :id => '1' })
+ assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'index', :id => '1' })
+ assert_equal '/people/1/edit', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1' })
+ assert_equal '/people/1/edit.xml', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1', :format => 'xml' })
+ assert_equal '/people/1/edit', url_for(@routes, { :use_route => 'edit_person', :id => '1' })
+ assert_equal '/people/1?legacy=true', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :legacy => 'true' })
+ assert_equal '/people?legacy=true', url_for(@routes, { :controller => 'people', :action => 'index', :legacy => 'true' })
+
+ assert_equal '/id_default/2', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '2' })
+ assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '1' })
+ assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => 1 })
+ assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default' })
+ assert_equal '/optional/bar', url_for(@routes, { :controller => 'posts', :action => 'index', :optional => 'bar' })
+ assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' })
+
+ assert_equal '/project', url_for(@routes, { :controller => 'project', :action => 'index' })
+ assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index', :project_id => '1' })
+ assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index'}, {:project_id => '1' })
+ assert_raise(ActionController::RoutingError) { url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }) }
+ assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1' })
+ assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }, { :project_id => '1' })
+
+ assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' })
+ assert_equal '/clients?project_id=1', url_for(@routes, { :controller => 'projects', :action => 'index', :project_id => '1' })
+ assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' }, { :project_id => '1' })
+ assert_equal '/clients', url_for(@routes, { :action => 'index' }, { :controller => 'projects', :action => 'index', :project_id => '1' })
+
+ assert_equal '/comment/20', url_for(@routes, { :id => 20 }, { :controller => 'comments', :action => 'show' })
+ assert_equal '/comment/20', url_for(@routes, { :controller => 'comments', :id => 20, :action => 'show' })
+ assert_equal '/comments/boo', url_for(@routes, { :controller => 'comments', :action => 'boo' })
+
+ assert_equal '/ws/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1', :ws => true })
+ assert_equal '/ws/posts', url_for(@routes, { :controller => 'posts', :action => 'index', :ws => true })
+
+ assert_equal '/account', url_for(@routes, { :controller => 'account', :action => 'subscription' })
+ assert_equal '/account/billing', url_for(@routes, { :controller => 'account', :action => 'billing' })
+
+ assert_equal '/pages/1/notes/show/1', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'show', :id => '1' })
+ assert_equal '/pages/1/notes/list', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'list' })
+ assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'index' })
+ assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes' })
+ assert_equal '/notes', url_for(@routes, { :page_id => nil, :controller => 'notes' })
+ assert_equal '/notes', url_for(@routes, { :controller => 'notes' })
+ assert_equal '/notes/print', url_for(@routes, { :controller => 'notes', :action => 'print' })
+ assert_equal '/notes/print', url_for(@routes, {}, { :controller => 'notes', :action => 'print' })
+
+ assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' })
+ assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1', :foo => 'bar' })
+ assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' })
+ assert_equal '/notes/index/1', url_for(@routes, { :action => 'index' }, { :controller => 'notes', :id => '1' })
+ assert_equal '/notes/index/1', url_for(@routes, {}, { :controller => 'notes', :id => '1' })
+ assert_equal '/notes/show/1', url_for(@routes, {}, { :controller => 'notes', :action => 'show', :id => '1' })
+ assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes', :id => '1' }, { :foo => 'bar' })
+ assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'notes', :action => 'show', :id => '1' })
+ assert_equal '/notes/list', url_for(@routes, { :action => 'list' }, { :controller => 'notes', :action => 'show', :id => '1' })
+
+ assert_equal '/posts/ping', url_for(@routes, { :controller => 'posts', :action => 'ping' })
+ assert_equal '/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1' })
+ assert_equal '/posts', url_for(@routes, { :controller => 'posts' })
+ assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' })
+ assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'posts', :action => 'index' })
+ assert_equal '/posts/create', url_for(@routes, { :action => 'create' }, { :controller => 'posts' })
+ assert_equal '/posts?foo=bar', url_for(@routes, { :controller => 'posts', :foo => 'bar' })
+ assert_equal '/posts?foo%5B%5D=bar&foo%5B%5D=baz', url_for(@routes, { :controller => 'posts', :foo => ['bar', 'baz'] })
+ assert_equal '/posts?page=2', url_for(@routes, { :controller => 'posts', :page => 2 })
+ assert_equal '/posts?q%5Bfoo%5D%5Ba%5D=b', url_for(@routes, { :controller => 'posts', :q => { :foo => { :a => 'b'}} })
+
+ assert_equal '/news.rss', url_for(@routes, { :controller => 'news', :action => 'index', :format => 'rss' })
+
+
+ assert_raise(ActionController::RoutingError) { url_for(@routes, { :action => 'index' }) }
end
def test_generate_extras
diff --git a/actionpack/test/controller/runner_test.rb b/actionpack/test/controller/runner_test.rb
new file mode 100644
index 0000000000..24c220dcd5
--- /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 < Test::Unit::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
index 5a5dc840b5..8ce9e43402 100644
--- a/actionpack/test/controller/selector_test.rb
+++ b/actionpack/test/controller/selector_test.rb
@@ -437,7 +437,7 @@ class SelectorTest < Test::Unit::TestCase
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.
@@ -471,7 +471,7 @@ class SelectorTest < Test::Unit::TestCase
end
- def test_first_and_last
+ def test_only_child_and_only_type_first_and_last
# Only child.
parse(%Q{<table><tr></tr></table>})
select("table:only-child")
@@ -503,7 +503,7 @@ class SelectorTest < Test::Unit::TestCase
assert_equal 1, @matches.size
end
-
+
def test_content
parse(%Q{<div> </div>})
select("div:content()")
@@ -582,7 +582,7 @@ class SelectorTest < Test::Unit::TestCase
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")
@@ -594,7 +594,7 @@ class SelectorTest < Test::Unit::TestCase
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>})
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index 13c9d9ee38..edda0d0a30 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -135,6 +135,11 @@ XML
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.env['PATH_INFO'] = nil
+ @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
+ r.draw do
+ match ':controller(/:action(/:id))'
+ end
+ end
end
def test_raw_post_handling
@@ -454,18 +459,26 @@ XML
def test_assert_routing_with_method
with_routing do |set|
- set.draw { |map| map.resources(:content) }
+ set.draw { resources(:content) }
assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' })
end
end
def test_assert_routing_in_module
- assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
+ with_routing do |set|
+ set.draw do
+ namespace :admin do
+ match '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 { |map| match('*path' => "pages#show") }
+ set.draw { match('*path' => "pages#show") }
assert_routing('/company/about', { :controller => 'pages', :action => 'show', :path => 'company/about' })
end
end
@@ -487,7 +500,7 @@ XML
def test_array_path_parameter_handled_properly
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'file/*path', :to => 'test_test/test#test_params'
match ':controller/:action'
end
@@ -546,7 +559,15 @@ XML
assert_equal "bar", @request.params[:foo]
@request.recycle!
post :no_op
- assert @request.params[:foo].blank?
+ assert_blank @request.params[:foo]
+ 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_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
@@ -570,7 +591,7 @@ XML
assert false, "expected RuntimeError, got nothing"
rescue RuntimeError => error
assert true
- assert_match %r{@#{variable} is nil}, error.message
+ assert_match(%r{@#{variable} is nil}, error.message)
rescue => error
assert false, "expected RuntimeError, got #{error.class}"
end
@@ -653,13 +674,6 @@ XML
assert_redirected_to 'created resource'
end
end
-
- def test_binary_content_works_with_send_file
- get :test_send_file
- assert_deprecated do
- assert_nothing_raised(NoMethodError) { @response.binary_content }
- end
- end
end
class InferringClassNameTest < ActionController::TestCase
@@ -694,7 +708,7 @@ class NamedRoutesControllerTest < ActionController::TestCase
def test_should_be_able_to_use_named_routes_before_a_request_is_done
with_routing do |set|
- set.draw { |map| resources :contents }
+ 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
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index 71a4a43477..3f3d6dcc2f 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -5,7 +5,7 @@ module AbstractController
class UrlForTests < ActionController::TestCase
class W
- include SharedTestRoutes.url_helpers
+ include ActionDispatch::Routing::RouteSet.new.tap { |r| r.draw { match ':controller(/:action(/:id(.:format)))' } }.url_helpers
end
def teardown
@@ -17,7 +17,7 @@ module AbstractController
end
def test_exception_is_thrown_without_host
- assert_raise RuntimeError do
+ assert_raise ArgumentError do
W.new.url_for :controller => 'c', :action => 'a', :id => 'i'
end
end
@@ -60,6 +60,27 @@ module AbstractController
)
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_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',
@@ -74,16 +95,29 @@ module AbstractController
)
end
- def test_protocol_with_and_without_separator
+ def test_protocol_with_and_without_separators
add_host!
assert_equal('https://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https')
)
assert_equal('https://www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https:')
+ )
+ assert_equal('https://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://')
)
end
+ def test_without_protocol
+ add_host!
+ assert_equal('//www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => '//')
+ )
+ assert_equal('//www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => false)
+ )
+ end
+
def test_trailing_slash
add_host!
options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'}
@@ -130,7 +164,7 @@ module AbstractController
def test_named_routes
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'this/is/verbose', :to => 'home#index', :as => :no_args
match 'home/sweet/home/:user', :to => 'home#index', :as => :home
end
@@ -151,7 +185,7 @@ module AbstractController
def test_relative_url_root_is_respected_for_named_routes
with_routing do |set|
- set.draw do |map|
+ set.draw do
match '/home/sweet/home/:user', :to => 'home#index', :as => :home
end
@@ -165,7 +199,7 @@ module AbstractController
def test_only_path
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'home/sweet/home/:user', :to => 'home#index', :as => :home
match ':controller/:action/:id'
end
@@ -219,7 +253,7 @@ module AbstractController
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
+ 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
@@ -233,7 +267,7 @@ module AbstractController
def test_named_routes_with_nil_keys
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'posts.:format', :to => 'posts#index', :as => :posts
match '/', :to => 'posts#index', :as => :main
end
@@ -277,6 +311,14 @@ module AbstractController
assert_equal("/c/a", W.new.url_for(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
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index a8d7b75372..89de4c1da4 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -19,6 +19,11 @@ class UrlRewriterTests < ActionController::TestCase
@request = ActionController::TestRequest.new
@params = {}
@rewriter = Rewriter.new(@request) #.new(@request, @params)
+ @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
+ r.draw do
+ match ':controller(/:action(/:id))'
+ end
+ end
end
def test_port
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
index b8972b04b6..edfcb5cc4d 100644
--- a/actionpack/test/controller/view_paths_test.rb
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -20,7 +20,7 @@ class ViewLoadPathsTest < ActionController::TestCase
layout 'test/sub'
def hello_world; render(:template => 'test/hello_world'); end
end
-
+
def setup
# TestController.view_paths = nil
@@ -64,7 +64,7 @@ class ViewLoadPathsTest < ActionController::TestCase
@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
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index 5942950b15..621fb79915 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class WebServiceTest < ActionController::IntegrationTest
+class WebServiceTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
def assign_parameters
if params[:full]
@@ -24,12 +24,13 @@ class WebServiceTest < ActionController::IntegrationTest
def setup
@controller = TestController.new
+ @integration_session = nil
end
def test_check_parameters
with_test_route_set do
get "/"
- assert @controller.response.body.blank?
+ assert_blank @controller.response.body
end
end
@@ -161,7 +162,7 @@ class WebServiceTest < ActionController::IntegrationTest
def test_use_xml_ximple_with_empty_request
with_test_route_set do
assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} }
- assert @controller.response.body.blank?
+ assert_blank @controller.response.body
end
end
@@ -215,7 +216,7 @@ class WebServiceTest < ActionController::IntegrationTest
def test_typecast_as_yaml
with_test_route_set do
with_params_parsers Mime::YAML => :yaml do
- yaml = <<-YAML
+ yaml = (<<-YAML).strip
---
data:
a: 15
@@ -254,7 +255,7 @@ class WebServiceTest < ActionController::IntegrationTest
def with_test_route_set
with_routing do |set|
- set.draw do |map|
+ set.draw do
match '/', :to => 'web_service_test/test#assign_parameters'
end
yield
diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb
index 9df882ce75..eed2eca2ab 100644
--- a/actionpack/test/dispatch/callbacks_test.rb
+++ b/actionpack/test/dispatch/callbacks_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class DispatcherTest < Test::Unit::TestCase
+class DispatcherTest < ActiveSupport::TestCase
class Foo
cattr_accessor :a, :b
end
@@ -9,69 +9,13 @@ class DispatcherTest < Test::Unit::TestCase
def call(env)
[200, {}, 'response']
end
- end
+ end
def setup
Foo.a, Foo.b = 0, 0
- ActionDispatch::Callbacks.reset_callbacks(:prepare)
ActionDispatch::Callbacks.reset_callbacks(:call)
end
- def test_prepare_callbacks_with_cache_classes
- a = b = c = nil
- ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 }
- ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 }
- ActionDispatch::Callbacks.to_prepare { |*args| c = 3 }
-
- # Ensure to_prepare callbacks are not run when defined
- assert_nil a || b || c
-
- # Run callbacks
- dispatch
-
- assert_equal 1, a
- assert_equal 2, b
- assert_equal 3, c
-
- # Make sure they are only run once
- a = b = c = nil
- dispatch
- assert_nil a || b || c
- end
-
- def test_prepare_callbacks_without_cache_classes
- a = b = c = nil
- ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 }
- ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 }
- ActionDispatch::Callbacks.to_prepare { |*args| c = 3 }
-
- # Ensure to_prepare callbacks are not run when defined
- assert_nil a || b || c
-
- # Run callbacks
- dispatch(false)
-
- assert_equal 1, a
- assert_equal 2, b
- assert_equal 3, c
-
- # Make sure they are run again
- a = b = c = nil
- dispatch(false)
- assert_equal 1, a
- assert_equal 2, b
- assert_equal 3, c
- end
-
- def test_to_prepare_with_identifier_replaces
- ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a, Foo.b = 1, 1 }
- ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a = 2 }
-
- dispatch
- assert_equal 2, Foo.a
- assert_equal 0, Foo.b
- end
-
def test_before_and_after_callbacks
ActionDispatch::Callbacks.before { |*args| Foo.a += 1; Foo.b += 1 }
ActionDispatch::Callbacks.after { |*args| Foo.a += 1; Foo.b += 1 }
@@ -85,10 +29,22 @@ class DispatcherTest < Test::Unit::TestCase
assert_equal 4, Foo.b
end
+ def test_to_prepare_and_cleanup_delegation
+ prepared = cleaned = false
+ ActionDispatch::Callbacks.to_prepare { prepared = true }
+ ActionDispatch::Callbacks.to_prepare { cleaned = true }
+
+ ActionDispatch::Reloader.prepare!
+ assert prepared
+
+ ActionDispatch::Reloader.cleanup!
+ assert cleaned
+ end
+
private
- def dispatch(cache_classes = true, &block)
- @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new, !cache_classes)
+ def dispatch(&block)
+ @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new)
@dispatcher.call({'rack.input' => StringIO.new('')})
end
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index b04c1a42c0..39159fd629 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -48,6 +48,11 @@ class CookiesTest < ActionController::TestCase
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
@@ -89,6 +94,50 @@ class CookiesTest < ActionController::TestCase
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'] = "david"
+ 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
@@ -129,6 +178,26 @@ class CookiesTest < ActionController::TestCase
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_in_development
+ Rails.env.stubs(:development?).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
@@ -158,8 +227,8 @@ class CookiesTest < ActionController::TestCase
def test_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"]
+ assert_match(/Jamie/, @response.headers["Set-Cookie"])
+ assert_match(%r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"])
end
def test_signed_cookie
@@ -174,7 +243,7 @@ class CookiesTest < ActionController::TestCase
def test_permanent_signed_cookie
get :set_permanent_signed_cookie
- assert_match %r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"]
+ assert_match(%r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"])
assert_equal 100, @controller.send(:cookies).signed[:remember_me]
end
@@ -232,12 +301,181 @@ class CookiesTest < ActionController::TestCase
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
get :delete_cookie_with_domain
assert_response :success
assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
end
+ def test_cookie_with_all_domain_option_and_tld_length
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_a_non_standard_tld_and_tld_length
+ @request.host = "two.subdomains.nextangle.local"
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_host_with_port_and_tld_length
+ @request.host = "nextangle.local:3000"
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_deleting_cookie_with_all_domain_option_and_tld_length
+ get :delete_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
+ end
+
+ def test_cookie_with_several_preset_domains_using_one_of_these_domains
+ @request.host = "example1.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=example1.com; path=/"
+ end
+
+ def test_cookie_with_several_preset_domains_using_other_domain
+ @request.host = "other-domain.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_cookie_with_several_preset_domains_using_shared_domain
+ @request.host = "example3.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.example3.com; path=/"
+ end
+
+ def test_deletings_cookie_with_several_preset_domains_using_one_of_these_domains
+ @request.host = "example2.com"
+ get :delete_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=; domain=example2.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
+ end
+
+ def test_deletings_cookie_with_several_preset_domains_using_other_domain
+ @request.host = "other-domain.com"
+ get :delete_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
+ end
+
+ def test_cookies_hash_is_indifferent_access
+ [:symbol_key, :string_key].each do |cookie_key|
+ get cookie_key
+ assert_equal "david", cookies[:user_name]
+ assert_equal "david", cookies['user_name']
+ end
+ end
+
+ def test_setting_request_cookies_is_indifferent_access
+ @request.cookies.clear
+ @request.cookies[:user_name] = "andrew"
+ get :string_key_mock
+ assert_equal "david", cookies[:user_name]
+
+ @request.cookies.clear
+ @request.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_equal "user_name=david; path=/", @response.headers["Set-Cookie"]
+ assert_equal "david", cookies[:user_name]
+
+ get :noop
+ assert_nil @response.headers["Set-Cookie"]
+ assert_equal "user_name=david", @request.env['HTTP_COOKIE']
+ assert_equal "david", cookies[:user_name]
+
+ get :noop
+ assert_nil @response.headers["Set-Cookie"]
+ assert_equal "user_name=david", @request.env['HTTP_COOKIE']
+ assert_equal "david", cookies[:user_name]
+ end
+
+ def test_cookies_can_be_cleared
+ get :symbol_key
+ assert_equal "user_name=david; path=/", @response.headers["Set-Cookie"]
+ assert_equal "david", cookies[:user_name]
+
+ @request.cookies.clear
+ get :noop
+ assert_nil @response.headers["Set-Cookie"]
+ assert_nil @request.env['HTTP_COOKIE']
+ assert_nil cookies[:user_name]
+
+ get :symbol_key
+ assert_equal "user_name=david; path=/", @response.headers["Set-Cookie"]
+ assert_equal "david", cookies[:user_name]
+ end
+
+ def test_cookies_are_escaped
+ @request.cookies[:user_ids] = '1;2'
+ get :noop
+ assert_equal "user_ids=1%3B2", @request.env['HTTP_COOKIE']
+ assert_equal "1;2", cookies[:user_ids]
+ end
+
private
def assert_cookie_header(expected)
header = @response.headers["Set-Cookie"]
@@ -247,4 +485,13 @@ class CookiesTest < ActionController::TestCase
assert_equal expected.split("\n"), header
end
end
-end \ No newline at end of file
+
+ 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
diff --git a/actionpack/test/dispatch/middleware_stack/middleware_test.rb b/actionpack/test/dispatch/middleware_stack/middleware_test.rb
new file mode 100644
index 0000000000..9607f026db
--- /dev/null
+++ b/actionpack/test/dispatch/middleware_stack/middleware_test.rb
@@ -0,0 +1,77 @@
+require 'abstract_unit'
+require 'action_dispatch/middleware/stack'
+
+module ActionDispatch
+ class MiddlewareStack
+ class MiddlewareTest < ActiveSupport::TestCase
+ class Omg; end
+
+ {
+ 'concrete' => Omg,
+ 'anonymous' => Class.new
+ }.each do |name, klass|
+
+ define_method("test_#{name}_klass") do
+ mw = Middleware.new klass
+ assert_equal klass, mw.klass
+ end
+
+ define_method("test_#{name}_==") do
+ mw1 = Middleware.new klass
+ mw2 = Middleware.new klass
+ assert_equal mw1, mw2
+ end
+
+ end
+
+ def test_string_class
+ mw = Middleware.new Omg.name
+ assert_equal Omg, mw.klass
+ end
+
+ def test_double_equal_works_with_classes
+ k = Class.new
+ mw = Middleware.new k
+ assert_operator mw, :==, k
+
+ result = mw != Class.new
+ assert result, 'middleware should not equal other anon class'
+ end
+
+ def test_double_equal_works_with_strings
+ mw = Middleware.new Omg
+ assert_operator mw, :==, Omg.name
+ end
+
+ def test_double_equal_normalizes_strings
+ mw = Middleware.new Omg
+ assert_operator mw, :==, "::#{Omg.name}"
+ end
+
+ def test_middleware_loads_classnames_from_cache
+ mw = Class.new(Middleware) {
+ attr_accessor :classcache
+ }.new(Omg.name)
+
+ fake_cache = { mw.name => Omg }
+ mw.classcache = fake_cache
+
+ assert_equal Omg, mw.klass
+
+ fake_cache[mw.name] = Middleware
+ assert_equal Middleware, mw.klass
+ end
+
+ def test_middleware_always_returns_class
+ mw = Class.new(Middleware) {
+ attr_accessor :classcache
+ }.new(Omg)
+
+ fake_cache = { mw.name => Middleware }
+ mw.classcache = fake_cache
+
+ assert_equal Omg, mw.klass
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/middleware_stack_test.rb b/actionpack/test/dispatch/middleware_stack_test.rb
index 6a1a4f556f..831f3db3e2 100644
--- a/actionpack/test/dispatch/middleware_stack_test.rb
+++ b/actionpack/test/dispatch/middleware_stack_test.rb
@@ -4,6 +4,12 @@ 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
@@ -39,7 +45,16 @@ class MiddlewareStackTest < ActiveSupport::TestCase
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
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index 369212e2d0..11cf68fdb3 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -6,10 +6,57 @@ class MimeTypeTest < ActiveSupport::TestCase
test "parse single" do
Mime::LOOKUP.keys.each do |mime_type|
- assert_equal [Mime::Type.lookup(mime_type)], Mime::Type.parse(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]
+ 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]
@@ -41,11 +88,10 @@ class MimeTypeTest < ActiveSupport::TestCase
begin
Mime::Type.register("image/gif", :gif)
assert_nothing_raised do
- Mime::GIF
assert_equal Mime::GIF, Mime::SET.last
end
ensure
- Mime.module_eval { remove_const :GIF if const_defined?(:GIF) }
+ Mime::Type.unregister(:gif)
end
end
@@ -85,6 +131,13 @@ class MimeTypeTest < ActiveSupport::TestCase
assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
end
+ test "references gives preference to symbols before strings" do
+ assert_equal :html, Mime::HTML.ref
+ another = Mime::Type.lookup("foo/bar")
+ assert_nil another.to_sym
+ assert_equal "foo/bar", another.ref
+ end
+
test "regexp matcher" do
assert Mime::JS =~ "text/javascript"
assert Mime::JS =~ "application/javascript"
diff --git a/actionpack/test/dispatch/mount_test.rb b/actionpack/test/dispatch/mount_test.rb
index 00ca5ec9dc..1a032539b9 100644
--- a/actionpack/test/dispatch/mount_test.rb
+++ b/actionpack/test/dispatch/mount_test.rb
@@ -2,6 +2,17 @@ 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"]}"]]
@@ -10,6 +21,8 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
mount SprocketsApp, :at => "/sprockets"
mount SprocketsApp => "/shorthand"
+ mount FakeEngine, :at => "/fakeengine"
+
scope "/its_a" do
mount SprocketsApp, :at => "/sprocket"
end
@@ -28,9 +41,14 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
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_with_fake_engine_does_not_call_invalid_method
+ get "/fakeengine"
+ assert_equal "OK", response.body
+ end
end \ No newline at end of file
diff --git a/actionpack/test/dispatch/prefix_generation_test.rb b/actionpack/test/dispatch/prefix_generation_test.rb
new file mode 100644
index 0000000000..18f28deee4
--- /dev/null
+++ b/actionpack/test/dispatch/prefix_generation_test.rb
@@ -0,0 +1,317 @@
+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
+ match "/posts/:id", :to => "inside_engine_generating#show", :as => :post
+ match "/posts", :to => "inside_engine_generating#index", :as => :posts
+ match "/url_to_application", :to => "inside_engine_generating#url_to_application"
+ match "/polymorphic_path_for_engine", :to => "inside_engine_generating#polymorphic_path_for_engine"
+ match "/conflicting_url", :to => "inside_engine_generating#conflicting"
+ 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
+ match "/generate", :to => "outside_engine_generating#index"
+ match "/polymorphic_path_for_engine", :to => "outside_engine_generating#polymorphic_path_for_engine"
+ match "/polymorphic_with_url_for", :to => "outside_engine_generating#polymorphic_with_url_for"
+ match "/conflicting_url", :to => "outside_engine_generating#conflicting"
+ 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
+
+ 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
+
+ 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_with_url_for
+ render :text => blog_engine.url_for(Post.new)
+ end
+
+ def conflicting
+ render :text => "application"
+ 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
+
+ # 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 application's url includes default_url_options[:script_name]" do
+ RailsApplication.routes.default_url_options = {:script_name => "/something"}
+ get "/pure-awesomeness/blog/url_to_application"
+ assert_equal "/something/generate", last_response.body
+ end
+
+ test "[ENGINE] generating application's url should give higher priority to default_url_options[:script_name]" do
+ RailsApplication.routes.default_url_options = {:script_name => "/something"}
+ get "/pure-awesomeness/blog/url_to_application", {}, 'SCRIPT_NAME' => '/foo'
+ assert_equal "/something/generate", last_response.body
+ end
+
+ test "[ENGINE] generating engine's url with polymorphic path" do
+ get "/pure-awesomeness/blog/polymorphic_path_for_engine"
+ assert_equal "/pure-awesomeness/blog/posts/1", last_response.body
+ 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 route should give higher priority to default_url_options[:script_name]" do
+ RailsApplication.routes.default_url_options = {:script_name => "/something"}
+ get "/generate", {}, 'SCRIPT_NAME' => "/foo"
+ assert_equal "/something/awesome/blog/posts/1", last_response.body
+ end
+
+ test "[APP] generating engine's url with polymorphic path" do
+ get "/polymorphic_path_for_engine"
+ assert_equal "/awesome/blog/posts/1", last_response.body
+ 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
+
+ # Inside any Object
+ 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 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
+ match "/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/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb
new file mode 100644
index 0000000000..eaabc1feb3
--- /dev/null
+++ b/actionpack/test/dispatch/reloader_test.rb
@@ -0,0 +1,138 @@
+require 'abstract_unit'
+
+class ReloaderTest < Test::Unit::TestCase
+ Reloader = ActionDispatch::Reloader
+
+ def test_prepare_callbacks
+ a = b = c = nil
+ Reloader.to_prepare { |*args| a = b = c = 1 }
+ Reloader.to_prepare { |*args| b = c = 2 }
+ Reloader.to_prepare { |*args| c = 3 }
+
+ # Ensure to_prepare callbacks are not run when defined
+ assert_nil a || b || c
+
+ # Run callbacks
+ call_and_return_body
+
+ assert_equal 1, a
+ assert_equal 2, b
+ assert_equal 3, c
+ end
+
+ class MyBody < Array
+ def initialize(&block)
+ @on_close = block
+ end
+
+ def foo
+ "foo"
+ end
+
+ def bar
+ "bar"
+ end
+
+ def close
+ @on_close.call if @on_close
+ end
+ end
+
+ def test_returned_body_object_always_responds_to_close
+ body = call_and_return_body
+ assert_respond_to body, :close
+ end
+
+ def test_returned_body_object_behaves_like_underlying_object
+ body = call_and_return_body do
+ b = MyBody.new
+ b << "hello"
+ b << "world"
+ [200, { "Content-Type" => "text/html" }, b]
+ end
+ assert_equal 2, body.size
+ assert_equal "hello", body[0]
+ assert_equal "world", body[1]
+ assert_equal "foo", body.foo
+ assert_equal "bar", body.bar
+ end
+
+ def test_it_calls_close_on_underlying_object_when_close_is_called_on_body
+ close_called = false
+ body = call_and_return_body do
+ b = MyBody.new do
+ close_called = true
+ end
+ [200, { "Content-Type" => "text/html" }, b]
+ end
+ body.close
+ assert close_called
+ end
+
+ def test_returned_body_object_responds_to_all_methods_supported_by_underlying_object
+ body = call_and_return_body do
+ [200, { "Content-Type" => "text/html" }, MyBody.new]
+ end
+ assert_respond_to body, :size
+ assert_respond_to body, :each
+ assert_respond_to body, :foo
+ assert_respond_to body, :bar
+ end
+
+ def test_cleanup_callbacks_are_called_when_body_is_closed
+ cleaned = false
+ Reloader.to_cleanup { cleaned = true }
+
+ body = call_and_return_body
+ assert !cleaned
+
+ body.close
+ assert cleaned
+ end
+
+ def test_prepare_callbacks_arent_called_when_body_is_closed
+ prepared = false
+ Reloader.to_prepare { prepared = true }
+
+ body = call_and_return_body
+ prepared = false
+
+ body.close
+ assert !prepared
+ end
+
+ def test_manual_reloading
+ prepared = cleaned = false
+ Reloader.to_prepare { prepared = true }
+ Reloader.to_cleanup { cleaned = true }
+
+ Reloader.prepare!
+ assert prepared
+ assert !cleaned
+
+ prepared = cleaned = false
+ Reloader.cleanup!
+ assert !prepared
+ assert cleaned
+ end
+
+ def test_cleanup_callbacks_are_called_on_exceptions
+ cleaned = false
+ Reloader.to_cleanup { cleaned = true }
+
+ begin
+ call_and_return_body do
+ raise "error"
+ end
+ rescue
+ end
+
+ assert cleaned
+ end
+
+ private
+ def call_and_return_body(&block)
+ @reloader ||= Reloader.new(block || proc {[200, {}, 'response']})
+ @reloader.call({'rack.input' => StringIO.new('')})[2]
+ end
+end
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
index 0faa99a912..34db7a4c66 100644
--- a/actionpack/test/dispatch/request/json_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class JsonParamsParsingTest < ActionController::IntegrationTest
+class JsonParamsParsingTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters
@@ -56,7 +56,7 @@ class JsonParamsParsingTest < ActionController::IntegrationTest
def with_test_routing
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => ::JsonParamsParsingTest::TestController
end
yield
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index e3ec5cf182..3ff558ec5a 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class MultipartParamsParsingTest < ActionController::IntegrationTest
+class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters
@@ -36,7 +36,6 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
assert_equal 'bar', params['foo']
file = params['file']
- assert_kind_of Tempfile, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
assert_equal 'contents', file.read
@@ -49,8 +48,6 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
file = params['file']
foo = params['foo']
- assert_kind_of Tempfile, file
-
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
@@ -64,11 +61,9 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
file = params['file']
- assert_kind_of Tempfile, file
-
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
- assert ('a' * 20480) == file.read
+ assert_equal(('a' * 20480), file.read)
end
test "parses binary file" do
@@ -77,13 +72,11 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
assert_equal 'bar', params['foo']
file = params['file']
- assert_kind_of Tempfile, file
assert_equal 'file.csv', file.original_filename
assert_nil file.content_type
assert_equal 'contents', file.read
file = params['flowers']
- assert_kind_of Tempfile, file
assert_equal 'flowers.jpg', file.original_filename
assert_equal "image/jpeg", file.content_type
assert_equal 19512, file.size
@@ -156,7 +149,7 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
def with_test_routing
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => 'multipart_params_parsing_test/test'
end
yield
diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb
index 071d80c5b0..f6a1475d04 100644
--- a/actionpack/test/dispatch/request/query_string_parsing_test.rb
+++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class QueryStringParsingTest < ActionController::IntegrationTest
+class QueryStringParsingTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_query_parameters
@@ -108,7 +108,7 @@ class QueryStringParsingTest < ActionController::IntegrationTest
private
def assert_parses(expected, actual)
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => ::QueryStringParsingTest::TestController
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
index 0bcef81534..04a0fb6f34 100644
--- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class UrlEncodedParamsParsingTest < ActionController::IntegrationTest
+class UrlEncodedParamsParsingTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters, :last_request_type
@@ -129,7 +129,7 @@ class UrlEncodedParamsParsingTest < ActionController::IntegrationTest
private
def with_test_routing
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => ::UrlEncodedParamsParsingTest::TestController
end
yield
diff --git a/actionpack/test/dispatch/request/xml_params_parsing_test.rb b/actionpack/test/dispatch/request/xml_params_parsing_test.rb
index d44c642420..ad9de02eb4 100644
--- a/actionpack/test/dispatch/request/xml_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/xml_params_parsing_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class XmlParamsParsingTest < ActionController::IntegrationTest
+class XmlParamsParsingTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
class << self
attr_accessor :last_request_parameters
@@ -18,6 +18,7 @@ class XmlParamsParsingTest < ActionController::IntegrationTest
test "parses a strict rack.input" do
class Linted
+ undef call if method_defined?(:call)
def call(env)
bar = env['action_dispatch.request.request_parameters']['foo']
result = "<ok>#{bar}</ok>"
@@ -96,7 +97,7 @@ class XmlParamsParsingTest < ActionController::IntegrationTest
private
def with_test_routing
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => ::XmlParamsParsingTest::TestController
end
yield
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index c8947aac80..f03ae7f2b3 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -1,6 +1,31 @@
require 'abstract_unit'
class RequestTest < ActiveSupport::TestCase
+
+ def url_for(options = {})
+ options.reverse_merge!(:host => 'www.example.com')
+ 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', url_for
+ assert_equal 'http://api.example.com', url_for(:subdomain => 'api')
+ 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' })
+ end
+
test "remote ip" do
request = stub_request 'REMOTE_ADDR' => '1.2.3.4'
assert_equal '1.2.3.4', request.remote_ip
@@ -45,9 +70,9 @@ class RequestTest < ActiveSupport::TestCase
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
+ 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)
# turn IP Spoofing detection off.
# This is useful for sites that are aimed at non-IP clients. The typical
@@ -96,6 +121,9 @@ class RequestTest < ActiveSupport::TestCase
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
@@ -116,6 +144,9 @@ class RequestTest < ActiveSupport::TestCase
request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk"
assert_equal %w( dev www ), request.subdomains(2)
+ request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk", :tld_length => 2
+ assert_equal %w( dev www ), request.subdomains
+
request = stub_request 'HTTP_HOST' => "foobar.foobar.com"
assert_equal %w( foobar ), request.subdomains
@@ -132,12 +163,46 @@ class RequestTest < ActiveSupport::TestCase
assert_equal [], request.subdomains
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
+ assert_equal '', request.port_string
request = stub_request 'HTTP_HOST' => 'www.example.org:8080'
- assert_equal ":8080", request.port_string
+ assert_equal ':8080', request.port_string
end
test "full path" do
@@ -223,6 +288,16 @@ class RequestTest < ActiveSupport::TestCase
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, :put, :delete].each do |method|
request = stub_request 'REQUEST_METHOD' => method.to_s.upcase
@@ -346,6 +421,18 @@ class RequestTest < ActiveSupport::TestCase
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
+ begin
+ request = stub_request(mock_rack_env)
+ request.parameters
+ rescue TypeError
+ # rack will raise a TypeError when parsing this query string
+ end
+ assert_equal({}, request.parameters)
+ end
+
test "formats with accept header" do
request = stub_request 'HTTP_ACCEPT' => 'text/html'
request.expects(:parameters).at_least_once.returns({})
@@ -428,15 +515,56 @@ class RequestTest < ActiveSupport::TestCase
assert_equal "[FILTERED]", request.raw_post
assert_equal "[FILTERED]", request.params["amount"]
- assert_equal "1", request.params["step"]
+ 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
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
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index c20fa10f63..6f38714b2e 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -11,9 +11,7 @@ class ResponseTest < ActiveSupport::TestCase
status, headers, body = @response.to_a
assert_equal 200, status
assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "max-age=0, private, must-revalidate",
- "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"'
+ "Content-Type" => "text/html; charset=utf-8"
}, headers)
parts = []
@@ -21,15 +19,17 @@ class ResponseTest < ActiveSupport::TestCase
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, body = @response.to_a
+ status, headers, _ = @response.to_a
assert_equal 200, status
assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "max-age=0, private, must-revalidate",
- "ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"'
+ "Content-Type" => "text/html; charset=utf-8"
}, headers)
end
@@ -41,8 +41,7 @@ class ResponseTest < ActiveSupport::TestCase
status, headers, body = @response.to_a
assert_equal 200, status
assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "no-cache"
+ "Content-Type" => "text/html; charset=utf-8"
}, headers)
parts = []
@@ -53,20 +52,20 @@ class ResponseTest < ActiveSupport::TestCase
test "content type" do
[204, 304].each do |c|
@response.status = c.to_s
- status, headers, body = @response.to_a
+ _, headers, _ = @response.to_a
assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
end
[200, 302, 404, 500].each do |c|
@response.status = c.to_s
- status, headers, body = @response.to_a
+ _, headers, _ = @response.to_a
assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
end
end
test "does not include Status header" do
@response.status = "200 OK"
- status, headers, body = @response.to_a
+ _, headers, _ = @response.to_a
assert !headers.has_key?('Status')
end
@@ -120,10 +119,10 @@ class ResponseTest < ActiveSupport::TestCase
end
test "read cache control" do
- resp = ActionDispatch::Response.new.tap { |resp|
- resp.cache_control[:public] = true
- resp.etag = '123'
- resp.body = 'Hello'
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.cache_control[:public] = true
+ response.etag = '123'
+ response.body = 'Hello'
}
resp.to_a
@@ -135,10 +134,10 @@ class ResponseTest < ActiveSupport::TestCase
end
test "read charset and content type" do
- resp = ActionDispatch::Response.new.tap { |resp|
- resp.charset = 'utf-16'
- resp.content_type = Mime::XML
- resp.body = 'Hello'
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.charset = 'utf-16'
+ response.content_type = Mime::XML
+ response.body = 'Hello'
}
resp.to_a
diff --git a/actionpack/test/dispatch/routing_assertions_test.rb b/actionpack/test/dispatch/routing_assertions_test.rb
new file mode 100644
index 0000000000..9f95d82129
--- /dev/null
+++ b/actionpack/test/dispatch/routing_assertions_test.rb
@@ -0,0 +1,103 @@
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+class SecureArticlesController < ArticlesController; end
+class BlockArticlesController < ArticlesController; end
+
+class RoutingAssertionsTest < ActionController::TestCase
+
+ def setup
+ @routes = ActionDispatch::Routing::RouteSet.new
+ @routes.draw do
+ resources :articles
+
+ scope 'secure', :constraints => { :protocol => 'https://' } do
+ resources :articles, :controller => 'secure_articles'
+ end
+
+ scope 'block', :constraints => lambda { |r| r.ssl? } do
+ resources :articles, :controller => 'block_articles'
+ end
+ end
+ end
+
+ def test_assert_generates
+ assert_generates('/articles', { :controller => 'articles', :action => 'index' })
+ assert_generates('/articles/1', { :controller => 'articles', :action => 'show', :id => '1' })
+ end
+
+ def test_assert_generates_with_defaults
+ assert_generates('/articles/1/edit', { :controller => 'articles', :action => 'edit' }, { :id => '1' })
+ end
+
+ def test_assert_generates_with_extras
+ assert_generates('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, {}, { :page => '1' })
+ end
+
+ def test_assert_recognizes
+ assert_recognizes({ :controller => 'articles', :action => 'index' }, '/articles')
+ assert_recognizes({ :controller => 'articles', :action => 'show', :id => '1' }, '/articles/1')
+ end
+
+ def test_assert_recognizes_with_extras
+ assert_recognizes({ :controller => 'articles', :action => 'index', :page => '1' }, '/articles', { :page => '1' })
+ end
+
+ def test_assert_recognizes_with_method
+ assert_recognizes({ :controller => 'articles', :action => 'create' }, { :path => '/articles', :method => :post })
+ assert_recognizes({ :controller => 'articles', :action => 'update', :id => '1' }, { :path => '/articles/1', :method => :put })
+ end
+
+ def test_assert_recognizes_with_hash_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'http://test.host/secure/articles')
+ end
+ assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'https://test.host/secure/articles')
+ end
+
+ def test_assert_recognizes_with_block_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'http://test.host/block/articles')
+ end
+ assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'https://test.host/block/articles')
+ end
+
+ def test_assert_routing
+ assert_routing('/articles', :controller => 'articles', :action => 'index')
+ end
+
+ def test_assert_routing_with_defaults
+ assert_routing('/articles/1/edit', { :controller => 'articles', :action => 'edit', :id => '1' }, { :id => '1' })
+ end
+
+ def test_assert_routing_with_extras
+ assert_routing('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, { }, { :page => '1' })
+ end
+
+ def test_assert_routing_with_hash_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_routing('http://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' })
+ end
+ assert_routing('https://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' })
+ end
+
+ def test_assert_routing_with_block_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_routing('http://test.host/block/articles', { :controller => 'block_articles', :action => 'index' })
+ end
+ assert_routing('https://test.host/block/articles', { :controller => 'block_articles', :action => 'index' })
+ end
+
+ def test_with_routing
+ with_routing do |routes|
+ routes.draw do
+ resources :articles, :path => 'artikel'
+ end
+
+ assert_routing('/artikel', :controller => 'articles', :action => 'index')
+ assert_raise(ActionController::RoutingError) do
+ assert_routing('/articles', { :controller => 'articles', :action => 'index' })
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 3f090b7254..5e5758a60e 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -13,6 +13,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ class YoutubeFavoritesRedirector
+ def self.call(params, request)
+ "http://www.youtube.com/watch?v=#{params[:youtube_id]}"
+ end
+ end
+
stub_controllers do |routes|
Routes = routes
Routes.draw do
@@ -40,11 +46,29 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get :new, :path => "build"
post :create, :path => "create", :as => ""
put :update
+ get :remove, :action => :destroy, :as => :remove
+ end
+
+ scope "pagemark", :controller => "pagemarks", :as => :pagemark do
+ get "new", :path => "build"
+ post "create", :as => ""
+ put "update"
get "remove", :action => :destroy, :as => :remove
end
match 'account/logout' => redirect("/logout"), :as => :logout_redirect
match 'account/login', :to => redirect("/login")
+ match 'secure', :to => redirect("/secure/login")
+
+ match 'mobile', :to => redirect(:subdomain => 'mobile')
+ match 'documentation', :to => redirect(:domain => 'example-documentation.com', :path => '')
+ match 'new_documentation', :to => redirect(:path => '/documentation/new')
+ match 'super_new_documentation', :to => redirect(:host => 'super-docs.com')
+
+ match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}')
+ match 'stores/:name(*rest)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{rest}')
+
+ match 'youtube_favorites/:youtube_id/:name', :to => redirect(YoutubeFavoritesRedirector)
constraints(lambda { |req| true }) do
match 'account/overview'
@@ -128,7 +152,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
member do
- get :some_path_with_name
+ get 'some_path_with_name'
put :accessible_projects
post :resend, :generate_new_password
end
@@ -147,6 +171,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
resources :replies do
+ collection do
+ get 'page/:page' => 'replies#index', :page => %r{\d+}
+ get ':page' => 'replies#index', :page => %r{\d+}
+ end
+
new do
post :preview
end
@@ -158,7 +187,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
resources :posts, :only => [:index, :show] do
- resources :comments, :except => :destroy
+ namespace :admin do
+ root :to => "index#index"
+ end
+ resources :comments, :except => :destroy do
+ get "views" => "comments#views", :as => :views
+ end
end
resource :past, :only => :destroy
@@ -176,6 +210,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ scope '/hello' do
+ shallow do
+ resources :notes do
+ resources :trackbacks
+ end
+ end
+ end
+
resources :threads, :shallow => true do
resource :owner
resources :messages do
@@ -187,7 +229,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- resources :sheep
+ resources :sheep do
+ get "_it", :on => :member
+ end
resources :clients do
namespace :google do
@@ -200,22 +244,28 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
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
+ 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(.:format)" => "avatars#thumbnail", :as => :thumbnail, :on => :member
+ get "thumbnail" => "avatars#thumbnail", :as => :thumbnail, :on => :member
end
resources :invoices do
- get "outstanding" => "invoices#outstanding", :as => :outstanding, :on => :collection
+ 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
+ get "aged/:months", :on => :collection, :action => :aged, :as => :aged
end
resources :notes, :shallow => true do
get "preview" => "notes#preview", :as => :preview, :on => :new
get "print" => "notes#print", :as => :print, :on => :member
end
+ get "inactive", :on => :collection
+ post "deactivate", :on => :member
+ get "old", :on => :collection, :as => :stale
+ get "export"
end
namespace :api do
@@ -337,6 +387,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
resources :content
+ namespace :transport do
+ resources :taxis
+ end
+
+ namespace :medical do
+ resource :taxis
+ end
+
scope :constraints => { :id => /\d+/ } do
get '/tickets', :to => 'tickets#index', :as => :tickets
end
@@ -371,6 +429,15 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ namespace :wiki do
+ resources :articles, :id => /[^\/]+/ do
+ resources :comments, :only => [:create, :new]
+ end
+ end
+
+ resources :wiki_pages, :path => :pages
+ resource :wiki_account, :path => :my_account
+
scope :only => :show do
namespace :only do
resources :sectors, :only => :index do
@@ -405,11 +472,41 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ resources :sections, :id => /.+/ do
+ get :preview, :on => :member
+ end
+
+ 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
+
+ get "/fc/:id", :as => :forced_collision, :to => "forced_collision#show"
+ get "/forced_collision", :as => :forced_collision, :to => "forced_collision#show"
+ end
+
+ match '/purchases/:token/:filename',
+ :to => 'purchases#fetch',
+ :token => /[[:alnum:]]{10}/,
+ :filename => /(.+)/,
+ :as => :purchase
+
+ resources :lists, :id => /([A-Za-z0-9]{25})|default/ do
+ resources :todos, :id => /\d+/
+ end
+
+ scope '/countries/:country', :constraints => lambda { |params, req| %[all France].include?(params[:country]) } do
+ match '/', :to => 'countries#index'
+ match '/cities', :to => 'countries#cities'
+ end
+
+ match '/countries/:country/(*other)', :to => redirect{ |params, req| params[:other] ? "/countries/all/#{params[:other]}" : '/countries/all' }
+
match '/:locale/*file.:format', :to => 'files#show', :file => /path\/to\/existing\/file/
end
end
- class TestAltApp < ActionController::IntegrationTest
+ class TestAltApp < ActionDispatch::IntegrationTest
class AltRequest
def initialize(env)
@env = env
@@ -599,6 +696,55 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_redirect_hash_with_subdomain
+ with_test_routes do
+ get '/mobile'
+ verify_redirect 'http://mobile.example.com/mobile'
+ end
+ end
+
+ def test_redirect_hash_with_domain_and_path
+ with_test_routes do
+ get '/documentation'
+ verify_redirect 'http://www.example-documentation.com'
+ end
+ end
+
+ def test_redirect_hash_with_path
+ with_test_routes do
+ get '/new_documentation'
+ verify_redirect 'http://www.example.com/documentation/new'
+ end
+ end
+
+ def test_redirect_hash_with_host
+ with_test_routes do
+ get '/super_new_documentation?section=top'
+ verify_redirect 'http://super-docs.com/super_new_documentation?section=top'
+ end
+ end
+
+ def test_redirect_hash_path_substitution
+ with_test_routes do
+ get '/stores/iernest'
+ verify_redirect 'http://stores.example.com/iernest'
+ end
+ end
+
+ def test_redirect_hash_path_substitution_with_catch_all
+ with_test_routes do
+ get '/stores/iernest/products'
+ verify_redirect 'http://stores.example.com/iernest/products'
+ end
+ end
+
+ def test_redirect_class
+ with_test_routes do
+ get '/youtube_favorites/oHg5SJYRHA0/rick-rolld'
+ verify_redirect 'http://www.youtube.com/watch?v=oHg5SJYRHA0'
+ end
+ end
+
def test_openid
with_test_routes do
get '/openid/login'
@@ -613,15 +759,15 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/bookmark/build'
assert_equal 'bookmarks#new', @response.body
- assert_equal '/bookmark/build', new_bookmark_path
+ assert_equal '/bookmark/build', bookmark_new_path
post '/bookmark/create'
assert_equal 'bookmarks#create', @response.body
assert_equal '/bookmark/create', bookmark_path
- put '/bookmark'
+ put '/bookmark/update'
assert_equal 'bookmarks#update', @response.body
- assert_equal '/bookmark', update_bookmark_path
+ assert_equal '/bookmark/update', bookmark_update_path
get '/bookmark/remove'
assert_equal 'bookmarks#destroy', @response.body
@@ -629,6 +775,26 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_pagemarks
+ with_test_routes do
+ 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
+ end
+
def test_admin
with_test_routes do
get '/admin', {}, {'REMOTE_ADDR' => '192.168.1.100'}
@@ -963,6 +1129,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
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
end
@@ -1141,14 +1308,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- def test_index
- with_test_routes do
- assert_equal '/info', info_path
- get '/info'
- assert_equal 'projects#info', @response.body
- end
- end
-
def test_match_shorthand_with_no_scope
with_test_routes do
assert_equal '/account/overview', account_overview_path
@@ -1165,6 +1324,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_dynamically_generated_helpers_on_collection_do_not_clobber_resources_url_helper
+ with_test_routes do
+ assert_equal '/replies', replies_path
+ end
+ end
+
def test_scoped_controller_with_namespace_and_action
with_test_routes do
assert_equal '/account/twitter/callback', account_callback_path("twitter")
@@ -1524,11 +1689,66 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_shallow_nested_resources_within_scope
+ with_test_routes do
+
+ get '/hello/notes/1/trackbacks'
+ assert_equal 'trackbacks#index', @response.body
+ assert_equal '/hello/notes/1/trackbacks', note_trackbacks_path(:note_id => 1)
+
+ get '/hello/notes/1/edit'
+ assert_equal 'notes#edit', @response.body
+ assert_equal '/hello/notes/1/edit', edit_note_path(:id => '1')
+
+ get '/hello/notes/1/trackbacks/new'
+ assert_equal 'trackbacks#new', @response.body
+ assert_equal '/hello/notes/1/trackbacks/new', new_note_trackback_path(:note_id => 1)
+
+ get '/hello/trackbacks/1'
+ assert_equal 'trackbacks#show', @response.body
+ assert_equal '/hello/trackbacks/1', trackback_path(:id => '1')
+
+ get '/hello/trackbacks/1/edit'
+ assert_equal 'trackbacks#edit', @response.body
+ assert_equal '/hello/trackbacks/1/edit', edit_trackback_path(:id => '1')
+
+ put '/hello/trackbacks/1'
+ assert_equal 'trackbacks#update', @response.body
+
+ post '/hello/notes/1/trackbacks'
+ assert_equal 'trackbacks#create', @response.body
+
+ delete '/hello/trackbacks/1'
+ assert_equal 'trackbacks#destroy', @response.body
+
+ get '/hello/notes'
+ assert_equal 'notes#index', @response.body
+
+ post '/hello/notes'
+ assert_equal 'notes#create', @response.body
+
+ get '/hello/notes/new'
+ assert_equal 'notes#new', @response.body
+ assert_equal '/hello/notes/new', new_note_path
+
+ get '/hello/notes/1'
+ assert_equal 'notes#show', @response.body
+ assert_equal '/hello/notes/1', note_path(:id => 1)
+
+ put '/hello/notes/1'
+ assert_equal 'notes#update', @response.body
+
+ delete '/hello/notes/1'
+ assert_equal 'notes#destroy', @response.body
+ end
+ end
+
def test_custom_resource_routes_are_scoped
with_test_routes do
assert_equal '/customers/recent', recent_customers_path
assert_equal '/customers/1/profile', profile_customer_path(:id => '1')
- assert_equal '/customers/new/preview', preview_new_customer_path
+ 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')
@@ -1541,6 +1761,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get '/customers/1/invoices/overdue'
assert_equal 'invoices#overdue', @response.body
+
+ get '/customers/1/secret/profile'
+ assert_equal 'customers#secret', @response.body
end
end
@@ -1884,11 +2107,269 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_resources_are_not_pluralized
+ with_test_routes do
+ 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
+ end
+
+ def test_singleton_resources_are_not_singularized
+ with_test_routes do
+ get '/medical/taxis/new'
+ assert_equal 'medical/taxes#new', @response.body
+ assert_equal '/medical/taxis/new', new_medical_taxis_path
+
+ post '/medical/taxis'
+ assert_equal 'medical/taxes#create', @response.body
+
+ get '/medical/taxis'
+ assert_equal 'medical/taxes#show', @response.body
+ assert_equal '/medical/taxis', medical_taxis_path
+
+ get '/medical/taxis/edit'
+ assert_equal 'medical/taxes#edit', @response.body
+ assert_equal '/medical/taxis/edit', edit_medical_taxis_path
+
+ put '/medical/taxis'
+ assert_equal 'medical/taxes#update', @response.body
+
+ delete '/medical/taxis'
+ assert_equal 'medical/taxes#destroy', @response.body
+ end
+ end
+
+ def test_greedy_resource_id_regexp_doesnt_match_edit_and_custom_action
+ with_test_routes do
+ 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
+ end
+
+ def test_resource_constraints_are_pushed_to_scope
+ with_test_routes do
+ 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
+ end
+
+ def test_resources_path_can_be_a_symbol
+ with_test_routes do
+ 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
+ end
+
+ def test_redirect_https
+ with_test_routes do
+ with_https do
+ get '/secure'
+ verify_redirect 'https://www.example.com/secure/login'
+ end
+ end
+ end
+
+ def test_symbolized_path_parameters_is_not_stale
+ 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_custom_resource_actions_defined_using_string
+ 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
+ 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
+ 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
+ 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::RoutingError){ list_todo_path(:list_id => '2', :id => '1') }
+ end
+
+ def test_named_routes_collision_is_avoided_unless_explicitly_given_as
+ assert_equal "/c/1", routes_collision_path(1)
+ assert_equal "/forced_collision", routes_forced_collision_path
+ end
+
+ def test_explicitly_avoiding_the_named_route
+ assert !respond_to?(:routes_no_collision_path)
+ end
+
+ def test_controller_name_with_leading_slash_raise_error
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/feeds/:service', :to => '/feeds#show' }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/feeds/:service', :controller => '/feeds', :action => 'show' }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/api/feeds/:service', :to => '/api/feeds#show' }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { controller("/feeds") { get '/feeds/:service', :to => :show } }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { resources :feeds, :controller => '/feeds' }
+ end
+ end
+ end
+
+ def test_invalid_route_name_raises_error
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/products', :to => 'products#index', :as => 'products ' }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/products', :to => 'products#index', :as => ' products' }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/products', :to => 'products#index', :as => 'products!' }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/products', :to => 'products#index', :as => 'products index' }
+ end
+ end
+
+ assert_raise(ArgumentError) do
+ self.class.stub_controllers do |routes|
+ routes.draw { get '/products', :to => 'products#index', :as => '1products' }
+ end
+ end
+ end
+
+ def test_nested_route_in_nested_resource
+ get "/posts/1/comments/2/views"
+ assert_equal "comments#views", @response.body
+ assert_equal "/posts/1/comments/2/views", post_comment_views_path(:post_id => '1', :comment_id => '2')
+ end
+
+ def test_root_in_deeply_nested_scope
+ get "/posts/1/admin"
+ assert_equal "admin/index#index", @response.body
+ assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1')
+ end
+
private
def with_test_routes
yield
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']
@@ -1899,3 +2380,96 @@ private
%(<html><body>You are being <a href="#{ERB::Util.h(url)}">redirected</a>.</body></html>)
end
end
+
+class TestAppendingRoutes < ActionDispatch::IntegrationTest
+ def simple_app(resp)
+ lambda { |e| [ 200, { 'Content-Type' => 'text/plain' }, [resp] ] }
+ end
+
+ setup do
+ s = self
+ @app = ActionDispatch::Routing::RouteSet.new
+ @app.append do
+ match '/hello' => s.simple_app('fail')
+ match '/goodbye' => s.simple_app('goodbye')
+ end
+
+ @app.draw do
+ match '/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 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
diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index 3864821ef0..27f55fd7ab 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
require 'stringio'
-class CookieStoreTest < ActionController::IntegrationTest
+class CookieStoreTest < ActionDispatch::IntegrationTest
SessionKey = '_myapp_session'
SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
@@ -53,18 +53,6 @@ class CookieStoreTest < ActionController::IntegrationTest
def rescue_action(e) raise end
end
- def test_raises_argument_error_if_missing_session_key
- assert_raise(ArgumentError, nil.inspect) {
- ActionDispatch::Session::CookieStore.new(nil,
- :key => nil, :secret => SessionSecret)
- }
-
- assert_raise(ArgumentError, ''.inspect) {
- ActionDispatch::Session::CookieStore.new(nil,
- :key => '', :secret => SessionSecret)
- }
- end
-
def test_setting_session_value
with_test_route_set do
get '/set_session_value'
@@ -106,6 +94,23 @@ class CookieStoreTest < ActionController::IntegrationTest
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_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"
@@ -118,11 +123,11 @@ class CookieStoreTest < ActionController::IntegrationTest
assert_equal 'id: ce8b0752a6ab7c7af3cdb8a80e6b9e46', response.body, "should auto-load unloaded class"
end
end
- end
-
+ end
+
def test_deserializes_unloaded_classes_on_get_value
with_test_route_set do
- with_autoload_path "session_autoload_test" do
+ with_autoload_path "session_autoload_test" do
cookies[SessionKey] = SignedSerializedCookie
get '/get_session_value'
assert_response :success
@@ -189,7 +194,6 @@ class CookieStoreTest < ActionController::IntegrationTest
with_test_route_set do
get '/set_session_value'
assert_response :success
- session_payload = response.body
assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
headers['Set-Cookie']
@@ -262,12 +266,12 @@ class CookieStoreTest < ActionController::IntegrationTest
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']
+ assert_match(/domain=example\.es/, headers['Set-Cookie'])
headers['Set-Cookie']
end
end
- def test_session_store_without_domain
+ def test_session_store_without_domain
with_test_route_set do
get '/set_session_value'
assert_no_match(/domain\=/, headers['Set-Cookie'])
@@ -298,7 +302,7 @@ class CookieStoreTest < ActionController::IntegrationTest
def with_test_route_set(options = {})
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => ::CookieStoreTest::TestController
end
diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb
index 9bd6f9b8c4..8502bc547b 100644
--- a/actionpack/test/dispatch/session/mem_cache_store_test.rb
+++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
# You need to start a memcached server inorder to run these tests
-class MemCacheStoreTest < ActionController::IntegrationTest
+class MemCacheStoreTest < ActionDispatch::IntegrationTest
class TestController < ActionController::Base
def no_session_access
head :ok
@@ -11,7 +11,7 @@ class MemCacheStoreTest < ActionController::IntegrationTest
session[:foo] = "bar"
head :ok
end
-
+
def set_serialized_session_value
session[:foo] = SessionAutoloadTest::Foo.new
head :ok
@@ -174,7 +174,7 @@ class MemCacheStoreTest < ActionController::IntegrationTest
private
def with_test_route_set
with_routing do |set|
- set.draw do |map|
+ set.draw do
match ':action', :to => ::MemCacheStoreTest::TestController
end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index 4966527f4d..2a478c214f 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -1,20 +1,7 @@
require 'abstract_unit'
-module ActionDispatch
- class ShowExceptions
- private
- def public_path
- "#{FIXTURE_LOAD_PATH}/public"
- end
-
- # Silence logger
- def logger
- nil
- end
- end
-end
+class ShowExceptionsTest < ActionDispatch::IntegrationTest
-class ShowExceptionsTest < ActionController::IntegrationTest
Boomer = lambda do |env|
req = ActionDispatch::Request.new(env)
case req.path
@@ -26,6 +13,8 @@ class ShowExceptionsTest < ActionController::IntegrationTest
raise ActionController::NotImplemented
when "/unprocessable_entity"
raise ActionController::InvalidAuthenticityToken
+ when "/not_found_original_exception"
+ raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new)
else
raise "puke!"
end
@@ -58,15 +47,15 @@ class ShowExceptionsTest < ActionController::IntegrationTest
get "/", {}, {'action_dispatch.show_exceptions' => true}
assert_response 500
- assert_match /puke/, body
+ assert_match(/puke/, body)
get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
assert_response 404
- assert_match /#{ActionController::UnknownAction.name}/, body
+ assert_match(/#{ActionController::UnknownAction.name}/, body)
get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
assert_response 405
- assert_match /ActionController::MethodNotAllowed/, body
+ assert_match(/ActionController::MethodNotAllowed/, body)
end
end
@@ -96,15 +85,15 @@ class ShowExceptionsTest < ActionController::IntegrationTest
get "/", {}, {'action_dispatch.show_exceptions' => true}
assert_response 500
- assert_match /puke/, body
+ assert_match(/puke/, body)
get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
assert_response 404
- assert_match /#{ActionController::UnknownAction.name}/, body
+ assert_match(/#{ActionController::UnknownAction.name}/, body)
get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
assert_response 405
- assert_match /ActionController::MethodNotAllowed/, body
+ assert_match(/ActionController::MethodNotAllowed/, body)
end
test "does not show filtered parameters" do
@@ -113,6 +102,23 @@ class ShowExceptionsTest < ActionController::IntegrationTest
get "/", {"foo"=>"bar"}, {'action_dispatch.show_exceptions' => true,
'action_dispatch.parameter_filter' => [:foo]}
assert_response 500
- assert_match "&quot;foo&quot;=&gt;&quot;[FILTERED]&quot;", body
+ assert_match("&quot;foo&quot;=&gt;&quot;[FILTERED]&quot;", body)
+ end
+
+ test "show registered original exception for wrapped exceptions when consider_all_requests_local is false" do
+ @app = ProductionApp
+ self.remote_addr = '208.77.188.166'
+
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/404 error/, body)
+ end
+
+ test "show registered original exception for wrapped exceptions when consider_all_requests_local is true" do
+ @app = DevelopmentApp
+
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/AbstractController::ActionNotFound/, body)
end
end
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
index e6957bb0ea..655745a848 100644
--- a/actionpack/test/dispatch/static_test.rb
+++ b/actionpack/test/dispatch/static_test.rb
@@ -1,35 +1,81 @@
require 'abstract_unit'
+module StaticTests
+ def test_serves_dynamic_content
+ assert_equal "Hello, World!", get("/nofile").body
+ 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
+
+ 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
+end
+
class StaticTest < ActiveSupport::TestCase
DummyApp = lambda { |env|
[200, {"Content-Type" => "text/plain"}, ["Hello, World!"]]
}
App = ActionDispatch::Static.new(DummyApp, "#{FIXTURE_LOAD_PATH}/public")
- test "serves dynamic content" do
- assert_equal "Hello, World!", get("/nofile")
+ def setup
+ @app = App
end
- test "serves static index at root" do
- assert_equal "/index.html", get("/index.html")
- assert_equal "/index.html", get("/index")
- assert_equal "/index.html", get("/")
- end
+ include StaticTests
+end
- test "serves static file in directory" do
- assert_equal "/foo/bar.html", get("/foo/bar.html")
- assert_equal "/foo/bar.html", get("/foo/bar/")
- assert_equal "/foo/bar.html", get("/foo/bar")
- end
+class MultipleDirectorisStaticTest < ActiveSupport::TestCase
+ DummyApp = lambda { |env|
+ [200, {"Content-Type" => "text/plain"}, ["Hello, World!"]]
+ }
+ App = ActionDispatch::Static.new(DummyApp,
+ { "/" => "#{FIXTURE_LOAD_PATH}/public",
+ "/blog" => "#{FIXTURE_LOAD_PATH}/blog_public",
+ "/foo" => "#{FIXTURE_LOAD_PATH}/non_existing_dir"
+ })
- test "serves static index file in directory" do
- assert_equal "/foo/index.html", get("/foo/index.html")
- assert_equal "/foo/index.html", get("/foo/")
- assert_equal "/foo/index.html", get("/foo")
+ def setup
+ @app = App
end
- private
- def get(path)
- Rack::MockRequest.new(App).request("GET", path).body
- end
+ include StaticTests
+
+ test "serves files from other mounted directories" do
+ assert_html "/blog/index.html", get("/blog/index.html")
+ assert_html "/blog/index.html", get("/blog/index")
+ assert_html "/blog/index.html", get("/blog/")
+
+ assert_html "/blog/blog.html", get("/blog/blog/")
+ assert_html "/blog/blog.html", get("/blog/blog.html")
+ assert_html "/blog/blog.html", get("/blog/blog")
+
+ assert_html "/blog/subdir/index.html", get("/blog/subdir/index.html")
+ assert_html "/blog/subdir/index.html", get("/blog/subdir/")
+ assert_html "/blog/subdir/index.html", get("/blog/subdir")
+ end
end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index e42ade73d1..81a8c24525 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -36,10 +36,10 @@ class TestRequestTest < ActiveSupport::TestCase
req.cookies["user_name"] = "david"
assert_equal({"user_name" => "david"}, req.cookies)
- assert_equal "user_name=david;", req.env["HTTP_COOKIE"]
+ assert_equal "user_name=david", req.env["HTTP_COOKIE"]
req.cookies["login"] = "XJ-122"
assert_equal({"user_name" => "david", "login" => "XJ-122"}, req.cookies)
- assert_equal %w(login=XJ-122 user_name=david), req.env["HTTP_COOKIE"].split(/; ?/).sort
+ assert_equal %w(login=XJ-122 user_name=david), req.env["HTTP_COOKIE"].split(/; /).sort
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 0000000000..dc17668def
--- /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 0000000000..e2a7f1bad7
--- /dev/null
+++ b/actionpack/test/dispatch/uploaded_file_test.rb
@@ -0,0 +1,70 @@
+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_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_to_tempfile
+ tf = Class.new { def read; 'thunderhorse' end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_equal 'thunderhorse', uf.read
+ end
+
+ def test_delegates_to_tempfile_with_params
+ tf = Class.new { def read *args; args 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_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
index f83651d583..2b54bc62b0 100644
--- a/actionpack/test/dispatch/url_generation_test.rb
+++ b/actionpack/test/dispatch/url_generation_test.rb
@@ -31,7 +31,7 @@ module TestUrlGeneration
end
test "the request's SCRIPT_NAME takes precedence over the routes'" do
- get "/foo", {}, 'SCRIPT_NAME' => "/new"
+ get "/foo", {}, 'SCRIPT_NAME' => "/new", 'action_dispatch.routes' => Routes
assert_equal "/new/foo", response.body
end
@@ -41,3 +41,4 @@ module TestUrlGeneration
end
end
end
+
diff --git a/actionpack/test/fixtures/alternate_helpers/foo_helper.rb b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
index a956fce6fa..2528584473 100644
--- a/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
+++ b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
@@ -1,3 +1,3 @@
module FooHelper
- def baz() end
+ redefine_method(:baz) {}
end
diff --git a/actionpack/test/fixtures/blog_public/.gitignore b/actionpack/test/fixtures/blog_public/.gitignore
new file mode 100644
index 0000000000..312e635ee6
--- /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 0000000000..79ad44c010
--- /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 0000000000..2de3825481
--- /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 0000000000..517bded335
--- /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/companies.yml b/actionpack/test/fixtures/companies.yml
index 707f72abc6..ed2992e0b1 100644
--- a/actionpack/test/fixtures/companies.yml
+++ b/actionpack/test/fixtures/companies.yml
@@ -17,7 +17,7 @@ Google:
id: 4
name: Google
rating: 4
-
+
Ionist:
id: 5
name: Ioni.st
diff --git a/actionpack/test/fixtures/company.rb b/actionpack/test/fixtures/company.rb
index cbbd0edb14..cd39ea7898 100644
--- a/actionpack/test/fixtures/company.rb
+++ b/actionpack/test/fixtures/company.rb
@@ -6,5 +6,5 @@ class Company < ActiveRecord::Base
validates_presence_of :name
def validate
errors.add('rating', 'rating should not be 2') if rating == 2
- end
+ end
end \ No newline at end of file
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 0000000000..6d7f3bafbb
--- /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 0000000000..dbd7e96ab6
--- /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 0000000000..6d7f3bafbb
--- /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/db_definitions/sqlite.sql b/actionpack/test/fixtures/db_definitions/sqlite.sql
index 8e1947d14a..99df4b3e61 100644
--- a/actionpack/test/fixtures/db_definitions/sqlite.sql
+++ b/actionpack/test/fixtures/db_definitions/sqlite.sql
@@ -5,20 +5,20 @@ CREATE TABLE 'companies' (
);
CREATE TABLE 'replies' (
- 'id' INTEGER PRIMARY KEY NOT NULL,
- 'content' text,
- 'created_at' datetime,
- 'updated_at' datetime,
+ '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,
+ 'id' INTEGER PRIMARY KEY NOT NULL,
+ 'title' varchar(255),
+ 'subtitle' varchar(255),
+ 'content' text,
+ 'created_at' datetime,
'updated_at' datetime
);
@@ -43,7 +43,7 @@ CREATE TABLE 'developers_projects' (
);
CREATE TABLE 'mascots' (
- 'id' INTEGER PRIMARY KEY NOT NULL,
+ '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/filter_test/implicit_actions/edit.html.erb b/actionpack/test/fixtures/filter_test/implicit_actions/edit.html.erb
new file mode 100644
index 0000000000..8491ab9f80
--- /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 0000000000..0a89cecf05
--- /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/helpers/helpery_test_helper.rb b/actionpack/test/fixtures/helpers/helpery_test_helper.rb
new file mode 100644
index 0000000000..a4f2951efa
--- /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 0000000000..b140a7b9b4
--- /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 0000000000..ce56042143
--- /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/layout_tests/alt/hello.erb b/actionpack/test/fixtures/layout_tests/alt/hello.erb
new file mode 100644
index 0000000000..1055c36659
--- /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/hello.rhtml b/actionpack/test/fixtures/layout_tests/alt/hello.rhtml
deleted file mode 100644
index fcda6cf97a..0000000000
--- a/actionpack/test/fixtures/layout_tests/alt/hello.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-alt/hello.rhtml
diff --git a/actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml b/actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb
index e69de29bb2..e69de29bb2 100644
--- a/actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml
+++ b/actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb
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 0000000000..121bc079a1
--- /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/controller_name_space/nested.rhtml b/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml
deleted file mode 100644
index 5f86a7de4d..0000000000
--- a/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-controller_name_space/nested.rhtml <%= 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 0000000000..60f04d77d5
--- /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/item.rhtml b/actionpack/test/fixtures/layout_tests/layouts/item.rhtml
deleted file mode 100644
index 1bc7cbda06..0000000000
--- a/actionpack/test/fixtures/layout_tests/layouts/item.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-item.rhtml <%= 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 0000000000..b74ac0840d
--- /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/layout_test.rhtml b/actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml
deleted file mode 100644
index c0f2642b40..0000000000
--- a/actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-layout_test.rhtml <%= yield %> \ 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 0000000000..4ee911188e
--- /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/goodbye.rhtml b/actionpack/test/fixtures/layout_tests/views/goodbye.rhtml
deleted file mode 100644
index bbccf0913e..0000000000
--- a/actionpack/test/fixtures/layout_tests/views/goodbye.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-hello.rhtml \ 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 0000000000..4ee911188e
--- /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/layout_tests/views/hello.rhtml b/actionpack/test/fixtures/layout_tests/views/hello.rhtml
deleted file mode 100644
index bbccf0913e..0000000000
--- a/actionpack/test/fixtures/layout_tests/views/hello.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-hello.rhtml \ 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 0000000000..ae63f13cd3
--- /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 0000000000..74cc428ffa
--- /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 0000000000..37f0bddbd7
--- /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 0000000000..68e6557fb8
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_yield_with_params.erb
@@ -0,0 +1 @@
+<%= yield '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 0000000000..74cc428ffa
--- /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/old_content_type/render_default_for_rxml.rxml b/actionpack/test/fixtures/old_content_type/render_default_for_builder.builder
index 598d62e2fc..598d62e2fc 100644
--- a/actionpack/test/fixtures/old_content_type/render_default_for_rxml.rxml
+++ b/actionpack/test/fixtures/old_content_type/render_default_for_builder.builder
diff --git a/actionpack/test/fixtures/old_content_type/render_default_for_rhtml.rhtml b/actionpack/test/fixtures/old_content_type/render_default_for_erb.erb
index c7926d48bb..c7926d48bb 100644
--- a/actionpack/test/fixtures/old_content_type/render_default_for_rhtml.rhtml
+++ b/actionpack/test/fixtures/old_content_type/render_default_for_erb.erb
diff --git a/actionpack/test/fixtures/replies.yml b/actionpack/test/fixtures/replies.yml
index 66020b706a..2a3454b8bf 100644
--- a/actionpack/test/fixtures/replies.yml
+++ b/actionpack/test/fixtures/replies.yml
@@ -5,7 +5,7 @@ witty_retort:
content: Birdman is better!
created_at: <%= 6.hours.ago.to_s(:db) %>
updated_at: nil
-
+
another:
id: 2
topic_id: 2
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 0000000000..4da4181f56
--- /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/test/_layout_with_partial_and_yield.html.erb b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
new file mode 100644
index 0000000000..5db0822f07
--- /dev/null
+++ b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
@@ -0,0 +1,4 @@
+Before
+<%= render :partial => "test/partial.html.erb" %>
+<%= yield %>
+After
diff --git a/actionpack/test/fixtures/test/_object_inspector.erb b/actionpack/test/fixtures/test/_object_inspector.erb
new file mode 100644
index 0000000000..53af593821
--- /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/_partial_with_layout.erb b/actionpack/test/fixtures/test/_partial_with_layout.erb
new file mode 100644
index 0000000000..2a50c834fe
--- /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 0000000000..65dafd93a8
--- /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 0000000000..444197a7d0
--- /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_partial.erb b/actionpack/test/fixtures/test/_partial_with_partial.erb
new file mode 100644
index 0000000000..ee0d5037b6
--- /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/hello_world_from_rxml.builder b/actionpack/test/fixtures/test/hello_world_from_rxml.builder
index 8455b11edc..619a97ba96 100644
--- a/actionpack/test/fixtures/test/hello_world_from_rxml.builder
+++ b/actionpack/test/fixtures/test/hello_world_from_rxml.builder
@@ -1,4 +1,3 @@
xml.html do
xml.p "Hello"
end
-"String return value"
diff --git a/actionpack/test/fixtures/test/hello_xml_world.builder b/actionpack/test/fixtures/test/hello_xml_world.builder
index 02b14fe87c..e7081b89fe 100644
--- a/actionpack/test/fixtures/test/hello_xml_world.builder
+++ b/actionpack/test/fixtures/test/hello_xml_world.builder
@@ -2,7 +2,7 @@ xml.html do
xml.head do
xml.title "Hello World"
end
-
+
xml.body do
xml.p "abes"
xml.p "monks"
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 0000000000..acc4453c08
--- /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/proper_block_detection.erb b/actionpack/test/fixtures/test/proper_block_detection.erb
index 23564dbcee..b55efbb25d 100644
--- a/actionpack/test/fixtures/test/proper_block_detection.erb
+++ b/actionpack/test/fixtures/test/proper_block_detection.erb
@@ -1 +1 @@
-<%= @todo %>
+<%= @todo %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/scoped_translation.erb b/actionpack/test/fixtures/test/scoped_translation.erb
deleted file mode 100644
index 3be63ab3cc..0000000000
--- a/actionpack/test/fixtures/test/scoped_translation.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= t('.foo.bar').join %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/translation.erb b/actionpack/test/fixtures/test/translation.erb
deleted file mode 100644
index 81a837d1ff..0000000000
--- a/actionpack/test/fixtures/test/translation.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= t('.helper') %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/topics.yml b/actionpack/test/fixtures/topics.yml
index 61ea02d76f..7fdd49d54e 100644
--- a/actionpack/test/fixtures/topics.yml
+++ b/actionpack/test/fixtures/topics.yml
@@ -5,7 +5,7 @@ futurama:
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
diff --git a/actionpack/test/fixtures/translations/templates/array.erb b/actionpack/test/fixtures/translations/templates/array.erb
new file mode 100644
index 0000000000..d86045a172
--- /dev/null
+++ b/actionpack/test/fixtures/translations/templates/array.erb
@@ -0,0 +1 @@
+<%= t('.foo.bar') %>
diff --git a/actionpack/test/fixtures/translations/templates/found.erb b/actionpack/test/fixtures/translations/templates/found.erb
new file mode 100644
index 0000000000..080c9c0aee
--- /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 0000000000..0f3f17f8ef
--- /dev/null
+++ b/actionpack/test/fixtures/translations/templates/missing.erb
@@ -0,0 +1 @@
+<%= t('.missing') %>
diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb
index bf3e175f1f..67baf369e2 100644
--- a/actionpack/test/lib/controller/fake_models.rb
+++ b/actionpack/test/lib/controller/fake_models.rb
@@ -55,6 +55,11 @@ class Post < Struct.new(:title, :author_name, :body, :secret, :written_on, :cost
alias_method :secret?, :secret
+ def initialize(*args)
+ super
+ @persisted = false
+ end
+
def persisted=(boolean)
@persisted = boolean
end
@@ -83,7 +88,7 @@ class Comment
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 to_param; @id.to_s; end
def name
@id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}"
end
@@ -91,6 +96,7 @@ class Comment
attr_accessor :relevances
def relevances_attributes=(attributes); end
+ attr_accessor :body
end
class Tag
@@ -129,6 +135,20 @@ class CommentRelevance
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
@@ -149,3 +169,34 @@ class Author < Comment
attr_accessor :post
def post_attributes=(attributes); end
end
+
+module Blog
+ def self._railtie
+ self
+ 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
diff --git a/actionpack/test/template/active_model_helper_test.rb b/actionpack/test/template/active_model_helper_test.rb
index 6ab244d178..8530a72a82 100644
--- a/actionpack/test/template/active_model_helper_test.rb
+++ b/actionpack/test/template/active_model_helper_test.rb
@@ -59,12 +59,4 @@ class ActiveModelHelperTest < ActionView::TestCase
ensure
ActionView::Base.field_error_proc = old_proc if old_proc
end
-
- def test_deprecations
- %w(input form error_messages_for error_message_on).each do |method|
- assert_deprecated do
- send(method, "post")
- end
- end
- end
end
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index 6d5e4893c4..1bf748af14 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -54,6 +54,9 @@ class AssetTagHelperTest < ActionView::TestCase
def teardown
config.perform_caching = false
ENV.delete('RAILS_ASSET_ID')
+
+ JavascriptIncludeTag.expansions.clear
+ StylesheetIncludeTag.expansions.clear
end
AutoDiscoveryToTag = {
@@ -89,9 +92,10 @@ class AssetTagHelperTest < ActionView::TestCase
%(javascript_include_tag("bank", :lang => "vbscript")) => %(<script lang="vbscript" src="/javascripts/bank.js" type="text/javascript"></script>),
%(javascript_include_tag("common.javascript", "/elsewhere/cools")) => %(<script src="/javascripts/common.javascript" type="text/javascript"></script>\n<script src="/elsewhere/cools.js" type="text/javascript"></script>),
%(javascript_include_tag(:defaults)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
- %(javascript_include_tag(:all)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>),
- %(javascript_include_tag(:all, :recursive => true)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>),
+ %(javascript_include_tag(:all)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
+ %(javascript_include_tag(:all, :recursive => true)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
%(javascript_include_tag(:defaults, "bank")) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
+ %(javascript_include_tag(:defaults, "application")) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
%(javascript_include_tag("bank", :defaults)) => %(<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
%(javascript_include_tag("http://example.com/all")) => %(<script src="http://example.com/all" type="text/javascript"></script>),
@@ -262,19 +266,66 @@ class AssetTagHelperTest < ActionView::TestCase
assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>), javascript_include_tag('controls', :robbery, 'effects')
end
+ def test_custom_javascript_expansions_return_unique_set
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :defaults => %w(prototype effects dragdrop controls rails application)
+ assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults)
+ end
+
def test_custom_javascript_expansions_and_defaults_puts_application_js_at_the_end
ENV["RAILS_ASSET_ID"] = ""
ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"]
- assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls',:defaults, :robbery, 'effects')
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls',:defaults, :robbery, 'effects')
+ end
+
+ def test_javascript_include_tag_should_not_output_the_same_asset_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('prototype', 'effects', :defaults)
+ end
+
+ def test_javascript_include_tag_should_not_output_the_same_expansion_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults, :defaults)
+ end
+
+ def test_single_javascript_asset_keys_should_take_precedence_over_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls', :defaults, 'effects')
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls', 'effects', :defaults)
+ end
+
+ def test_registering_javascript_expansions_merges_with_existing_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank']
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['robber']
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank']
+ assert_dom_equal %(<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>), javascript_include_tag(:can_merge)
end
def test_custom_javascript_expansions_with_undefined_symbol
+ assert_raise(ArgumentError) { javascript_include_tag('first', :unknown, 'last') }
+ end
+
+ def test_custom_javascript_expansions_with_nil_value
ActionView::Helpers::AssetTagHelper::register_javascript_expansion :monkey => nil
- assert_raise(ArgumentError) { javascript_include_tag('first', :monkey, 'last') }
+ assert_dom_equal %(<script src="/javascripts/first.js" type="text/javascript"></script>\n<script src="/javascripts/last.js" type="text/javascript"></script>), javascript_include_tag('first', :monkey, 'last')
+ end
+
+ def test_custom_javascript_expansions_with_empty_array_value
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :monkey => []
+ assert_dom_equal %(<script src="/javascripts/first.js" type="text/javascript"></script>\n<script src="/javascripts/last.js" type="text/javascript"></script>), javascript_include_tag('first', :monkey, 'last')
+ end
+
+ def test_custom_javascript_and_stylesheet_expansion_with_same_name
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"]
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :robbery => ["money", "security"]
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>), javascript_include_tag('controls', :robbery, 'effects')
+ assert_dom_equal %(<link href="/stylesheets/style.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/money.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/security.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/print.css" rel="stylesheet" type="text/css" media="screen" />), stylesheet_link_tag('style', :robbery, 'print')
end
def test_reset_javascript_expansions
- ActionView::Helpers::AssetTagHelper.javascript_expansions.clear
+ JavascriptIncludeTag.expansions.clear
assert_raise(ArgumentError) { javascript_include_tag(:defaults) }
end
@@ -306,7 +357,6 @@ class AssetTagHelperTest < ActionView::TestCase
ENV["RAILS_ASSET_ID"] = ""
assert stylesheet_link_tag('dir/file').html_safe?
assert stylesheet_link_tag('dir/other/file', 'dir/file2').html_safe?
- assert stylesheet_tag('dir/file', {}).html_safe?
end
def test_custom_stylesheet_expansions
@@ -315,9 +365,49 @@ class AssetTagHelperTest < ActionView::TestCase
assert_dom_equal %(<link href="/stylesheets/version.1.0.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/subdir/subdir.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('version.1.0', :robbery, 'subdir/subdir')
end
- def test_custom_stylesheet_expansions_with_undefined_symbol
+ def test_custom_stylesheet_expansions_return_unique_set
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london)
+ assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:cities)
+ end
+
+ def test_stylesheet_link_tag_should_not_output_the_same_asset_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('wellington', 'wellington', 'amsterdam')
+ end
+
+ def test_stylesheet_link_tag_should_not_output_the_same_expansion_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london)
+ assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:cities, :cities)
+ end
+
+ def test_single_stylesheet_asset_keys_should_take_precedence_over_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london)
+ assert_dom_equal %(<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('london', :cities)
+ end
+
+ def test_custom_stylesheet_expansions_with_unknown_symbol
+ assert_raise(ArgumentError) { stylesheet_link_tag('first', :unknown, 'last') }
+ end
+
+ def test_custom_stylesheet_expansions_with_nil_value
ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => nil
- assert_raise(ArgumentError) { stylesheet_link_tag('first', :monkey, 'last') }
+ assert_dom_equal %(<link href="/stylesheets/first.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/last.css" rel="stylesheet" type="text/css" media="screen" />), stylesheet_link_tag('first', :monkey, 'last')
+ end
+
+ def test_custom_stylesheet_expansions_with_empty_array_value
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => []
+ assert_dom_equal %(<link href="/stylesheets/first.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/last.css" rel="stylesheet" type="text/css" media="screen" />), stylesheet_link_tag('first', :monkey, 'last')
+ end
+
+ def test_registering_stylesheet_expansions_merges_with_existing_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank']
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['robber']
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank']
+ assert_dom_equal %(<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:can_merge)
end
def test_image_path
@@ -387,6 +477,15 @@ class AssetTagHelperTest < ActionView::TestCase
assert_equal %(<img alt="Rails" src="#{expected_path}" />), image_tag("rails.png")
end
+ def test_env_asset_path
+ @controller.config.asset_path = "/assets%s"
+ def @controller.env; @_env ||= {} end
+ @controller.env["action_dispatch.asset_path"] = "/omg%s"
+
+ expected_path = "/assets/omg/images/rails.png"
+ assert_equal %(<img alt="Rails" src="#{expected_path}" />), image_tag("rails.png")
+ end
+
def test_proc_asset_id
@controller.config.asset_path = Proc.new do |asset_path|
"/assets.v12345#{asset_path}"
@@ -396,6 +495,20 @@ class AssetTagHelperTest < ActionView::TestCase
assert_equal %(<img alt="Rails" src="#{expected_path}" />), image_tag("rails.png")
end
+ def test_env_proc_asset_path
+ @controller.config.asset_path = Proc.new do |asset_path|
+ "/assets.v12345#{asset_path}"
+ end
+
+ def @controller.env; @_env ||= {} end
+ @controller.env["action_dispatch.asset_path"] = Proc.new do |asset_path|
+ "/omg#{asset_path}"
+ end
+
+ expected_path = "/assets.v12345/omg/images/rails.png"
+ assert_equal %(<img alt="Rails" src="#{expected_path}" />), image_tag("rails.png")
+ 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@acontentid" />', image_tag("cid:thi%25%25sis@acontentid")
@@ -605,7 +718,7 @@ class AssetTagHelperTest < ActionView::TestCase
assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'combined.js'))
assert_equal(
- %(// prototype js\n\n// effects js\n\n// dragdrop js\n\n// controls js\n\n// application js\n\n// bank js\n\n// robber js\n\n// subdir js\n\n\n// version.1.0 js),
+ %(// prototype js\n\n// effects js\n\n// dragdrop js\n\n// controls js\n\n// bank js\n\n// robber js\n\n// subdir js\n\n\n// version.1.0 js\n\n// application js),
IO.read(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'combined.js'))
)
@@ -626,7 +739,7 @@ class AssetTagHelperTest < ActionView::TestCase
assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'combined.js'))
assert_equal(
- %(// prototype js\n\n// effects js\n\n// dragdrop js\n\n// controls js\n\n// application js\n\n// bank js\n\n// robber js\n\n// version.1.0 js),
+ %(// prototype js\n\n// effects js\n\n// dragdrop js\n\n// controls js\n\n// bank js\n\n// robber js\n\n// version.1.0 js\n\n// application js),
IO.read(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'combined.js'))
)
@@ -658,29 +771,49 @@ class AssetTagHelperTest < ActionView::TestCase
FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js'))
end
+ def test_caching_javascript_include_tag_with_named_paths_and_relative_url_root_when_caching_off
+ ENV["RAILS_ASSET_ID"] = ""
+ @controller.config.relative_url_root = "/collaboration/hieraki"
+ config.perform_caching = false
+
+ assert_dom_equal(
+ %(<script src="/collaboration/hieraki/javascripts/robber.js" type="text/javascript"></script>),
+ javascript_include_tag('robber', :cache => true)
+ )
+
+ assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js'))
+
+ assert_dom_equal(
+ %(<script src="/collaboration/hieraki/javascripts/robber.js" type="text/javascript"></script>),
+ javascript_include_tag('robber', :cache => "money", :recursive => true)
+ )
+
+ assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js'))
+ end
+
def test_caching_javascript_include_tag_when_caching_off
ENV["RAILS_ASSET_ID"] = ""
config.perform_caching = false
assert_dom_equal(
- %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>),
+ %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
javascript_include_tag(:all, :cache => true)
)
assert_dom_equal(
- %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>),
+ %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
javascript_include_tag(:all, :cache => true, :recursive => true)
)
assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js'))
assert_dom_equal(
- %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>),
+ %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
javascript_include_tag(:all, :cache => "money")
)
assert_dom_equal(
- %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>),
+ %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
javascript_include_tag(:all, :cache => "money", :recursive => true)
)
@@ -704,6 +837,17 @@ class AssetTagHelperTest < ActionView::TestCase
assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js'))
end
+ def test_caching_javascript_include_tag_when_caching_on_and_javascript_file_is_uri
+ ENV["RAILS_ASSET_ID"] = ""
+ config.perform_caching = true
+
+ assert_raise(Errno::ENOENT) {
+ javascript_include_tag('bank', 'robber', 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js', :cache => true)
+ }
+
+ assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js'))
+ end
+
def test_caching_javascript_include_tag_when_caching_off_and_missing_javascript_file
ENV["RAILS_ASSET_ID"] = ""
config.perform_caching = false
@@ -874,6 +1018,30 @@ class AssetTagHelperTest < ActionView::TestCase
FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css'))
end
+
+ def test_caching_stylesheet_link_tag_with_named_paths_and_relative_url_root_when_caching_off
+ ENV["RAILS_ASSET_ID"] = ""
+ @controller.config.relative_url_root = "/collaboration/hieraki"
+ config.perform_caching = false
+
+ assert_dom_equal(
+ %(<link href="/collaboration/hieraki/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />),
+ stylesheet_link_tag('robber', :cache => true)
+ )
+
+ assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'all.css'))
+
+ assert_dom_equal(
+ %(<link href="/collaboration/hieraki/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />),
+ stylesheet_link_tag('robber', :cache => "money")
+ )
+
+ assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css'))
+ end
+
+
+
+
def test_caching_stylesheet_include_tag_when_caching_off
ENV["RAILS_ASSET_ID"] = ""
config.perform_caching = false
@@ -915,7 +1083,7 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
@request = Struct.new(:protocol).new("gopher://")
@controller.request = @request
- ActionView::Helpers::AssetTagHelper.javascript_expansions.clear
+ JavascriptIncludeTag.expansions.clear
end
def url_for(options)
@@ -952,7 +1120,7 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
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_path('xml.png'))
end
def test_asset_host_without_protocol_should_use_request_protocol
diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb
index 869ea22469..36102bbc4f 100644
--- a/actionpack/test/template/atom_feed_helper_test.rb
+++ b/actionpack/test/template/atom_feed_helper_test.rb
@@ -203,7 +203,7 @@ class AtomFeedTest < ActionController::TestCase
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
+ assert_match(%r{xml:lang="en-US"}, @response.body)
end
end
@@ -226,7 +226,7 @@ class AtomFeedTest < ActionController::TestCase
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?
+ assert_blank @response.body
end
end
@@ -314,7 +314,7 @@ class AtomFeedTest < ActionController::TestCase
private
def with_restful_routing(resources)
with_routing do |set|
- set.draw do |map|
+ set.draw do
resources(resources)
end
yield
diff --git a/actionpack/test/template/capture_helper_test.rb b/actionpack/test/template/capture_helper_test.rb
index f7c42c7f22..03050485fa 100644
--- a/actionpack/test/template/capture_helper_test.rb
+++ b/actionpack/test/template/capture_helper_test.rb
@@ -15,7 +15,6 @@ class CaptureHelperTest < ActionView::TestCase
end
assert_nil @av.output_buffer
assert_equal 'foobar', string
- assert_kind_of ActionView::NonConcattingString, string
end
def test_capture_captures_the_value_returned_by_the_block_if_the_temporary_buffer_is_blank
@@ -23,13 +22,22 @@ class CaptureHelperTest < ActionView::TestCase
a + b
end
assert_equal 'foobar', string
- assert_kind_of ActionView::NonConcattingString, 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 '&lt;em&gt;bar&lt;/em&gt;', string
+ end
+
+ def test_capture_doesnt_escape_twice
+ string = @av.capture { '&lt;em&gt;bar&lt;/em&gt;'.html_safe }
+ assert_equal '&lt;em&gt;bar&lt;/em&gt;', string
+ end
+
def test_content_for
assert ! content_for?(:title)
content_for :title, 'title'
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index 2c719757e4..3f31edd5ce 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -8,7 +8,7 @@ class CompiledTemplatesTest < Test::Unit::TestCase
@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.erb")
assert_equal "two", render(:file => "test/render_file_with_locals_and_default.erb", :locals => { :secret => "two" })
diff --git a/actionpack/test/template/date_helper_i18n_test.rb b/actionpack/test/template/date_helper_i18n_test.rb
index b69a449617..d45215acfd 100644
--- a/actionpack/test/template/date_helper_i18n_test.rb
+++ b/actionpack/test/template/date_helper_i18n_test.rb
@@ -5,7 +5,7 @@ class DateHelperDistanceOfTimeInWordsI18nTests < Test::Unit::TestCase
attr_reader :request
def setup
- @from = Time.mktime(2004, 6, 6, 21, 45, 0)
+ @from = Time.utc(2004, 6, 6, 21, 45, 0)
end
# distance_of_time_in_words
@@ -62,7 +62,7 @@ class DateHelperDistanceOfTimeInWordsI18nTests < Test::Unit::TestCase
[:'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'
+ [:'over_x_years', 2] => 'over 2 years'
}.each do |args, expected|
key, count = *args
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index a1db49d4d0..aca2fef170 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -99,7 +99,7 @@ class DateHelperTest < ActionView::TestCase
end
def test_distance_in_words
- from = Time.mktime(2004, 6, 6, 21, 45, 0)
+ from = Time.utc(2004, 6, 6, 21, 45, 0)
assert_distance_of_time_in_words(from)
end
@@ -673,7 +673,7 @@ class DateHelperTest < ActionView::TestCase
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), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :order => [:day])
end
@@ -897,7 +897,7 @@ class DateHelperTest < ActionView::TestCase
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)
@@ -978,7 +978,7 @@ class DateHelperTest < ActionView::TestCase
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 value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
expected << "</select>\n"
- expected << " &mdash; "
+ expected << " &mdash; "
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</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
@@ -1007,7 +1007,7 @@ class DateHelperTest < ActionView::TestCase
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 value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
expected << "</select>\n"
- expected << " &mdash; "
+ expected << " &mdash; "
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<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
@@ -1121,7 +1121,7 @@ class DateHelperTest < ActionView::TestCase
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<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
expected << "</select>\n"
@@ -1158,7 +1158,7 @@ class DateHelperTest < ActionView::TestCase
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<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
expected << "</select>\n"
@@ -1182,7 +1182,7 @@ class DateHelperTest < ActionView::TestCase
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<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
expected << "</select>\n"
@@ -1206,7 +1206,7 @@ class DateHelperTest < ActionView::TestCase
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<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
expected << "</select>\n"
@@ -1229,11 +1229,11 @@ class DateHelperTest < ActionView::TestCase
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<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
expected << "</select>\n"
-
+
expected << " : "
expected << %(<select id="date_minute" name="date[minute]">\n)
@@ -1253,7 +1253,7 @@ class DateHelperTest < ActionView::TestCase
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>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n)
expected << "</select>\n"
@@ -1497,26 +1497,6 @@ class DateHelperTest < ActionView::TestCase
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_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"/>' + "\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_cant_override_discard_hour
@post = Post.new
@post.written_on = Date.new(2004, 6, 15)
@@ -1604,6 +1584,47 @@ class DateHelperTest < ActionView::TestCase
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</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
+ 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</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
+ 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)
@@ -1861,10 +1882,17 @@ class DateHelperTest < ActionView::TestCase
end
def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set
- time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0)
- time_zone = mock()
- time_zone.expects(:now).returns time
- Time.zone_default = time_zone
+ # The love zone is UTC+0
+ mytz = Class.new(ActiveSupport::TimeZone) {
+ attr_accessor :now
+ }.create('tenderlove', 0)
+
+ now = Time.mktime(2004, 6, 15, 16, 35, 0)
+ mytz.now = now
+ Time.zone = mytz
+
+ assert_equal mytz, Time.zone
+
@post = Post.new
expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
@@ -1891,7 +1919,7 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, datetime_select("post", "updated_at")
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_datetime_select_with_html_options_within_fields_for
@@ -2670,13 +2698,39 @@ class DateHelperTest < ActionView::TestCase
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?
+ 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.today
+ expected = "<time datetime=\"#{date.rfc3339}\">#{I18n.l(date, :format => :long)}</time>"
+ assert_equal expected, time_tag(date)
+ end
+
+ def test_time_tag_with_time
+ time = Time.now
+ expected = "<time datetime=\"#{time.xmlschema}\">#{I18n.l(time, :format => :long)}</time>"
+ assert_equal expected, time_tag(time)
+ end
+
+ def test_time_tag_pubdate_option
+ assert_match /<time.*pubdate="pubdate">.*<\/time>/, time_tag(Time.now, :pubdate => true)
+ end
+
+ def test_time_tag_with_given_text
+ assert_match /<time.*>Right now<\/time>/, time_tag(Time.now, 'Right now')
+ end
+
+ def test_time_tag_with_different_format
+ time = Time.now
+ expected = "<time datetime=\"#{time.xmlschema}\">#{I18n.l(time, :format => :short)}</time>"
+ assert_equal expected, time_tag(time, :format => :short)
end
protected
diff --git a/actionpack/test/template/erb/tag_helper_test.rb b/actionpack/test/template/erb/tag_helper_test.rb
index d073100986..a384e94766 100644
--- a/actionpack/test/template/erb/tag_helper_test.rb
+++ b/actionpack/test/template/erb/tag_helper_test.rb
@@ -2,59 +2,32 @@ require "abstract_unit"
require "template/erb/helper"
module ERBTest
- module SharedTagHelpers
- extend ActiveSupport::Testing::Declarative
+ class TagHelperTest < BlockTestCase
- def maybe_deprecated
- if @deprecated
- assert_deprecated { yield }
- else
- yield
- end
- end
+ extend ActiveSupport::Testing::Declarative
test "percent equals works for content_tag and does not require parenthesis on method call" do
- maybe_deprecated { assert_equal "<div>Hello world</div>", render_content("content_tag :div", "Hello world") }
+ 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 type=\"text/javascript\">\n//<![CDATA[\nalert('Hello')\n//]]>\n</script>"
- maybe_deprecated { assert_equal expected_output, render_content("javascript_tag", "alert('Hello')") }
+ 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\" type=\"text/javascript\">\n//<![CDATA[\nalert('Hello')\n//]]>\n</script>"
- maybe_deprecated { assert_equal expected_output, render_content("javascript_tag(:id => 'the_js_tag')", "alert('Hello')") }
+ 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>}
- maybe_deprecated { assert_match expected_output, render_content("form_tag('foo')", "<%= 'hello' %>") }
+ 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>"
- maybe_deprecated { assert_equal expected_output, render_content("field_set_tag('foo')", "<%= 'hello' %>") }
- end
- end
-
- class TagHelperTest < BlockTestCase
- def block_helper(str, rest)
- "<%= #{str} do %>#{rest}<% end %>"
+ assert_equal expected_output, render_content("field_set_tag('foo')", "<%= 'hello' %>")
end
-
- include SharedTagHelpers
- end
-
- class DeprecatedTagHelperTest < BlockTestCase
- def block_helper(str, rest)
- "<% __in_erb_template=true %><% #{str} do %>#{rest}<% end %>"
- end
-
- def setup
- @deprecated = true
- end
-
- include SharedTagHelpers
end
end \ No newline at end of file
diff --git a/actionpack/test/template/erb_util_test.rb b/actionpack/test/template/erb_util_test.rb
index d3129d0e1a..d1891094e8 100644
--- a/actionpack/test/template/erb_util_test.rb
+++ b/actionpack/test/template/erb_util_test.rb
@@ -14,7 +14,7 @@ class ErbUtilTest < Test::Unit::TestCase
end
end
end
-
+
def test_html_escape_is_html_safe
escaped = h("<p>")
assert_equal "&lt;p&gt;", escaped
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index be66710ae5..359b078466 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -4,16 +4,6 @@ require 'controller/fake_models'
class FormHelperTest < ActionView::TestCase
tests ActionView::Helpers::FormHelper
- class Developer
- def name_before_type_cast
- "David"
- end
-
- def name
- "Santiago"
- end
- end
-
def form_for(*)
@output_buffer = super
end
@@ -73,15 +63,38 @@ class FormHelperTest < ActionView::TestCase
@post.body = "Back to the hill and over it again!"
@post.secret = 1
@post.written_on = Date.new(2004, 6, 15)
+
+ @blog_post = Blog::Post.new("And his name will be forty and four.", 44)
+ 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
+
+ match "/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)
- "http://www.example.com"
- else
- super
+ if object.is_a?(Hash) && object[:use_route].blank? && object[:controller].blank?
+ object.merge!(:controller => "main", :action => "index")
end
+ super
end
def test_label
@@ -165,7 +178,10 @@ class FormHelperTest < ActionView::TestCase
'<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title")
)
assert_dom_equal(
- '<input id="post_title" name="post[title]" size="30" type="password" value="Hello World" />', password_field("post", "title")
+ '<input id="post_title" name="post[title]" size="30" type="password" />', password_field("post", "title")
+ )
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" size="30" type="password" value="Hello World" />', password_field("post", "title", :value => @post.title)
)
assert_dom_equal(
'<input id="person_name" name="person[name]" size="30" type="password" />', password_field("person", "name")
@@ -240,7 +256,7 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, hidden_field("post", "title", :value => nil)
end
- def test_text_field_with_options
+ 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
@@ -250,13 +266,6 @@ class FormHelperTest < ActionView::TestCase
text_field("user", "email", :type => "email")
end
- def test_text_field_from_a_user_defined_method
- @developer = Developer.new
- assert_dom_equal(
- '<input id="developer_name" name="developer[name]" size="30" type="text" value="Santiago" />', text_field("developer", "name")
- )
- end
-
def test_check_box
assert_dom_equal(
'<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
@@ -600,31 +609,91 @@ class FormHelperTest < ActionView::TestCase
)
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
- assert_deprecated do
- form_for(:post, @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')
- end
+ 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')
end
- expected =
- "<form accept-charset='UTF-8' action='http://www.example.com' id='create-post' method='post'>" +
- snowman +
+ expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
"<label for='post_title'>The Title</label>" +
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[secret]' type='hidden' value='0' />" +
"<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='commit' id='post_submit' type='submit' value='Create post' />" +
- "</form>"
+ "<input name='commit' type='submit' value='Create post' />"
+ 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 => "put", :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 => "put", :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 => "put") do
+ "<label for='post_title'>Title</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_isolated_namespaced_model
+ form_for(@blog_post) do |f|
+ concat f.text_field :title
+ concat f.submit('Edit post')
+ end
+
+ expected =
+ "<form accept-charset='UTF-8' action='/posts/44' method='post'>" +
+ snowman +
+ "<label for='post_title'>The Title</label>" +
+ "<input name='post[title]' size='30' type='text' id='post_title' value='And his name will be forty and four.' />" +
+ "<input name='commit' id='post_submit' type='submit' value='Edit post' />" +
+ "</form>"
+ 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')
@@ -640,22 +709,20 @@ class FormHelperTest < ActionView::TestCase
"<textarea name='other_name[body]' id='other_name_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='other_name[secret]' value='0' type='hidden' />" +
"<input name='other_name[secret]' checked='checked' id='other_name_secret' value='1' type='checkbox' />" +
- "<input name='commit' id='other_name_submit' value='Create post' type='submit' />"
+ "<input name='commit' value='Create post' type='submit' />"
end
assert_dom_equal expected, output_buffer
end
def test_form_for_with_method
- assert_deprecated do
- form_for(:post, @post, :html => { :id => 'create-post', :method => :put }) do |f|
- concat f.text_field(:title)
- concat f.text_area(:body)
- concat f.check_box(:secret)
- end
+ form_for(@post, :url => '/', :html => { :id => 'create-post', :method => :put }) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
end
- expected = whole_form("http://www.example.com", "create-post", nil, "put") do
+ expected = whole_form("/", "create-post", "edit_post", "put") do
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[secret]' type='hidden' value='0' />" +
@@ -665,16 +732,28 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_form_for_with_search_field
+ # Test case for bug which would emit an "object" attribute
+ # when used with form_for using a search_field form helper
+ 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", "get") do
+ "<input name='post[title]' size='30' type='search' id='post_title' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_form_for_with_remote
- assert_deprecated do
- form_for(:post, @post, :remote => true, :html => { :id => 'create-post', :method => :put }) do |f|
- concat f.text_field(:title)
- concat f.text_area(:body)
- concat f.check_box(:secret)
- end
+ form_for(@post, :url => '/', :remote => true, :html => { :id => 'create-post', :method => :put }) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
end
- expected = whole_form("http://www.example.com", "create-post", nil, :method => "put", :remote => true) do
+ expected = whole_form("/", "create-post", "edit_post", :method => "put", :remote => true) do
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[secret]' type='hidden' value='0' />" +
@@ -685,15 +764,14 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_for_with_remote_without_html
- assert_deprecated do
- form_for(:post, @post, :remote => true) do |f|
- concat f.text_field(:title)
- concat f.text_area(:body)
- concat f.check_box(:secret)
- end
+ @post.persisted = false
+ 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("http://www.example.com", nil, nil, :remote => true) do
+ expected = whole_form("/posts", 'new_post', 'new_post', :remote => true) do
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[secret]' type='hidden' value='0' />" +
@@ -710,7 +788,7 @@ class FormHelperTest < ActionView::TestCase
concat f.check_box(:secret)
end
- expected = whole_form("http://www.example.com", "create-post") do
+ expected = whole_form("/", "create-post") do
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[secret]' type='hidden' value='0' />" +
@@ -721,16 +799,14 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_for_with_index
- assert_deprecated do
- form_for("post[]", @post) do |f|
- concat f.label(:title)
- concat f.text_field(:title)
- concat f.text_area(:body)
- concat f.check_box(:secret)
- end
+ 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 do
+ expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
"<label for='post_123_title'>Title</label>" +
"<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
"<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
@@ -742,15 +818,13 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_for_with_nil_index_option_override
- assert_deprecated do
- form_for("post[]", @post, :index => nil) do |f|
- concat f.text_field(:title)
- concat f.text_area(:body)
- concat f.check_box(:secret)
- end
+ 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 do
+ expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
"<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" +
"<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[][secret]' type='hidden' value='0' />" +
@@ -764,15 +838,13 @@ class FormHelperTest < ActionView::TestCase
old_locale, I18n.locale = I18n.locale, :submit
@post.persisted = false
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.submit
- end
+ form_for(@post) do |f|
+ concat f.submit
end
- expected = whole_form do
- "<input name='commit' id='post_submit' type='submit' value='Create Post' />"
- 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
@@ -782,15 +854,13 @@ class FormHelperTest < ActionView::TestCase
def test_submit_with_object_as_existing_record_and_locale_strings
old_locale, I18n.locale = I18n.locale, :submit
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.submit
- end
+ form_for(@post) do |f|
+ concat f.submit
end
- expected = whole_form do
- "<input name='commit' id='post_submit' type='submit' value='Confirm Post changes' />"
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ "<input name='commit' type='submit' value='Confirm Post changes' />"
+ end
assert_dom_equal expected, output_buffer
ensure
@@ -804,9 +874,9 @@ class FormHelperTest < ActionView::TestCase
concat f.submit :class => "extra"
end
- expected = whole_form do
- "<input name='commit' class='extra' id='post_submit' type='submit' value='Save changes' />"
- end
+ expected = whole_form do
+ "<input name='commit' class='extra' type='submit' value='Save changes' />"
+ end
assert_dom_equal expected, output_buffer
ensure
@@ -816,15 +886,13 @@ class FormHelperTest < ActionView::TestCase
def test_submit_with_object_and_nested_lookup
old_locale, I18n.locale = I18n.locale, :submit
- assert_deprecated do
- form_for(:another_post, @post) do |f|
- concat f.submit
- end
+ form_for(@post, :as => :another_post) do |f|
+ concat f.submit
end
- expected = whole_form do
- "<input name='commit' id='another_post_submit' type='submit' value='Update your Post' />"
- end
+ expected = whole_form('/posts/123', 'another_post_edit', 'another_post_edit', :method => 'put') do
+ "<input name='commit' type='submit' value='Update your Post' />"
+ end
assert_dom_equal expected, output_buffer
ensure
@@ -832,188 +900,167 @@ class FormHelperTest < ActionView::TestCase
end
def test_nested_fields_for
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.fields_for(:comment, @post) { |c|
- concat c.text_field(:title)
- }
- end
+ @comment.body = 'Hello World'
+ form_for(@post) do |f|
+ concat f.fields_for(@comment) { |c|
+ concat c.text_field(:body)
+ }
end
- expected = whole_form do
- "<input name='post[comment][title]' size='30' type='text' id='post_comment_title' value='Hello World' />"
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ "<input name='post[comment][body]' size='30' 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
- assert_deprecated do
- form_for('post[]', @post) do |f|
- concat f.text_field(:title)
- concat f.fields_for('comment[]', @comment) { |c|
- concat c.text_field(:name)
- }
- end
+ 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 do
- "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
- "<input name='post[123][comment][][name]' size='30' type='text' id='post_123_comment__name' value='new comment' />"
- end
+ expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
+ "<input name='post[123][comment][][name]' size='30' 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
- assert_deprecated do
- form_for('post', @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
+ 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 do
- "<input name='post[1][title]' size='30' type='text' id='post_1_title' value='Hello World' />" +
- "<input name='post[1][comment][1][name]' size='30' type='text' id='post_1_comment_1_name' value='new comment' />"
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'put') do
+ "<input name='post[1][title]' size='30' type='text' id='post_1_title' value='Hello World' />" +
+ "<input name='post[1][comment][1][name]' size='30' 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
- assert_deprecated do
- output_buffer = form_for(:post, @post, :index => 1) do |f|
- concat f.fields_for(:comment, @post) { |c|
- concat c.text_field(:title)
- }
- end
+ 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 do
- "<input name='post[1][comment][title]' size='30' type='text' id='post_1_comment_title' value='Hello World' />"
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'put') do
+ "<input name='post[1][comment][title]' size='30' 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
- assert_deprecated do
- form_for(:post, @post, :index => 1) do |f|
- concat f.fields_for(:comment, @post, :index => 5) { |c|
- concat c.text_field(:title)
- }
- end
+ 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 do
- "<input name='post[1][comment][5][title]' size='30' type='text' id='post_1_comment_5_title' value='Hello World' />"
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'put') do
+ "<input name='post[1][comment][5][title]' size='30' 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
- assert_deprecated do
- form_for("post[]", @post) do |f|
- concat f.fields_for(:comment, @post) { |c|
- concat c.text_field(:title)
- }
- end
+ form_for(@post, :as => "post[]") do |f|
+ concat f.fields_for(:comment, @post) { |c|
+ concat c.text_field(:title)
+ }
end
- expected = whole_form do
- "<input name='post[123][comment][title]' size='30' type='text' id='post_123_comment_title' value='Hello World' />"
- end
+ expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ "<input name='post[123][comment][title]' size='30' 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
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.fields_for(:comment, @post, :index => 5) { |c|
- concat c.radio_button(:title, "hello")
- }
- end
+ form_for(@post) do |f|
+ concat f.fields_for(:comment, @post, :index => 5) { |c|
+ concat c.radio_button(:title, "hello")
+ }
end
- expected = whole_form do
- "<input name='post[comment][5][title]' type='radio' id='post_comment_5_title_hello' value='hello' />"
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'put') 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
- assert_deprecated do
- form_for("post[]", @post) do |f|
- concat f.fields_for("comment[]", @post) { |c|
- concat c.text_field(:title)
- }
- end
+ form_for(@post, :as => "post[]") do |f|
+ concat f.fields_for("comment[]", @post) { |c|
+ concat c.text_field(:title)
+ }
end
- expected = whole_form do
- "<input name='post[123][comment][123][title]' size='30' type='text' id='post_123_comment_123_title' value='Hello World' />"
- end
+ expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ "<input name='post[123][comment][123][title]' size='30' 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
- assert_deprecated do
- output_buffer = form_for("post[]", @post) do |f|
- concat f.fields_for(:comment, @post, :index => 5) { |c|
- concat c.text_field(:title)
- }
- end
-
- output_buffer << form_for(:post, @post, :index => 1) do |f|
- concat f.fields_for("comment[]", @post) { |c|
- concat c.text_field(:title)
- }
- end
+ output_buffer = form_for(@post, :as => "post[]") do |f|
+ concat f.fields_for(:comment, @post, :index => 5) { |c|
+ concat c.text_field(:title)
+ }
+ end
- expected = whole_form do
- "<input name='post[123][comment][5][title]' size='30' type='text' id='post_123_comment_5_title' value='Hello World' />"
- end + whole_form do
- "<input name='post[1][comment][123][title]' size='30' type='text' id='post_1_comment_123_title' value='Hello World' />"
- 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
- assert_dom_equal expected, output_buffer
+ expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ "<input name='post[123][comment][5][title]' size='30' type='text' id='post_123_comment_5_title' value='Hello World' />"
+ end + whole_form('/posts/123', 'post_edit', 'post_edit', 'put') do
+ "<input name='post[1][comment][123][title]' size='30' 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
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- concat f.fields_for(:author) { |af|
- concat af.text_field(:name)
- }
- end
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="new author" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="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
- assert_deprecated do
- form_for(:post, @post) do |f|
- f.fields_for(:author, Author.new(123)) do |af|
- assert_not_nil af.object
- assert_equal 123, af.object.id
- end
+ 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
@@ -1021,67 +1068,238 @@ class FormHelperTest < ActionView::TestCase
def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association
@post.author = Author.new(321)
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- concat f.fields_for(:author) { |af|
- concat af.text_field(:name)
+ 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 => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_inline_block
+ @post.author = Author.new(321)
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_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 => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />'
+ 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 => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />'
+ 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 => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement
+ @post.author = Author.new(321)
+
+ 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 => 'put') do
+ '<input name="post[title]" size="30" 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]" size="30" 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
- '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
assert_dom_equal expected, output_buffer
end
- def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement
+ 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)
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- concat f.fields_for(:author) { |af|
- concat af.hidden_field(:id)
- concat af.text_field(:name)
+ 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 do
- '<input name="post[title]" size="30" 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]" size="30" type="text" value="author #321" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" 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
+ 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 => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" 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)
- assert_deprecated do
- form_for(:post, @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
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
- '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
- '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
- '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" 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 => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
assert_dom_equal expected, output_buffer
end
@@ -1089,25 +1307,23 @@ class FormHelperTest < ActionView::TestCase
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) }
- assert_deprecated do
- form_for(:post, @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
+ 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 do
- '<input name="post[title]" size="30" 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]" size="30" 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]" size="30" type="text" value="comment #2" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_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]" size="30" type="text" value="comment #2" />'
+ end
assert_dom_equal expected, output_buffer
end
@@ -1115,22 +1331,20 @@ class FormHelperTest < ActionView::TestCase
def test_nested_fields_for_with_new_records_on_a_nested_attributes_collection_association
@post.comments = [Comment.new, Comment.new]
- assert_deprecated do
- form_for(:post, @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
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" />' +
- '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />'
+ end
assert_dom_equal expected, output_buffer
end
@@ -1138,40 +1352,36 @@ class FormHelperTest < ActionView::TestCase
def test_nested_fields_for_with_existing_and_new_records_on_a_nested_attributes_collection_association
@post.comments = [Comment.new(321), Comment.new]
- assert_deprecated do
- form_for(:post, @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
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #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]" size="30" type="text" value="new comment" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #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]" size="30" type="text" value="new comment" />'
+ end
assert_dom_equal expected, output_buffer
end
def test_nested_fields_for_with_an_empty_supplied_attributes_collection
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- f.fields_for(:comments, []) do |cf|
- concat cf.text_field(:name)
- end
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />'
+ end
assert_dom_equal expected, output_buffer
end
@@ -1179,22 +1389,41 @@ class FormHelperTest < ActionView::TestCase
def test_nested_fields_for_with_existing_records_on_a_supplied_nested_attributes_collection
@post.comments = Array.new(2) { |id| Comment.new(id + 1) }
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- concat f.fields_for(:comments, @post.comments) { |cf|
- concat cf.text_field(:name)
- }
- end
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
- '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
- '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
- '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_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 => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
assert_dom_equal expected, output_buffer
end
@@ -1203,22 +1432,20 @@ class FormHelperTest < ActionView::TestCase
comments = Array.new(2) { |id| Comment.new(id + 1) }
@post.comments = []
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- concat f.fields_for(:comments, comments) { |cf|
- concat cf.text_field(:name)
- }
- end
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
- '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
- '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
- '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
assert_dom_equal expected, output_buffer
end
@@ -1227,22 +1454,20 @@ class FormHelperTest < ActionView::TestCase
@post.comments = [Comment.new(321), Comment.new]
yielded_comments = []
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- concat f.fields_for(:comments) { |cf|
- concat cf.text_field(:name)
- yielded_comments << cf.object
- }
- end
+ 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 do
- '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
- '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #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]" size="30" type="text" value="new comment" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #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]" size="30" type="text" value="new comment" />'
+ end
assert_dom_equal expected, output_buffer
assert_equal yielded_comments, @post.comments
@@ -1251,18 +1476,16 @@ class FormHelperTest < ActionView::TestCase
def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association
@post.comments = []
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.fields_for(:comments, Comment.new(321), :child_index => 'abc') { |cf|
- concat cf.text_field(:name)
- }
- end
+ 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 do
- '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" size="30" type="text" value="comment #321" />' +
- '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />'
- end
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" size="30" 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
@@ -1274,43 +1497,41 @@ class FormHelperTest < ActionView::TestCase
@post.tags[0].relevances = []
@post.tags[1].relevances = []
- assert_deprecated do
- form_for(:post, @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)
- }
+ 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[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)
- }
+ }
+ 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
+ }
end
- expected = whole_form do
- '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' +
- '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" size="30" 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]" size="30" type="text" value="tag #123" />' +
- '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" size="30" 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]" size="30" type="text" value="tag #456" />' +
- '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" size="30" 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
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" size="30" 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]" size="30" type="text" value="tag #123" />' +
+ '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" size="30" 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]" size="30" type="text" value="tag #456" />' +
+ '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" size="30" 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
@@ -1438,47 +1659,40 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_for_and_fields_for
- assert_deprecated do
- form_for(:post, @post, :html => { :id => 'create-post' }) do |post_form|
- concat post_form.text_field(:title)
- concat post_form.text_area(:body)
+ 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
+ concat fields_for(:parent_post, @post) { |parent_fields|
+ concat parent_fields.check_box(:secret)
+ }
end
- expected =
- "<form accept-charset='UTF-8' action='http://www.example.com' id='create-post' method='post'>" +
- snowman +
+ expected = whole_form('/posts/123', 'create-post', 'post_edit', :method => 'put') do
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back 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' />" +
- "</form>"
+ "<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
- assert_deprecated do
- form_for(:post, @post, :html => { :id => 'create-post' }) do |post_form|
- concat post_form.text_field(:title)
- concat post_form.text_area(:body)
+ 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
+ concat post_form.fields_for(@comment) { |comment_fields|
+ concat comment_fields.text_field(:name)
+ }
end
- expected =
- whole_form("http://www.example.com", "create-post") do
- "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
- "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
- "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' size='30' />"
- end
+ expected = whole_form('/posts/123', 'create-post', 'post_edit', :method => 'put') do
+ "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
+ "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' size='30' />"
+ end
assert_dom_equal expected, output_buffer
end
@@ -1494,63 +1708,63 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_for_with_labelled_builder
- assert_deprecated do
- form_for(:post, @post, :builder => LabelledFormBuilder) do |f|
- concat f.text_field(:title)
- concat f.text_area(:body)
- concat f.check_box(:secret)
- end
+ 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 do
- "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
- "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back 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
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
+ "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back 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 snowman(method = nil)
txt = %{<div style="margin:0;padding:0;display:inline">}
- txt << %{<input name="_e" type="hidden" value="&#9731;" />}
- txt << %{<input name="_method" type="hidden" value="#{method}" />} if method
+ txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
+ if (method && !['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", id = nil, html_class = nil, remote = nil)
+ 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
- txt << %{ method="post">}
+ method = method.to_s == "get" ? "get" : "post"
+ txt << %{ method="#{method}">}
end
- def whole_form(action = "http://www.example.com", id = nil, html_class = nil, options = nil)
+ def whole_form(action = "/", id = nil, html_class = nil, options = nil)
contents = block_given? ? yield : ""
if options.is_a?(Hash)
- method, remote = options.values_at(:method, :remote)
+ method, remote, multipart = options.values_at(:method, :remote, :multipart)
else
method = options
end
- form_text(action, id, html_class, remote) + snowman(method) + contents + "</form>"
+ form_text(action, id, html_class, remote, multipart, method) + snowman(method) + contents + "</form>"
end
def test_default_form_builder
old_default_form_builder, ActionView::Base.default_form_builder =
ActionView::Base.default_form_builder, LabelledFormBuilder
- assert_deprecated do
- form_for(:post, @post) do |f|
- concat f.text_field(:title)
- concat f.text_area(:body)
- concat f.check_box(:secret)
- end
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
end
- expected = whole_form do
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
"<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
"<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back 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/>"
@@ -1579,12 +1793,10 @@ class FormHelperTest < ActionView::TestCase
def test_form_for_with_labelled_builder_with_nested_fields_for_without_options_hash
klass = nil
- assert_deprecated do
- form_for(:post, @post, :builder => LabelledFormBuilder) do |f|
- f.fields_for(:comments, Comment.new) do |nested_fields|
- klass = nested_fields.class
- ''
- end
+ form_for(@post, :builder => LabelledFormBuilder) do |f|
+ f.fields_for(:comments, Comment.new) do |nested_fields|
+ klass = nested_fields.class
+ ''
end
end
@@ -1594,12 +1806,10 @@ class FormHelperTest < ActionView::TestCase
def test_form_for_with_labelled_builder_with_nested_fields_for_with_options_hash
klass = nil
- assert_deprecated do
- form_for(:post, @post, :builder => LabelledFormBuilder) do |f|
- f.fields_for(:comments, Comment.new, :index => 'foo') do |nested_fields|
- klass = nested_fields.class
- ''
- end
+ form_for(@post, :builder => LabelledFormBuilder) do |f|
+ f.fields_for(:comments, Comment.new, :index => 'foo') do |nested_fields|
+ klass = nested_fields.class
+ ''
end
end
@@ -1611,12 +1821,10 @@ class FormHelperTest < ActionView::TestCase
def test_form_for_with_labelled_builder_with_nested_fields_for_with_custom_builder
klass = nil
- assert_deprecated do
- form_for(:post, @post, :builder => LabelledFormBuilder) do |f|
- f.fields_for(:comments, Comment.new, :builder => LabelledFormBuilderSubclass) do |nested_fields|
- klass = nested_fields.class
- ''
- end
+ form_for(@post, :builder => LabelledFormBuilder) do |f|
+ f.fields_for(:comments, Comment.new, :builder => LabelledFormBuilderSubclass) do |nested_fields|
+ klass = nested_fields.class
+ ''
end
end
@@ -1624,39 +1832,29 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_for_with_html_options_adds_options_to_form_tag
- assert_deprecated do
- form_for(:post, @post, :html => {:id => 'some_form', :class => 'some_class'}) do |f| end
- end
- expected = whole_form("http://www.example.com", "some_form", "some_class")
+ form_for(@post, :html => {:id => 'some_form', :class => 'some_class'}) do |f| end
+ expected = whole_form("/posts/123", "some_form", "some_class", 'put')
assert_dom_equal expected, output_buffer
end
def test_form_for_with_string_url_option
- assert_deprecated do
- form_for(:post, @post, :url => 'http://www.otherdomain.com') do |f| end
- end
+ form_for(@post, :url => 'http://www.otherdomain.com') do |f| end
- assert_equal whole_form("http://www.otherdomain.com"), output_buffer
- # assert_equal '<form action="http://www.otherdomain.com" method="post"></form>', output_buffer
+ assert_equal whole_form("http://www.otherdomain.com", 'edit_post_123', 'edit_post', 'put'), output_buffer
end
def test_form_for_with_hash_url_option
- assert_deprecated do
- form_for(:post, @post, :url => {:controller => 'controller', :action => 'action'}) do |f| end
- end
+ 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
- assert_deprecated do
- form_for(:post, @post, :url => @post) do |f| end
- end
+ form_for(@post, :url => @post) do |f| end
- expected = whole_form("/posts/123")
- # expected = "<form action=\"/posts/123\" method=\"post\"></form>"
+ expected = whole_form("/posts/123", 'edit_post_123', 'edit_post', 'put')
assert_equal expected, output_buffer
end
@@ -1682,14 +1880,14 @@ class FormHelperTest < ActionView::TestCase
@comment.save
form_for([@post, @comment]) {}
- expected = whole_form(comment_path(@post, @comment), "edit_comment_1", "edit_comment", "put")
+ expected = whole_form(post_comment_path(@post, @comment), "edit_comment_1", "edit_comment", "put")
assert_dom_equal expected, output_buffer
end
def test_form_for_with_new_object_in_list
form_for([@post, @comment]) {}
- expected = whole_form(comments_path(@post), "new_comment", "new_comment")
+ expected = whole_form(post_comments_path(@post), "new_comment", "new_comment")
assert_dom_equal expected, output_buffer
end
@@ -1697,14 +1895,14 @@ class FormHelperTest < ActionView::TestCase
@comment.save
form_for([:admin, @post, @comment]) {}
- expected = whole_form(admin_comment_path(@post, @comment), "edit_comment_1", "edit_comment", "put")
+ expected = whole_form(admin_post_comment_path(@post, @comment), "edit_comment_1", "edit_comment", "put")
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_comments_path(@post), "new_comment", "new_comment")
+ expected = whole_form(admin_post_comments_path(@post), "new_comment", "new_comment")
assert_dom_equal expected, output_buffer
end
@@ -1721,35 +1919,8 @@ class FormHelperTest < ActionView::TestCase
end
protected
- def comments_path(post)
- "/posts/#{post.id}/comments"
- end
- alias_method :post_comments_path, :comments_path
-
- def comment_path(post, comment)
- "/posts/#{post.id}/comments/#{comment.id}"
- end
- alias_method :post_comment_path, :comment_path
-
- def admin_comments_path(post)
- "/admin/posts/#{post.id}/comments"
- end
- alias_method :admin_post_comments_path, :admin_comments_path
-
- def admin_comment_path(post, comment)
- "/admin/posts/#{post.id}/comments/#{comment.id}"
- end
- alias_method :admin_post_comment_path, :admin_comment_path
-
- def posts_path
- "/posts"
- end
-
- def post_path(post)
- "/posts/#{post.id}"
- end
-
def protect_against_forgery?
false
end
+
end
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index d14e5020c7..93ff7ba0fd 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -1,13 +1,19 @@
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)
+ Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments)
Continent = Struct.new('Continent', :continent_name, :countries)
Country = Struct.new('Country', :country_id, :country_name)
Firm = Struct.new('Firm', :time_zone)
@@ -130,6 +136,13 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_boolean_array_options_for_select_with_selection_and_disabled_value
+ assert_dom_equal(
+ "<option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option>",
+ options_for_select([ true, false ], :selected => false, :disabled => nil)
+ )
+ end
+
def test_array_options_for_string_include_in_other_string_bug_fix
assert_dom_equal(
"<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>",
@@ -176,6 +189,68 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_collection_options_with_preselected_value_as_string_and_option_value_is_integer
+ albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")]
+ 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=\"&lt;Africa&gt;\"><option value=\"&lt;sa&gt;\">&lt;South Africa&gt;</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>",
@@ -289,6 +364,10 @@ class FormOptionsHelperTest < ActionView::TestCase
opts
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>"
@@ -298,6 +377,15 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_select_with_boolean_method
+ @post = Post.new
+ @post.allow_comments = false
+ assert_dom_equal(
+ "<select id=\"post_allow_comments\" name=\"post[allow_comments]\"><option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option></select>",
+ select("post", "allow_comments", %w( true false ))
+ )
+ end
+
def test_select_under_fields_for
@post = Post.new
@post.category = "<mus>"
@@ -305,13 +393,26 @@ class FormOptionsHelperTest < ActionView::TestCase
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=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</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=\"&lt;mus&gt;\" selected=\"selected\">&lt;mus&gt;</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>"
@@ -438,11 +539,11 @@ class FormOptionsHelperTest < ActionView::TestCase
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>"
+
+ 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,
+ expected,
select("album[]", "genre", %w[rap rock country], {}, { :index => nil })
)
end
@@ -491,7 +592,7 @@ class FormOptionsHelperTest < ActionView::TestCase
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=\"&lt;Abe&gt;\">&lt;Abe&gt;</option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
output_buffer
@@ -599,7 +700,7 @@ class FormOptionsHelperTest < ActionView::TestCase
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" +
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index 6c85952d40..f8671f2980 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -12,20 +12,24 @@ class FormTagHelperTest < ActionView::TestCase
method = options[:method]
txt = %{<div style="margin:0;padding:0;display:inline">}
- txt << %{<input name="_e" type="hidden" value="&#9731;" />}
- txt << %{<input name="_method" type="hidden" value="#{method}" />} if method
+ txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
+ if (method && !['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 = options.values_at(:remote, :enctype, :html_class, :id)
+ 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="post">}
+ txt << %{ method="#{method}">}
end
def whole_form(action = "http://www.example.com", options = {})
@@ -201,12 +205,6 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
- def test_select_tag_with_array_options
- assert_deprecated /array/ do
- select_tag "people", ["<option>david</option>"]
- end
- 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">hello world</textarea>)
@@ -387,6 +385,57 @@ class FormTagHelperTest < ActionView::TestCase
)
end
+ def test_button_tag
+ assert_dom_equal(
+ %(<button name="button" type="submit">Button</button>),
+ button_tag
+ )
+ end
+
+ def test_button_tag_with_submit_type
+ assert_dom_equal(
+ %(<button name="button" type="submit">Save</button>),
+ button_tag("Save", :type => "submit")
+ )
+ end
+
+ def test_button_tag_with_button_type
+ assert_dom_equal(
+ %(<button name="button" type="button">Button</button>),
+ button_tag("Button", :type => "button")
+ )
+ end
+
+ def test_button_tag_with_reset_type
+ assert_dom_equal(
+ %(<button name="button" type="reset">Reset</button>),
+ button_tag("Reset", :type => "reset")
+ )
+ end
+
+ def test_button_tag_with_disabled_option
+ assert_dom_equal(
+ %(<button name="button" type="reset" disabled="disabled">Reset</button>),
+ button_tag("Reset", :type => "reset", :disabled => true)
+ )
+ end
+
+ def test_button_tag_escape_content
+ assert_dom_equal(
+ %(<button name="button" type="reset" disabled="disabled">&lt;b&gt;Reset&lt;/b&gt;</button>),
+ button_tag("<b>Reset</b>", :type => "reset", :disabled => true)
+ )
+ end
+
+ def test_button_tag_with_block
+ assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { 'Content' })
+ end
+
+ def test_button_tag_with_block_and_options
+ output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') }
+ assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output)
+ end
+
def test_image_submit_tag_with_confirmation
assert_dom_equal(
%(<input type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
diff --git a/actionpack/test/template/html-scanner/document_test.rb b/actionpack/test/template/html-scanner/document_test.rb
index c68f04fa75..ddfb351595 100644
--- a/actionpack/test/template/html-scanner/document_test.rb
+++ b/actionpack/test/template/html-scanner/document_test.rb
@@ -15,7 +15,7 @@ class DocumentTest < Test::Unit::TestCase
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>
diff --git a/actionpack/test/template/html-scanner/node_test.rb b/actionpack/test/template/html-scanner/node_test.rb
index b0df36877e..f4b9b198e8 100644
--- a/actionpack/test/template/html-scanner/node_test.rb
+++ b/actionpack/test/template/html-scanner/node_test.rb
@@ -1,39 +1,39 @@
require 'abstract_unit'
class NodeTest < Test::Unit::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
@@ -58,7 +58,7 @@ class NodeTest < Test::Unit::TestCase
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
diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb
index c9edde8892..fcc3782f04 100644
--- a/actionpack/test/template/html-scanner/sanitizer_test.rb
+++ b/actionpack/test/template/html-scanner/sanitizer_test.rb
@@ -24,11 +24,11 @@ class SanitizerTest < ActionController::TestCase
def test_strip_links
sanitizer = HTML::LinkSanitizer.new
- assert_equal "Dont touch me", sanitizer.sanitize("Dont touch me")
+ 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 "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>")
@@ -58,7 +58,7 @@ class SanitizerTest < ActionController::TestCase
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>}
@@ -130,6 +130,13 @@ class SanitizerTest < ActionController::TestCase
assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad")
end
end
+
+ def test_should_accept_good_protocols_ignoring_case
+ sanitizer = HTML::WhiteListSanitizer.new
+ HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
+ assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto.capitalize}://good")
+ end
+ end
def test_should_accept_good_protocols
sanitizer = HTML::WhiteListSanitizer.new
@@ -147,9 +154,9 @@ class SanitizerTest < ActionController::TestCase
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 SRC="javascript:alert('XSS');">),
+ %(<IMG SRC=javascript:alert('XSS')>),
+ %(<IMG SRC=JaVaScRiPt:alert('XSS')>),
%(<IMG """><SCRIPT>alert("XSS")</SCRIPT>">),
%(<IMG SRC=javascript:alert(&quot;XSS&quot;)>),
%(<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>),
@@ -166,28 +173,28 @@ class SanitizerTest < ActionController::TestCase
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>), "&lt;"
assert_sanitized %(<iframe src=http://ha.ckers.org/scriptlet.html\n<a), %(&lt;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>"
@@ -214,15 +221,15 @@ class SanitizerTest < ActionController::TestCase
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
diff --git a/actionpack/test/template/html-scanner/tag_node_test.rb b/actionpack/test/template/html-scanner/tag_node_test.rb
index d1d4667378..0d87f1bd42 100644
--- a/actionpack/test/template/html-scanner/tag_node_test.rb
+++ b/actionpack/test/template/html-scanner/tag_node_test.rb
@@ -7,7 +7,7 @@ class TagNodeTest < Test::Unit::TestCase
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
@@ -15,28 +15,28 @@ class TagNodeTest < Test::Unit::TestCase
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"]
@@ -46,27 +46,27 @@ class TagNodeTest < Test::Unit::TestCase
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'\" />")
- assert_equal %(<a b='c' d='f' g='h \\'i\\'' />), node.to_s
+ assert_equal %(<a b="c" d="f" g="h 'i'" />), node.to_s
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/)
@@ -77,45 +77,45 @@ class TagNodeTest < Test::Unit::TestCase
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)
@@ -123,7 +123,7 @@ class TagNodeTest < Test::Unit::TestCase
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)
@@ -131,13 +131,13 @@ class TagNodeTest < Test::Unit::TestCase
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/}})
@@ -149,13 +149,13 @@ class TagNodeTest < Test::Unit::TestCase
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)
@@ -221,7 +221,7 @@ class TagNodeTest < Test::Unit::TestCase
assert !m.match(:after => {:tag => "span", :attributes => {:k => true}})
end
- def test_to_s
+ def test_tag_to_s
t = tag("<b x='foo'>")
tag("hello", t)
tag("<hr />", t)
@@ -229,7 +229,7 @@ class TagNodeTest < Test::Unit::TestCase
end
private
-
+
def tag(content, parent=nil)
node = HTML::Node.parse(parent,0,0,content)
parent.children << node if parent
diff --git a/actionpack/test/template/html-scanner/text_node_test.rb b/actionpack/test/template/html-scanner/text_node_test.rb
index 1ab3f4454e..6f61253ffa 100644
--- a/actionpack/test/template/html-scanner/text_node_test.rb
+++ b/actionpack/test/template/html-scanner/text_node_test.rb
@@ -4,27 +4,27 @@ class TextNodeTest < Test::Unit::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
diff --git a/actionpack/test/template/html-scanner/tokenizer_test.rb b/actionpack/test/template/html-scanner/tokenizer_test.rb
index a001bcbbad..bf45a7c2e3 100644
--- a/actionpack/test/template/html-scanner/tokenizer_test.rb
+++ b/actionpack/test/template/html-scanner/tokenizer_test.rb
@@ -29,7 +29,7 @@ class TokenizerTest < Test::Unit::TestCase
tokenize "</tag>"
assert_next "</tag>"
end
-
+
def test_tag_with_single_quoted_attribute
tokenize %{<tag a='hello'>x}
assert_next %{<tag a='hello'>}
@@ -49,7 +49,7 @@ class TokenizerTest < Test::Unit::TestCase
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>}
@@ -59,12 +59,12 @@ class TokenizerTest < Test::Unit::TestCase
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">}
@@ -90,7 +90,7 @@ class TokenizerTest < Test::Unit::TestCase
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 }
@@ -109,22 +109,22 @@ class TokenizerTest < Test::Unit::TestCase
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
diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb
index a8ca19931b..2e7484afaf 100644
--- a/actionpack/test/template/javascript_helper_test.rb
+++ b/actionpack/test/template/javascript_helper_test.rb
@@ -22,8 +22,6 @@ class JavaScriptHelperTest < ActionView::TestCase
ActiveSupport.escape_html_entities_in_json = false
end
- def _evaluate_assigns_and_ivars() 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'))
diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb
index eb1e548672..8b8b005a1d 100644
--- a/actionpack/test/template/log_subscriber_test.rb
+++ b/actionpack/test/template/log_subscriber_test.rb
@@ -29,7 +29,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
wait
assert_equal 1, @logger.logged(:info).size
- assert_match /Rendered test\/hello_world\.erb/, @logger.logged(:info).last
+ assert_match(/Rendered test\/hello_world\.erb/, @logger.logged(:info).last)
end
def test_render_text_template
@@ -37,7 +37,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
wait
assert_equal 1, @logger.logged(:info).size
- assert_match /Rendered text template/, @logger.logged(:info).last
+ assert_match(/Rendered text template/, @logger.logged(:info).last)
end
def test_render_inline_template
@@ -45,7 +45,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
wait
assert_equal 1, @logger.logged(:info).size
- assert_match /Rendered inline template/, @logger.logged(:info).last
+ assert_match(/Rendered inline template/, @logger.logged(:info).last)
end
def test_render_partial_template
@@ -53,16 +53,16 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
wait
assert_equal 1, @logger.logged(:info).size
- assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last
+ assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
end
def test_render_partial_with_implicit_path
- @view.stubs(:controller_path).returns("test")
+ @view.stubs(:controller_prefixes).returns(%w(test))
@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
+ assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
end
def test_render_collection_template
@@ -70,24 +70,24 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
wait
assert_equal 1, @logger.logged(:info).size
- assert_match /Rendered test\/_customer.erb/, @logger.logged(:info).last
+ assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
end
def test_render_collection_with_implicit_path
- @view.stubs(:controller_path).returns("test")
+ @view.stubs(:controller_prefixes).returns(%w(test))
@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
+ assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
end
def test_render_collection_template_without_path
- @view.stubs(:controller_path).returns("test")
+ @view.stubs(:controller_prefixes).returns(%w(test))
@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
+ assert_match(/Rendered collection/, @logger.logged(:info).last)
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb
index cc71cb42d0..8d063e66b0 100644
--- a/actionpack/test/template/lookup_context_test.rb
+++ b/actionpack/test/template/lookup_context_test.rb
@@ -47,7 +47,7 @@ class LookupContextTest < ActiveSupport::TestCase
end
test "handles */* formats" do
- @lookup_context.formats = [:"*/*"]
+ @lookup_context.formats = ["*/*"]
assert_equal Mime::SET, @lookup_context.formats
end
@@ -73,25 +73,25 @@ class LookupContextTest < ActiveSupport::TestCase
assert_equal :pt, I18n.locale
assert_equal :pt, @lookup_context.locale
ensure
- I18n.config = I18n.config.i18n_config
+ I18n.config = I18n.config.original_config
end
assert_equal :pt, I18n.locale
end
test "find templates using the given view paths and configured details" do
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
assert_equal "Hello world!", template.source
@lookup_context.locale = :da
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
assert_equal "Hey verden", template.source
end
test "found templates respects given formats if one cannot be found from template or handler" do
ActionView::Template::Handlers::ERB.expects(:default_format).returns(nil)
@lookup_context.formats = [:text]
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
assert_equal [:text], template.formats
end
@@ -100,8 +100,8 @@ class LookupContextTest < ActiveSupport::TestCase
@lookup_context.with_fallbacks do
assert_equal 3, @lookup_context.view_paths.size
- assert @lookup_context.view_paths.include?(ActionView::FileSystemResolver.new(""))
- assert @lookup_context.view_paths.include?(ActionView::FileSystemResolver.new("/"))
+ assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new(""))
+ assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new("/"))
end
end
@@ -137,30 +137,137 @@ class LookupContextTest < ActiveSupport::TestCase
test "gives the key forward to the resolver, so it can be used as cache key" do
@lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo")
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# Now we are going to change the template, but it won't change the returned template
# since we will hit the cache.
@lookup_context.view_paths.first.hash["test/_foo.erb"] = "Bar"
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# This time we will change the locale. The updated template should be picked since
# lookup_context generated a new key after we changed the locale.
@lookup_context.locale = :da
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Bar", template.source
# Now we will change back the locale and it will still pick the old template.
# This is expected because lookup_context will reuse the previous key for :en locale.
@lookup_context.locale = :en
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# Finally, we can expire the cache. And the expected template will be used.
@lookup_context.view_paths.first.clear_cache
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Bar", template.source
end
-end \ No newline at end of file
+
+ 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 "data can be stored in cached templates" do
+ template = @lookup_context.find("hello_world", %w(test))
+ template.data["cached"] = "data"
+ assert_equal "Hello world!", template.source
+
+ template = @lookup_context.find("hello_world", %w(test))
+ assert_equal "data", template.data["cached"]
+ assert_equal "Hello world!", template.source
+ end
+end
+
+class LookupContextWithFalseCaching < ActiveSupport::TestCase
+ def setup
+ @resolver = ActionView::FixtureResolver.new("test/_foo.erb" => ["Foo", Time.utc(2000)])
+ @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
+
+ test "data can be stored as long as template was not updated" do
+ template = @lookup_context.find("foo", %w(test), true)
+ template.data["cached"] = "data"
+ assert_equal "Foo", template.source
+
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "data", template.data["cached"]
+ assert_equal "Foo", template.source
+
+ @resolver.hash["test/_foo.erb"][1] = Time.now.utc
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_nil template.data["cached"]
+ 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
+end
diff --git a/actionpack/test/template/number_helper_i18n_test.rb b/actionpack/test/template/number_helper_i18n_test.rb
index 8561019461..5df09b4d3b 100644
--- a/actionpack/test/template/number_helper_i18n_test.rb
+++ b/actionpack/test/template/number_helper_i18n_test.rb
@@ -7,7 +7,7 @@ class NumberHelperTest < ActionView::TestCase
I18n.backend.store_translations 'ts',
:number => {
:format => { :precision => 3, :delimiter => ',', :separator => '.', :significant => false, :strip_insignificant_zeros => false },
- :currency => { :format => { :unit => '&$', :format => '%u - %n', :precision => 2 } },
+ :currency => { :format => { :unit => '&$', :format => '%u - %n', :negative_format => '(%u - %n)', :precision => 2 } },
:human => {
:format => {
:precision => 2,
@@ -41,17 +41,20 @@ class NumberHelperTest < ActionView::TestCase
: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_currency
+ 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_clean_i18n_settings
clean_i18n do
assert_equal("$10.00", number_to_currency(10))
+ assert_equal("-$10.00", number_to_currency(-10))
end
end
- def test_number_with_precision
+ def test_number_with_i18n_precision
#Delimiter was set to ""
assert_equal("10000", number_with_precision(10000, :locale => 'ts'))
@@ -60,12 +63,12 @@ class NumberHelperTest < ActionView::TestCase
end
- def test_number_with_delimiter
+ def test_number_with_i18n_delimiter
#Delimiter "," and separator "."
assert_equal("1,000,000.234", number_with_delimiter(1000000.234, :locale => 'ts'))
end
- def test_number_to_percentage
+ 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
@@ -74,7 +77,7 @@ class NumberHelperTest < ActionView::TestCase
assert_equal("12434%", number_to_percentage(12434, :locale => 'ts'))
end
- def test_number_to_human_size
+ 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'))
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index 7f787b7b00..c8d50ebf75 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -45,11 +45,15 @@ class NumberHelperTest < ActionView::TestCase
def test_number_to_currency
assert_equal("$1,234,567,890.50", number_to_currency(1234567890.50))
assert_equal("$1,234,567,890.51", number_to_currency(1234567890.506))
+ assert_equal("-$1,234,567,890.50", number_to_currency(-1234567890.50))
+ assert_equal("-$ 1,234,567,890.50", number_to_currency(-1234567890.50, {:format => "%u %n"}))
+ assert_equal("($1,234,567,890.50)", number_to_currency(-1234567890.50, {:negative_format => "(%u%n)"}))
assert_equal("$1,234,567,892", number_to_currency(1234567891.50, {:precision => 0}))
assert_equal("$1,234,567,890.5", number_to_currency(1234567890.50, {:precision => 1}))
assert_equal("&pound;1234567890,50", number_to_currency(1234567890.50, {:unit => "&pound;", :separator => ",", :delimiter => ""}))
assert_equal("$1,234,567,890.50", number_to_currency("1234567890.50"))
assert_equal("1,234,567,890.50 K&#269;", number_to_currency("1234567890.50", {:unit => "K&#269;", :format => "%n %u"}))
+ assert_equal("1,234,567,890.50 - K&#269;", number_to_currency("-1234567890.50", {:unit => "K&#269;", :format => "%n %u", :negative_format => "%n - %u"}))
end
def test_number_to_percentage
@@ -83,6 +87,7 @@ class NumberHelperTest < ActionView::TestCase
end
def test_number_with_precision
+ assert_equal("-111.235", number_with_precision(-111.2346))
assert_equal("111.235", number_with_precision(111.2346))
assert_equal("31.83", number_with_precision(31.825, :precision => 2))
assert_equal("111.23", number_with_precision(111.2346, :precision => 2))
@@ -95,6 +100,8 @@ class NumberHelperTest < ActionView::TestCase
assert_equal("0", number_with_precision(0, :precision => 0))
assert_equal("0.00100", number_with_precision(0.001, :precision => 5))
assert_equal("0.001", number_with_precision(0.00111, :precision => 3))
+ assert_equal("10.00", number_with_precision(9.995, :precision => 2))
+ assert_equal("11.00", number_with_precision(10.995, :precision => 2))
end
def test_number_with_precision_with_custom_delimiter_and_separator
@@ -116,10 +123,13 @@ class NumberHelperTest < ActionView::TestCase
assert_equal "9775.00", number_with_precision(9775, :precision => 6, :significant => true )
assert_equal "5.392900", number_with_precision(5.3929, :precision => 7, :significant => true )
assert_equal "0.0", number_with_precision(0, :precision => 2, :significant => true )
- assert_equal "0", number_with_precision(0, :precision => 1, :significant => true )
+ assert_equal "0", number_with_precision(0, :precision => 1, :significant => true )
assert_equal "0.0001", number_with_precision(0.0001, :precision => 1, :significant => true )
assert_equal "0.000100", number_with_precision(0.0001, :precision => 3, :significant => true )
assert_equal "0.0001", number_with_precision(0.0001111, :precision => 1, :significant => true )
+ assert_equal "10.0", number_with_precision(9.995, :precision => 3, :significant => true)
+ assert_equal "9.99", number_with_precision(9.994, :precision => 3, :significant => true)
+ assert_equal "11.0", number_with_precision(10.995, :precision => 3, :significant => true)
end
def test_number_with_precision_with_strip_insignificant_zeros
@@ -130,7 +140,7 @@ class NumberHelperTest < ActionView::TestCase
def test_number_with_precision_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 compatibily for number_to_human_size)
+ # so we treat it as if significant was false (increases backwards compatibility for number_to_human_size)
assert_equal "124", number_with_precision(123.987, :precision => 0, :significant => true)
assert_equal "12", number_with_precision(12, :precision => 0, :significant => true )
assert_equal "12", number_with_precision("12.3", :precision => 0, :significant => true )
@@ -184,53 +194,57 @@ class NumberHelperTest < ActionView::TestCase
end
def test_number_to_human
- assert_equal '123', number_to_human(123)
- assert_equal '1.23 Thousand', number_to_human(1234)
- assert_equal '12.3 Thousand', number_to_human(12345)
- assert_equal '1.23 Million', number_to_human(1234567)
- assert_equal '1.23 Billion', number_to_human(1234567890)
- assert_equal '1.23 Trillion', number_to_human(1234567890123)
- assert_equal '1.23 Quadrillion', number_to_human(1234567890123456)
- assert_equal '1230 Quadrillion', number_to_human(1234567890123456789)
- assert_equal '490 Thousand', number_to_human(489939, :precision => 2)
- assert_equal '489.9 Thousand', number_to_human(489939, :precision => 4)
- assert_equal '489 Thousand', number_to_human(489000, :precision => 4)
- assert_equal '489.0 Thousand', number_to_human(489000, :precision => 4, :strip_insignificant_zeros => false)
- assert_equal '1.2346 Million', number_to_human(1234567, :precision => 4, :significant => false)
- assert_equal '1,2 Million', number_to_human(1234567, :precision => 1, :significant => false, :separator => ',')
- assert_equal '1 Million', number_to_human(1234567, :precision => 0, :significant => true, :separator => ',') #significant forced to false
+ assert_equal '-123', number_to_human(-123)
+ assert_equal '-0.5', number_to_human(-0.5)
+ assert_equal '0', number_to_human(0)
+ assert_equal '0.5', number_to_human(0.5)
+ assert_equal '123', number_to_human(123)
+ assert_equal '1.23 Thousand', number_to_human(1234)
+ assert_equal '12.3 Thousand', number_to_human(12345)
+ assert_equal '1.23 Million', number_to_human(1234567)
+ assert_equal '1.23 Billion', number_to_human(1234567890)
+ assert_equal '1.23 Trillion', number_to_human(1234567890123)
+ assert_equal '1.23 Quadrillion', number_to_human(1234567890123456)
+ assert_equal '1230 Quadrillion', number_to_human(1234567890123456789)
+ assert_equal '490 Thousand', number_to_human(489939, :precision => 2)
+ assert_equal '489.9 Thousand', number_to_human(489939, :precision => 4)
+ assert_equal '489 Thousand', number_to_human(489000, :precision => 4)
+ assert_equal '489.0 Thousand', number_to_human(489000, :precision => 4, :strip_insignificant_zeros => false)
+ assert_equal '1.2346 Million', number_to_human(1234567, :precision => 4, :significant => false)
+ assert_equal '1,2 Million', number_to_human(1234567, :precision => 1, :significant => false, :separator => ',')
+ assert_equal '1 Million', number_to_human(1234567, :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', number_to_human(123456, :units => volume)
- assert_equal '12 ml', number_to_human(12, :units => volume)
- assert_equal '1.23 m3', 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_to_human(0.00123, :units => distance)
- assert_equal '1.23 cm', number_to_human(0.0123, :units => distance)
- assert_equal '1.23 dm', number_to_human(0.123, :units => distance)
- assert_equal '1.23 m', number_to_human(1.23, :units => distance)
- assert_equal '1.23 dam', number_to_human(12.3, :units => distance)
- assert_equal '1.23 hm', number_to_human(123, :units => distance)
- assert_equal '1.23 km', number_to_human(1230, :units => distance)
- assert_equal '1.23 km', number_to_human(1230, :units => distance)
- assert_equal '1.23 km', number_to_human(1230, :units => distance)
- assert_equal '12.3 km', 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_to_human(100, :units => gangster)
- assert_equal '25 hundred bucks', number_to_human(2500, :units => gangster)
- assert_equal '25 thousand quids', number_to_human(25000000, :units => gangster)
- assert_equal '12300 thousand quids', number_to_human(12345000000, :units => gangster)
-
- #Spaces are stripped from the resulting string
- assert_equal '4', number_to_human(4, :units => {:unit => "", :ten => 'tens '})
- assert_equal '4.5 tens', number_to_human(45, :units => {:unit => "", :ten => ' tens '})
+ #Only integers
+ volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
+ assert_equal '123 lt', number_to_human(123456, :units => volume)
+ assert_equal '12 ml', number_to_human(12, :units => volume)
+ assert_equal '1.23 m3', 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_to_human(0.00123, :units => distance)
+ assert_equal '1.23 cm', number_to_human(0.0123, :units => distance)
+ assert_equal '1.23 dm', number_to_human(0.123, :units => distance)
+ assert_equal '1.23 m', number_to_human(1.23, :units => distance)
+ assert_equal '1.23 dam', number_to_human(12.3, :units => distance)
+ assert_equal '1.23 hm', number_to_human(123, :units => distance)
+ assert_equal '1.23 km', number_to_human(1230, :units => distance)
+ assert_equal '1.23 km', number_to_human(1230, :units => distance)
+ assert_equal '1.23 km', number_to_human(1230, :units => distance)
+ assert_equal '12.3 km', 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_to_human(100, :units => gangster)
+ assert_equal '25 hundred bucks', number_to_human(2500, :units => gangster)
+ assert_equal '25 thousand quids', number_to_human(25000000, :units => gangster)
+ assert_equal '12300 thousand quids', number_to_human(12345000000, :units => gangster)
+
+ #Spaces are stripped from the resulting string
+ assert_equal '4', number_to_human(4, :units => {:unit => "", :ten => 'tens '})
+ assert_equal '4.5 tens', number_to_human(45, :units => {:unit => "", :ten => ' tens '})
end
def test_number_to_human_with_custom_format
@@ -286,7 +300,8 @@ class NumberHelperTest < ActionView::TestCase
assert number_to_percentage("asdf".html_safe).html_safe?
assert number_to_phone(1).html_safe?
- assert !number_to_phone("<script></script>").html_safe?
+ assert_equal "&lt;script&gt;&lt;/script&gt;", number_to_phone("<script></script>")
+ assert number_to_phone("<script></script>").html_safe?
assert number_to_phone("asdf".html_safe).html_safe?
assert number_with_delimiter(1).html_safe?
@@ -341,7 +356,7 @@ class NumberHelperTest < ActionView::TestCase
end
assert_raise InvalidNumberError do
- number_with_delimiter("x", :raise => true)
+ number_with_delimiter("x", :raise => true)
end
begin
number_with_delimiter("x", :raise => true)
@@ -350,7 +365,7 @@ class NumberHelperTest < ActionView::TestCase
end
assert_raise InvalidNumberError do
- number_to_phone("x", :raise => true)
+ number_to_phone("x", :raise => true)
end
begin
number_to_phone("x", :raise => true)
diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb
new file mode 100644
index 0000000000..fc127c24e9
--- /dev/null
+++ b/actionpack/test/template/output_safety_helper_test.rb
@@ -0,0 +1,30 @@
+require 'abstract_unit'
+require 'testing_sandbox'
+
+class OutputSafetyHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::OutputSafetyHelper
+ include TestingSandbox
+
+ def setup
+ @string = "hello"
+ end
+
+ test "raw returns the safe string" do
+ result = raw(@string)
+ assert_equal @string, result
+ assert result.html_safe?
+ end
+
+ test "raw handles nil values correctly" do
+ assert_equal "", raw(nil)
+ end
+
+ test "safe_join should html_escape any items, including the separator, if they are not html_safe" do
+ joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
+ assert_equal "<p>foo</p>&lt;br /&gt;&lt;p&gt;bar&lt;/p&gt;", joined
+
+ joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
+ assert_equal "<p>foo</p><br /><p>bar</p>", joined
+ end
+
+end \ No newline at end of file
diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb
index 036a44730c..a6aa848a00 100644
--- a/actionpack/test/template/prototype_helper_test.rb
+++ b/actionpack/test/template/prototype_helper_test.rb
@@ -71,7 +71,7 @@ class PrototypeHelperBaseTest < ActionView::TestCase
end
def create_generator
- block = Proc.new { |*args| yield *args if block_given? }
+ block = Proc.new { |*args| yield(*args) if block_given? }
JavaScriptGenerator.new self, &block
end
end
diff --git a/actionpack/test/template/raw_output_helper_test.rb b/actionpack/test/template/raw_output_helper_test.rb
deleted file mode 100644
index 598aa5b1d8..0000000000
--- a/actionpack/test/template/raw_output_helper_test.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'abstract_unit'
-require 'testing_sandbox'
-
-class RawOutputHelperTest < ActionView::TestCase
- tests ActionView::Helpers::RawOutputHelper
- include TestingSandbox
-
- def setup
- @string = "hello"
- end
-
- test "raw returns the safe string" do
- result = raw(@string)
- assert_equal @string, result
- assert result.html_safe?
- end
-
- test "raw handles nil values correctly" do
- assert_equal "", raw(nil)
- end
-end \ No newline at end of file
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 059dcedad8..dd86bfed04 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -69,8 +69,6 @@ module RenderTestCases
end
def test_render_update
- # TODO: You should not have to stub out template because template is self!
- @view.instance_variable_set(:@template, @view)
assert_equal 'alert("Hello, World!");', @view.render(:update) { |page| page.alert('Hello, World!') }
end
@@ -116,7 +114,7 @@ module RenderTestCases
end
def test_render_sub_template_with_errors
- @view.render(:file => "test/sub_template_raise")
+ @view.render(:template => "test/sub_template_raise")
flunk "Render did not raise Template::Error"
rescue ActionView::Template::Error => e
assert_match %r!method.*doesnt_exist!, e.message
@@ -125,15 +123,35 @@ module RenderTestCases
assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name
end
+ def test_render_file_with_errors
+ @view.render(:file => File.expand_path("test/_raise", FIXTURE_LOAD_PATH))
+ flunk "Render did not raise Template::Error"
+ rescue ActionView::Template::Error => e
+ 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
+ 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
@@ -191,6 +209,11 @@ module RenderTestCases
@view.formats = nil
end
+ def test_render_layout_with_block_and_other_partial_inside
+ render = @view.render(:layout => "test/layout_with_partial_and_yield.html.erb") { "Yield!" }
+ assert_equal "Before\npartial html\nYield!\nAfter\n", render
+ end
+
def test_render_inline
assert_equal "Hello, World!", @view.render(:inline => "Hello, World!")
end
@@ -208,6 +231,20 @@ module RenderTestCases
"@output_buffer << 'source: #{template.source.inspect}'\n"
end
+ WithViewHandler = lambda do |template, view|
+ %'"#{template.class} #{view.class}"'
+ 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_template_handler_with_view
+ ActionView::Template.register_template_handler :with_view, WithViewHandler
+ assert_equal 'ActionView::Template ActionView::Base', @view.render(:inline => "Hello, World!", :type => :with_view)
+ 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)
@@ -234,13 +271,49 @@ module RenderTestCases
@view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_inline_inside")
end
+ def test_render_with_layout_which_renders_another_partial
+ assert_equal %(partial html\nHello world!\n),
+ @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_partial_inside")
+ end
- # TODO: Move to deprecated_tests.rb
- def test_render_with_nested_layout_deprecated
- assert_deprecated do
- assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n),
- @view.render(:file => "test/deprecated_nested_layout.erb", :layout => "layouts/yield")
- 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_with_nested_layout
@@ -252,6 +325,11 @@ module RenderTestCases
assert_equal %(\n<title>title</title>\n\n),
@view.render(:file => "test/layout_render_file.erb")
end
+
+ def test_render_layout_with_object
+ assert_equal %(<title>David</title>),
+ @view.render(:file => "test/layout_render_object.erb")
+ end
end
class CachedViewRenderTest < ActiveSupport::TestCase
@@ -303,7 +381,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase
end
def test_render_utf8_template_with_incompatible_external_encoding
- with_external_encoding Encoding::SJIS do
+ with_external_encoding Encoding::SHIFT_JIS do
begin
result = @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield")
flunk 'Should have raised incompatible encoding error'
@@ -314,7 +392,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase
end
def test_render_utf8_template_with_partial_with_incompatible_encoding
- with_external_encoding Encoding::SJIS do
+ with_external_encoding Encoding::SHIFT_JIS do
begin
result = @view.render(:file => "test/utf8_magic_with_bare_partial.html.erb", :layouts => "layouts/yield")
flunk 'Should have raised incompatible encoding error'
@@ -325,10 +403,11 @@ class LazyViewRenderTest < ActiveSupport::TestCase
end
def with_external_encoding(encoding)
- old, Encoding.default_external = Encoding.default_external, encoding
+ old = Encoding.default_external
+ silence_warnings { Encoding.default_external = encoding }
yield
ensure
- Encoding.default_external = old
+ silence_warnings { Encoding.default_external = old }
end
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 0000000000..97b1bad055
--- /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/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb
index 507cdca8d0..60b466a9ff 100644
--- a/actionpack/test/template/tag_helper_test.rb
+++ b/actionpack/test/template/tag_helper_test.rb
@@ -11,8 +11,8 @@ class TagHelperTest < ActionView::TestCase
def test_tag_options
str = tag("p", "class" => "show", :class => "elsewhere")
- assert_match /class="show"/, str
- assert_match /class="elsewhere"/, str
+ assert_match(/class="show"/, str)
+ assert_match(/class="elsewhere"/, str)
end
def test_tag_options_rejects_nil_option
@@ -90,24 +90,31 @@ class TagHelperTest < ActionView::TestCase
def test_cdata_section
assert_equal "<![CDATA[<hello world>]]>", cdata_section("<hello world>")
end
-
+
def test_escape_once
assert_equal '1 &lt; 2 &amp; 3', escape_once('1 < 2 &amp; 3')
end
-
+
def test_tag_honors_html_safe_for_param_values
['1&amp;2', '1 &lt; 2', '&#8220;test&#8220;'].each do |escaped|
assert_equal %(<a href="#{escaped}" />), tag('a', :href => escaped.html_safe)
end
end
-
+
def test_skip_invalid_escaped_attributes
['&1;', '&#1dfa3;', '& #123;'].each do |escaped|
- assert_equal %(<a href="#{escaped.gsub /&/, '&amp;'}" />), tag('a', :href => escaped)
+ assert_equal %(<a href="#{escaped.gsub(/&/, '&amp;')}" />), tag('a', :href => escaped)
end
end
def test_disable_escaping
assert_equal '<a href="&amp;" />', tag('a', { :href => '&amp;' }, false, false)
end
+
+ def test_data_attributes
+ ['data', :data].each { |data|
+ assert_dom_equal '<a data-a-number="1" data-array="[1,2,3]" data-hash="{&quot;key&quot;:&quot;value&quot;}" data-string="hello" data-symbol="foo" />',
+ tag('a', { data => { :a_number => 1, :string => 'hello', :symbol => :foo, :array => [1, 2, 3], :hash => { :key => 'value'} } })
+ }
+ 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 0000000000..3a874082d9
--- /dev/null
+++ b/actionpack/test/template/template_error_test.rb
@@ -0,0 +1,13 @@
+require "abstract_unit"
+
+class TemplateErrorTest < ActiveSupport::TestCase
+ def test_provides_original_message
+ error = ActionView::Template::Error.new("test", {}, Exception.new("original"))
+ assert_equal "original", error.message
+ end
+
+ def test_provides_useful_inspect
+ error = ActionView::Template::Error.new("test", {}, Exception.new("original"))
+ assert_equal "#<ActionView::Template::Error: original>", error.inspect
+ end
+end
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
index 18e0e83ec3..3432a02c3c 100644
--- a/actionpack/test/template/template_test.rb
+++ b/actionpack/test/template/template_test.rb
@@ -1,18 +1,21 @@
require "abstract_unit"
-
-if "ruby".encoding_aware?
- # These are the normal settings that will be set up by Railties
- # TODO: Have these tests support other combinations of these values
- Encoding.default_internal = "UTF-8"
- Encoding.default_external = "UTF-8"
-end
+require "logger"
class TestERBTemplate < ActiveSupport::TestCase
- ERBHandler = ActionView::Template::Handlers::ERB
+ ERBHandler = ActionView::Template::Handlers::ERB.new
+
+ class LookupContext
+ def disable_cache
+ yield
+ end
+ end
class Context
+ attr_accessor :_template
+
def initialize
@output_buffer = "original"
+ @_virtual_path = nil
end
def hello
@@ -21,15 +24,18 @@ class TestERBTemplate < ActiveSupport::TestCase
def partial
ActionView::Template.new(
- "<%= @_virtual_path %>",
+ "<%= @_template.virtual_path %>",
"partial",
ERBHandler,
:virtual_path => "partial"
)
end
+ def lookup_context
+ @lookup_context ||= LookupContext.new
+ end
+
def logger
- require "logger"
Logger.new(STDERR)
end
@@ -38,16 +44,16 @@ class TestERBTemplate < ActiveSupport::TestCase
end
end
- def new_template(body = "<%= hello %>", handler = ERBHandler, details = {})
- ActionView::Template.new(body, "hello template", ERBHandler, {:virtual_path => "hello"})
+ def new_template(body = "<%= hello %>", details = {})
+ ActionView::Template.new(body, "hello template", ERBHandler, {:virtual_path => "hello"}.merge!(details))
end
def render(locals = {})
- @template.render(@obj, locals)
+ @template.render(@context, locals)
end
def setup
- @obj = Context.new
+ @context = Context.new
end
def test_basic_template
@@ -55,24 +61,96 @@ class TestERBTemplate < ActiveSupport::TestCase
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'm a local", render(:my_local => "I'm a local")
end
def test_restores_buffer
@template = new_template
assert_equal "Hello", render
- assert_equal "original", @obj.my_buffer
+ assert_equal "original", @context.my_buffer
end
def test_virtual_path
- @template = new_template("<%= @_virtual_path %>" \
+ @template = new_template("<%= @_template.virtual_path %>" \
"<%= partial.render(self, {}) %>" \
- "<%= @_virtual_path %>")
+ "<%= @_template.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_template_expire_sets_the_timestamp_to_1970
+ @template = new_template("Hello", :updated_at => Time.utc(2010))
+ assert_equal Time.utc(2010), @template.updated_at
+ @template.expire!
+ assert_equal Time.utc(1970), @template.updated_at
+ end
+
+ def test_template_rerender_renders_a_template_like_self
+ @template = new_template("Hello", :virtual_path => "test/foo_bar")
+ @context.expects(:render).with(:template => "test/foo_bar").returns("template")
+ assert_equal "template", @template.rerender(@context)
+ end
+
+ def test_template_rerender_renders_a_root_template_like_self
+ @template = new_template("Hello", :virtual_path => "foo_bar")
+ @context.expects(:render).with(:template => "foo_bar").returns("template")
+ assert_equal "template", @template.rerender(@context)
+ end
+
+ def test_template_rerender_renders_a_partial_like_self
+ @template = new_template("Hello", :virtual_path => "test/_foo_bar")
+ @context.expects(:render).with(:partial => "test/foo_bar").returns("partial")
+ assert_equal "partial", @template.rerender(@context)
+ end
+
+ def test_template_rerender_renders_a_root_partial_like_self
+ @template = new_template("Hello", :virtual_path => "_foo_bar")
+ @context.expects(:render).with(:partial => "foo_bar").returns("partial")
+ assert_equal "partial", @template.rerender(@context)
+ end
+
+ def test_rerender_raises_an_error_without_virtual_path
+ @template = new_template("Hello", :virtual_path => nil)
+ assert_raise RuntimeError do
+ @template.rerender(@context)
+ end
+ end
+
if "ruby".encoding_aware?
def test_resulting_string_is_utf8
@template = new_template
@@ -89,12 +167,11 @@ class TestERBTemplate < ActiveSupport::TestCase
# 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
- Encoding.default_external = "ISO-8859-1"
- @template = new_template("hello \xFCmlat")
- assert_equal Encoding::UTF_8, render.encoding
- assert_equal "hello \u{fc}mlat", render
- ensure
- Encoding.default_external = "UTF-8"
+ 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
@@ -108,14 +185,14 @@ class TestERBTemplate < ActiveSupport::TestCase
# inside Rails.
def test_lying_with_magic_comment
assert_raises(ActionView::Template::Error) do
- @template = new_template("# encoding: UTF-8\nhello \xFCmlat")
+ @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")
+ @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", :virtual_path => nil)
result = render
assert_equal Encoding::UTF_8, render.encoding
assert_equal "hello \u{fc}mlat", render
@@ -124,16 +201,17 @@ class TestERBTemplate < ActiveSupport::TestCase
def test_error_when_template_isnt_valid_utf8
assert_raises(ActionView::Template::Error, /\xFC/) do
- @template = new_template("hello \xFCmlat")
+ @template = new_template("hello \xFCmlat", :virtual_path => nil)
render
end
end
def with_external_encoding(encoding)
- old, Encoding.default_external = Encoding.default_external, encoding
+ old = Encoding.default_external
+ silence_warnings { Encoding.default_external = encoding }
yield
ensure
- Encoding.default_external = old
+ silence_warnings { Encoding.default_external = old }
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb
index a0c46f8a59..11c355dc6d 100644
--- a/actionpack/test/template/test_case_test.rb
+++ b/actionpack/test/template/test_case_test.rb
@@ -112,7 +112,59 @@ module ActionView
@controller.controller_path = 'test'
@customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')]
- assert_match /Hello: EloyHello: Manfred/, render(:partial => 'test/from_helper')
+ 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 AssignsTest < ActionView::TestCase
+ setup do
+ ActiveSupport::Deprecation.stubs(:warn)
+ end
+
+ test "_assigns delegates to user_defined_ivars" do
+ self.expects(:view_assigns)
+ _assigns
+ end
+
+ test "_assigns is deprecated" do
+ ActiveSupport::Deprecation.expects(:warn)
+ _assigns
+ 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.sub('@','').to_sym), "expected #{ivar} to be excluded from view_assigns"
+ end
end
end
@@ -172,7 +224,7 @@ module ActionView
test "is able to use named routes" do
with_routing do |set|
- set.draw { |map| resources :contents }
+ 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
@@ -180,7 +232,7 @@ module ActionView
test "named routes can be used from helper included in view" do
with_routing do |set|
- set.draw { |map| resources :contents }
+ set.draw { resources :contents }
_helpers.module_eval do
def render_from_helper
new_content_url
@@ -201,7 +253,7 @@ module ActionView
@controller.controller_path = "test"
@customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')]
- assert_match /Hello: EloyHello: Manfred/, render(:file => 'test/list')
+ 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
@@ -210,7 +262,7 @@ module ActionView
view
@customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')]
- assert_match /Hello: EloyHello: Manfred/, render(:file => 'test/list')
+ assert_match(/Hello: EloyHello: Manfred/, render(:file => 'test/list'))
end
end
@@ -253,4 +305,17 @@ module ActionView
end
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
index 68e790cf46..3d0bbba435 100644
--- a/actionpack/test/template/test_test.rb
+++ b/actionpack/test/template/test_test.rb
@@ -39,7 +39,7 @@ class PeopleHelperTest < ActionView::TestCase
with_test_route_set do
person = mock(:name => "David")
person.class.extend ActiveModel::Naming
- expects(:mocha_mock_path).with(person).returns("/people/1")
+ _routes.url_helpers.expects(:hash_for_mocha_mock_path).with(person).returns("/people/1")
assert_equal '<a href="/people/1">David</a>', link_to_person(person)
end
end
@@ -47,7 +47,7 @@ class PeopleHelperTest < ActionView::TestCase
private
def with_test_route_set
with_routing do |set|
- set.draw do |map|
+ set.draw do
match 'people', :to => 'people#index', :as => :people
end
yield
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index d22b9fe406..d0d4286393 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -1,4 +1,4 @@
-# encoding: us-ascii
+# encoding: utf-8
require 'abstract_unit'
require 'testing_sandbox'
@@ -99,7 +99,7 @@ class TextHelperTest < ActionView::TestCase
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 <strong class=\"highlight\">beautiful</strong> morning",
@@ -415,6 +415,12 @@ class TextHelperTest < ActionView::TestCase
link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/'
link10_result = generate_result(link10_raw)
assert_equal %(<p>#{link10_result} Link</p>), auto_link("<p>#{link10_raw} Link</p>")
+
+ link11_raw = 'http://asakusa.rubyist.net/'
+ link11_result = generate_result(link11_raw)
+ with_kcode 'u' do
+ assert_equal %(浅草.rbの公式サイトはこちら#{link11_result}), auto_link("浅草.rbの公式サイトはこちら#{link11_raw}")
+ end
end
def test_auto_link_should_sanitize_input_when_sanitize_option_is_not_false
@@ -430,7 +436,7 @@ class TextHelperTest < ActionView::TestCase
def test_auto_link_other_protocols
ftp_raw = 'ftp://example.com/file.txt'
assert_equal %(Download #{generate_result(ftp_raw)}), auto_link("Download #{ftp_raw}")
-
+
file_scheme = 'file:///home/username/RomeoAndJuliet.pdf'
z39_scheme = 'z39.50r://host:696/db'
chrome_scheme = 'chrome://package/section/path'
@@ -452,7 +458,7 @@ class TextHelperTest < ActionView::TestCase
assert_equal linked3, auto_link(linked3)
assert_equal linked4, auto_link(linked4)
assert_equal linked5, auto_link(linked5)
-
+
linked_email = %Q(<a href="mailto:david@loudthinking.com">Mail me</a>)
assert_equal linked_email, auto_link(linked_email)
end
@@ -491,13 +497,13 @@ class TextHelperTest < ActionView::TestCase
url = "http://api.rubyonrails.com/Foo.html"
email = "fantabulous@shiznadel.ic"
- assert_equal %(<p><a href="#{url}">#{url[0...7]}...</a><br /><a href="mailto:#{email}">#{email[0...7]}...</a><br /></p>), auto_link("<p>#{url}<br />#{email}<br /></p>") { |url| truncate(url, :length => 10) }
+ assert_equal %(<p><a href="#{url}">#{url[0...7]}...</a><br /><a href="mailto:#{email}">#{email[0...7]}...</a><br /></p>), auto_link("<p>#{url}<br />#{email}<br /></p>") { |_url| truncate(_url, :length => 10) }
end
-
+
def test_auto_link_with_block_with_html
pic = "http://example.com/pic.png"
url = "http://example.com/album?a&b=c"
-
+
assert_equal %(My pic: <a href="#{pic}"><img src="#{pic}" width="160px"></a> -- full album here #{generate_result(url)}), auto_link("My pic: #{pic} -- full album here #{url}") { |link|
if link =~ /\.(jpg|gif|png|bmp|tif)$/i
raw %(<img src="#{link}" width="160px">)
@@ -512,7 +518,7 @@ class TextHelperTest < ActionView::TestCase
auto_link("Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com.",
:link => :all, :html => { :class => "menu", :target => "_blank" })
end
-
+
def test_auto_link_with_multiple_trailing_punctuations
url = "http://youtube.com"
url_result = generate_result(url)
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index 1be418a206..9b5c6d127c 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -4,60 +4,78 @@ class TranslationHelperTest < ActiveSupport::TestCase
include ActionView::Helpers::TagHelper
include ActionView::Helpers::TranslationHelper
- attr_reader :request
+ attr_reader :request, :view
+
def setup
+ I18n.backend.store_translations(:en,
+ :translations => {
+ :templates => {
+ :found => { :foo => 'Foo' },
+ :array => { :foo => { :bar => 'Foo Bar' } }
+ },
+ :foo => 'Foo',
+ :hello => '<a>Hello World</a>',
+ :html => '<a>Hello World</a>',
+ :hello_html => '<a>Hello World</a>',
+ :array_html => %w(foo bar),
+ :array => %w(foo bar)
+ }
+ )
+ @view = ::ActionView::Base.new(ActionController::Base.view_paths, {})
end
-
- def test_delegates_to_i18n_setting_the_raise_option
- I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true).returns("")
+
+ 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">en, foo</span>'
- assert_equal expected, translate(:foo)
+ expected = '<span class="translation_missing" title="translation missing: en.translations.missing">Missing</span>'
+ assert_equal expected, translate(:"translations.missing")
+ 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)
end
def test_translation_returning_an_array
- I18n.expects(:translate).with(:foo, :raise => true).returns(["foo", "bar"])
- assert_equal ["foo", "bar"], translate(:foo)
+ expected = %w(foo bar)
+ assert_equal expected, translate(:"translations.array")
end
- def test_delegates_localize_to_i18n
- @time = Time.utc(2008, 7, 8, 12, 18, 38)
- I18n.expects(:localize).with(@time)
- localize @time
+ def test_finds_translation_scoped_by_partial
+ assert_equal 'Foo', view.render(:file => 'translations/templates/found').strip
end
-
- def test_scoping_by_partial
- I18n.expects(:translate).with("test.translation.helper", :raise => true).returns("helper")
- @view = ActionView::Base.new(ActionController::Base.view_paths, {})
- assert_equal "helper", @view.render(:file => "test/translation")
+
+ def test_finds_array_of_translations_scoped_by_partial
+ assert_equal 'Foo Bar', @view.render(:file => 'translations/templates/array').strip
end
- def test_scoping_by_partial_of_an_array
- I18n.expects(:translate).with("test.scoped_translation.foo.bar", :raise => true).returns(["foo", "bar"])
- @view = ActionView::Base.new(ActionController::Base.view_paths, {})
- assert_equal "foobar", @view.render(:file => "test/scoped_translation")
+ 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
- I18n.expects(:translate).with("hello", :raise => true).returns("Hello World")
- assert_equal false, translate("hello").html_safe?
+ assert_equal false, translate(:'translations.hello').html_safe?
end
def test_translate_marks_translations_named_html_as_safe_html
- I18n.expects(:translate).with("html", :raise => true).returns("<a>Hello World</a>")
- assert translate("html").html_safe?
+ assert translate(:'translations.html').html_safe?
end
def test_translate_marks_translations_with_a_html_suffix_as_safe_html
- I18n.expects(:translate).with("hello_html", :raise => true).returns("<a>Hello World</a>")
- assert translate("hello_html").html_safe?
+ assert translate(:'translations.hello_html').html_safe?
end
def test_translation_returning_an_array_ignores_html_suffix
- I18n.expects(:translate).with(:foo_html, :raise => true).returns(["foo", "bar"])
- assert_equal ["foo", "bar"], translate(:foo_html)
+ assert_equal ["foo", "bar"], translate(:'translations.array_html')
end
end
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index d59bbec4a9..fc330f7a73 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -9,7 +9,7 @@ class UrlHelperTest < ActiveSupport::TestCase
# or request.
#
# In those cases, we'll set up a simple mock
- attr_accessor :controller, :request
+ attr_accessor :controller, :request, :_template
routes = ActionDispatch::Routing::RouteSet.new
routes.draw do
@@ -20,17 +20,11 @@ class UrlHelperTest < ActiveSupport::TestCase
include routes.url_helpers
include ActionView::Helpers::UrlHelper
+ include ActionView::Helpers::JavaScriptHelper
include ActionDispatch::Assertions::DomAssertions
include ActionView::Context
include RenderERBUtils
- # self.default_url_options = {:host => "www.example.com"}
-
- # TODO: This shouldn't be needed (see template.rb:53)
- def assigns
- {}
- end
-
def hash_for(opts = [])
ActiveSupport::OrderedHash[*([:controller, "foo", :action, "bar"].concat(opts))]
end
@@ -57,6 +51,14 @@ class UrlHelperTest < ActiveSupport::TestCase
assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com")
end
+ def test_button_to_with_form_class
+ assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"custom-class\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :form_class => 'custom-class')
+ end
+
+ def test_button_to_with_form_class_escapes
+ assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"&lt;script&gt;evil_js&lt;/script&gt;\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :form_class => '<script>evil_js</script>')
+ end
+
def test_button_to_with_query
assert_dom_equal "<form method=\"post\" action=\"http://www.example.com/q1=v1&amp;q2=v2\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com/q1=v1&q2=v2")
end
@@ -76,6 +78,13 @@ class UrlHelperTest < ActiveSupport::TestCase
)
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", :disable_with => "Greeting...")
+ )
+ 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>",
@@ -83,6 +92,20 @@ class UrlHelperTest < ActiveSupport::TestCase
)
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, :disable_with => "Greeting...")
+ )
+ end
+
+ def test_button_to_with_remote_and_javascript_confirm_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...\" data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :remote => true, :confirm => "Are you sure?", :disable_with => "Greeting...")
+ )
+ 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>",
@@ -249,12 +272,7 @@ class UrlHelperTest < ActiveSupport::TestCase
assert_equal "<strong>Showing</strong>",
link_to_unless(true, "Showing", url_hash) { |name|
- "<strong>#{name}</strong>"
- }
-
- assert_equal "<strong>Showing</strong>",
- link_to_unless(true, "Showing", url_hash) { |name|
- "<strong>#{name}</strong>"
+ "<strong>#{name}</strong>".html_safe
}
assert_equal "test",
@@ -350,13 +368,13 @@ class UrlHelperTest < ActiveSupport::TestCase
def test_mail_to_with_javascript
snippet = mail_to("me@domain.com", "My email", :encode => "javascript")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", snippet
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet
assert snippet.html_safe?
end
def test_mail_to_with_javascript_unicode
snippet = mail_to("unicode@example.com", "únicode", :encode => "javascript")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%22%3e%c3%ba%6e%69%63%6f%64%65%3c%2f%61%3e%27%29%3b'))</script>", snippet
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%5c%22%3e%c3%ba%6e%69%63%6f%64%65%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet
assert snippet.html_safe
end
@@ -382,8 +400,8 @@ class UrlHelperTest < ActiveSupport::TestCase
assert_dom_equal "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)")
assert_dom_equal "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">My email</a>", mail_to("me@domain.com", "My email", :encode => "hex", :replace_at => "(at)")
assert_dom_equal "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#40;&#100;&#111;&#116;&#41;&#99;&#111;&#109;</a>", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)", :replace_dot => "(dot)")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%5c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
end
# TODO: button_to looks at this ... why?
@@ -401,7 +419,7 @@ end
class UrlHelperControllerTest < ActionController::TestCase
class UrlHelperController < ActionController::Base
- test_routes do |map|
+ test_routes do
match 'url_helper_controller_test/url_helper/show/:id',
:to => 'url_helper_controller_test/url_helper#show',
:as => :show
@@ -414,12 +432,15 @@ class UrlHelperControllerTest < ActionController::TestCase
:to => 'url_helper_controller_test/url_helper#show_named_route',
:as => :show_named_route
- map.connect ":controller/:action/:id"
- # match "/:controller(/:action(/:id))"
+ match "/:controller(/:action(/:id))"
match 'url_helper_controller_test/url_helper/normalize_recall_params',
:to => UrlHelperController.action(:normalize_recall),
:as => :normalize_recall_params
+
+ match '/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
@@ -455,6 +476,15 @@ class UrlHelperControllerTest < ActionController::TestCase
end
def rescue_action(e) raise e 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
@@ -514,6 +544,11 @@ class UrlHelperControllerTest < ActionController::TestCase
get :show, :name => '123'
assert_equal 'ok', @response.body
end
+
+ def test_url_helper_can_be_overriden
+ get :override_url_helper
+ assert_equal '/url_helper_controller_test/url_helper/override_url_helper/override', @response.body
+ end
end
class TasksController < ActionController::Base
@@ -555,24 +590,6 @@ class LinkToUnlessCurrentWithControllerTest < ActionController::TestCase
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
-
class Session
extend ActiveModel::Naming
include ActiveModel::Conversion
@@ -654,10 +671,10 @@ class PolymorphicControllerTest < ActionController::TestCase
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
diff --git a/activemodel/CHANGELOG b/activemodel/CHANGELOG
index 8374853231..3082c7186a 100644
--- a/activemodel/CHANGELOG
+++ b/activemodel/CHANGELOG
@@ -1,22 +1,28 @@
-*Rails 3.0.0 [release candidate] (July 26th, 2010)*
+*Rails 3.1.0 (unreleased)*
-* Added ActiveModel::MassAssignmentSecurity [Eric Chapweske, Josh Kalderimis]
+* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]
+* ActiveModel::AttributeMethods allows attributes to be defined on demand [Alexander Uvarov]
-*Rails 3.0.0 [beta 4] (June 8th, 2010)*
-* JSON supports a custom root option: to_json(:root => 'custom') #4515 [Jatinder Singh]
+*Rails 3.0.2 (unreleased)*
+
+* No changes
-*Rails 3.0.0 [beta 3] (April 13th, 2010)*
+*Rails 3.0.1 (October 15, 2010)*
-* No changes
+* No Changes, just a version bump.
-*Rails 3.0.0 [beta 2] (April 1st, 2010)*
+*Rails 3.0.0 (August 29, 2010)*
+
+* Added ActiveModel::MassAssignmentSecurity [Eric Chapweske, Josh Kalderimis]
+
+* JSON supports a custom root option: to_json(:root => 'custom') #4515 [Jatinder Singh]
* #new_record? and #destroyed? were removed from ActiveModel::Lint. Use
- persisted? instead. A model is persisted if it's not a new_record? and it was
+ persisted? instead. A model is persisted if it's not a new_record? and it was
not destroyed? [MG]
* Added validations reflection in ActiveModel::Validations [JV]
@@ -27,19 +33,15 @@
* #to_key was added to ActiveModel::Lint so we can generate DOM IDs for
AMo objects with composite keys [MG]
-
-*Rails 3.0.0 [beta 1] (February 4, 2010)*
-
* ActiveModel::Observer#add_observer!
It has a custom hook to define after_find that should really be in a
ActiveRecord::Observer subclass:
- def add_observer!(klass)
- klass.add_observer(self)
- klass.class_eval 'def after_find() end' unless
- klass.respond_to?(:after_find)
- end
+ def add_observer!(klass)
+ klass.add_observer(self)
+ klass.class_eval 'def after_find() end' unless klass.respond_to?(:after_find)
+ end
* Change the ActiveModel::Base.include_root_in_json default to true for Rails 3 [DHH]
diff --git a/activemodel/MIT-LICENSE b/activemodel/MIT-LICENSE
index a345a2419d..7ad1051066 100644
--- a/activemodel/MIT-LICENSE
+++ b/activemodel/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
index 89cacbcab4..b5b5edd52a 100644
--- a/activemodel/README.rdoc
+++ b/activemodel/README.rdoc
@@ -8,7 +8,7 @@ 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 exacly conform to the Active Record interface. This would result
+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. You can include functionality from the following
@@ -18,38 +18,38 @@ modules:
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_create_callbacks do
+ 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
@@ -66,38 +66,38 @@ modules:
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
+ errors.add(:name, "can not be nil") if name.nil?
end
-
+
def ErrorsPerson.human_attribute_name(attr, options = {})
"Name"
end
-
+
end
-
+
person.errors.full_messages
- # => ["Name Can not be nil"]
-
+ # => ["Name can not be nil"]
+
person.errors.full_messages
- # => ["Name Can not be nil"]
+ # => ["Name can not be nil"]
{Learn more}[link:classes/ActiveModel/Errors.html]
@@ -106,9 +106,9 @@ modules:
class NamedPerson
extend ActiveModel::Naming
end
-
- NamedPerson.model_name #=> "NamedPerson"
- NamedPerson.model_name.human #=> "Named person"
+
+ NamedPerson.model_name # => "NamedPerson"
+ NamedPerson.model_name.human # => "Named person"
{Learn more}[link:classes/ActiveModel/Naming.html]
@@ -117,19 +117,19 @@ modules:
ActiveModel::Observers allows your object to implement the Observer
pattern in a Rails App and take advantage of all the standard observer
functions.
-
+
{Learn more}[link:classes/ActiveModel/Observer.html]
* Making objects serializable
ActiveModel::Serialization provides a standard interface for your object
to provide +to_json+ or +to_xml+ serialization.
-
+
s = SerialPerson.new
s.serializable_hash # => {"name"=>nil}
s.to_json # => "{\"name\":null}"
s.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
+
{Learn more}[link:classes/ActiveModel/Serialization.html]
* Internationalization (i18n) support
@@ -137,10 +137,10 @@ modules:
class Person
extend ActiveModel::Translation
end
-
+
Person.human_attribute_name('my_attribute')
- #=> "My attribute"
-
+ # => "My attribute"
+
{Learn more}[link:classes/ActiveModel/Translation.html]
* Validation support
@@ -157,10 +157,10 @@ modules:
person = Person.new
person.first_name = 'zoolander'
- person.valid? #=> false
+ person.valid? # => false
{Learn more}[link:classes/ActiveModel/Validations.html]
-
+
* Custom validators
class Person
@@ -168,17 +168,17 @@ modules:
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.valid? # => false
+ p.errors.full_messages # => ["Name must exist"]
p.name = "Bob"
- p.valid? #=> true
+ p.valid? # => true
{Learn more}[link:classes/ActiveModel/Validator.html]
diff --git a/activemodel/Rakefile b/activemodel/Rakefile
index 3fffc0d021..0a10912695 100644..100755
--- a/activemodel/Rakefile
+++ b/activemodel/Rakefile
@@ -1,8 +1,5 @@
dir = File.dirname(__FILE__)
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
-
require 'rake/testtask'
task :default => :test
@@ -17,26 +14,11 @@ namespace :test do
task :isolated do
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
Dir.glob("#{dir}/test/**/*_test.rb").all? do |file|
- system(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file)
+ sh(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file)
end or raise "Failures"
end
end
-
-require 'rdoc/task'
-
-# Generate the RDoc documentation
-RDoc::Task.new do |rdoc|
- rdoc.rdoc_dir = "doc"
- rdoc.title = "Active Model"
- rdoc.options << '-f' << 'horo'
- rdoc.options << '--charset' << 'utf-8'
- rdoc.options << '--main' << 'README.rdoc'
- rdoc.rdoc_files.include("README.rdoc", "CHANGELOG")
- rdoc.rdoc_files.include("lib/**/*.rb")
-end
-
-
require 'rake/packagetask'
require 'rake/gempackagetask'
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
index c483ecbc3c..fec9c7ff8b 100644
--- a/activemodel/activemodel.gemspec
+++ b/activemodel/activemodel.gemspec
@@ -20,6 +20,7 @@ Gem::Specification.new do |s|
s.has_rdoc = true
s.add_dependency('activesupport', version)
- s.add_dependency('builder', '~> 2.1.2')
- s.add_dependency('i18n', '~> 0.4.1')
+ s.add_dependency('builder', '~> 3.0.0')
+ s.add_dependency('i18n', '~> 0.5.0')
+ s.add_dependency('bcrypt-ruby', '~> 2.1.4')
end
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index 5ed21a39c2..d0e2a6f39c 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -24,7 +24,7 @@
activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
require 'active_support'
-
+require 'active_model/version'
module ActiveModel
extend ActiveSupport::Autoload
@@ -33,7 +33,6 @@ module ActiveModel
autoload :BlockValidator, 'active_model/validator'
autoload :Callbacks
autoload :Conversion
- autoload :DeprecatedErrorMethods
autoload :Dirty
autoload :EachValidator, 'active_model/validator'
autoload :Errors
@@ -43,10 +42,10 @@ module ActiveModel
autoload :Naming
autoload :Observer, 'active_model/observing'
autoload :Observing
+ autoload :SecurePassword
autoload :Serialization
autoload :TestCase
autoload :Translation
- autoload :VERSION
autoload :Validations
autoload :Validator
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index a43436e008..be55581c66 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -1,5 +1,5 @@
require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/class/inheritable_attributes'
+require 'active_support/core_ext/class/attribute'
module ActiveModel
class MissingAttributeError < NoMethodError
@@ -9,46 +9,46 @@ module ActiveModel
# <tt>ActiveModel::AttributeMethods</tt> provides a way to add prefixes and suffixes
# to your methods as well as handling the creation of Active Record like class methods
# such as +table_name+.
- #
+ #
# The requirements to implement ActiveModel::AttributeMethods are to:
#
# * <tt>include ActiveModel::AttributeMethods</tt> in your object
- # * Call each Attribute Method module method you want to add, such as
+ # * Call each Attribute Method module method you want to add, such as
# attribute_method_suffix or attribute_method_prefix
# * Call <tt>define_attribute_methods</tt> after the other methods are
# called.
# * Define the various generic +_attribute+ methods that you have declared
- #
+ #
# 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
- #
+ #
# 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
#
- # Notice that whenever you include ActiveModel::AttributeMethods in your class,
- # it requires you to implement a <tt>attributes</tt> methods which returns a hash
- # with each attribute name in your model as hash key and the attribute value as
+ # Note that whenever you include ActiveModel::AttributeMethods in your class,
+ # it requires you to implement an <tt>attributes</tt> 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.
@@ -56,35 +56,40 @@ module ActiveModel
module AttributeMethods
extend ActiveSupport::Concern
+ included do
+ class_attribute :attribute_method_matchers, :instance_writer => false
+ self.attribute_method_matchers = []
+ end
+
module ClassMethods
- # Defines an "attribute" method (like +inheritance_column+ or +table_name+).
- # A new (class) method will be created with the given name. If a value is
- # specified, the new method will return that value (as a string).
- # Otherwise, the given block will be used to compute the value of the
+ # Defines an "attribute" method (like +inheritance_column+ or +table_name+).
+ # A new (class) method will be created with the given name. If a value is
+ # specified, the new method will return that value (as a string).
+ # Otherwise, the given block will be used to compute the value of the
# method.
#
# The original method will be aliased, with the new name being prefixed
- # with "original_". This allows the new method to access the original
+ # with "original_". This allows the new method to access the original
# value.
#
# Example:
#
# class Person
- #
+ #
# include ActiveModel::AttributeMethods
- #
+ #
# cattr_accessor :primary_key
# cattr_accessor :inheritance_column
- #
+ #
# define_attr_method :primary_key, "sysid"
# define_attr_method( :inheritance_column ) do
# original_inheritance_column + "_id"
# end
- #
+ #
# end
- #
+ #
# Provides you with:
- #
+ #
# AttributePerson.primary_key
# # => "sysid"
# AttributePerson.inheritance_column = 'address'
@@ -93,19 +98,22 @@ module ActiveModel
def define_attr_method(name, value=nil, &block)
sing = singleton_class
sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
- if method_defined?(:original_#{name})
- undef :original_#{name}
+ if method_defined?('original_#{name}')
+ undef :'original_#{name}'
end
- alias_method :original_#{name}, :#{name}
+ alias_method :'original_#{name}', :'#{name}'
eorb
if block_given?
sing.send :define_method, name, &block
else
- # use eval instead of a block to work around a memory leak in dev
- # mode in fcgi
- sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
- def #{name}; #{value.to_s.inspect}; end
- eorb
+ if name =~ /^[a-zA-Z_]\w*[!?=]?$/
+ sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
+ def #{name}; #{value.nil? ? 'nil' : value.to_s.inspect}; end
+ eorb
+ else
+ value = value.to_s if value
+ sing.send(:define_method, name) { value }
+ end
end
end
@@ -118,20 +126,20 @@ module ActiveModel
#
# #{prefix}attribute(#{attr}, *args, &block)
#
- # An instance method <tt>#{prefix}attribute</tt> must exist and accept
+ # An instance method <tt>#{prefix}attribute</tt> must exist and accept
# at least the +attr+ argument.
#
# For example:
#
# 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
@@ -143,7 +151,7 @@ module ActiveModel
# person.clear_name
# person.name # => nil
def attribute_method_prefix(*prefixes)
- attribute_method_matchers.concat(prefixes.map { |prefix| AttributeMethodMatcher.new :prefix => prefix })
+ self.attribute_method_matchers += prefixes.map { |prefix| AttributeMethodMatcher.new :prefix => prefix }
undefine_attribute_methods
end
@@ -162,14 +170,14 @@ module ActiveModel
# For example:
#
# 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
@@ -180,7 +188,7 @@ module ActiveModel
# person.name # => "Bob"
# person.name_short? # => true
def attribute_method_suffix(*suffixes)
- attribute_method_matchers.concat(suffixes.map { |suffix| AttributeMethodMatcher.new :suffix => suffix })
+ self.attribute_method_matchers += suffixes.map { |suffix| AttributeMethodMatcher.new :suffix => suffix }
undefine_attribute_methods
end
@@ -200,14 +208,14 @@ module ActiveModel
# For example:
#
# 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
@@ -218,29 +226,27 @@ module ActiveModel
# person.reset_name_to_default!
# person.name # => 'Gemma'
def attribute_method_affix(*affixes)
- attribute_method_matchers.concat(affixes.map { |affix| AttributeMethodMatcher.new :prefix => affix[:prefix], :suffix => affix[:suffix] })
+ self.attribute_method_matchers += affixes.map { |affix| AttributeMethodMatcher.new :prefix => affix[:prefix], :suffix => affix[:suffix] }
undefine_attribute_methods
end
def alias_attribute(new_name, old_name)
attribute_method_matchers.each do |matcher|
- module_eval <<-STR, __FILE__, __LINE__ + 1
- def #{matcher.method_name(new_name)}(*args)
- send(:#{matcher.method_name(old_name)}, *args)
- end
- STR
+ define_method(matcher.method_name(new_name)) do |*args|
+ send(matcher.method_name(old_name), *args)
+ end
end
end
- # Declares a the attributes that should be prefixed and suffixed by
+ # Declares the attributes that should be prefixed and suffixed by
# ActiveModel::AttributeMethods.
- #
+ #
# To use, pass in an array of attribute names (as strings or symbols),
# 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_'
@@ -251,36 +257,36 @@ module ActiveModel
# define_attribute_methods [:name, :age, :address]
#
# private
- #
+ #
# def clear_attribute(attr)
# ...
# end
# end
def define_attribute_methods(attr_names)
- return if attribute_methods_generated?
- attr_names.each do |attr_name|
- attribute_method_matchers.each do |matcher|
- unless instance_method_already_implemented?(matcher.method_name(attr_name))
- generate_method = "define_method_#{matcher.prefix}attribute#{matcher.suffix}"
+ attr_names.each { |attr_name| define_attribute_method(attr_name) }
+ end
- if respond_to?(generate_method)
- send(generate_method, attr_name)
- else
- method_name = matcher.method_name(attr_name)
+ def define_attribute_method(attr_name)
+ attribute_method_matchers.each do |matcher|
+ unless instance_method_already_implemented?(matcher.method_name(attr_name))
+ generate_method = "define_method_#{matcher.prefix}attribute#{matcher.suffix}"
+
+ if respond_to?(generate_method)
+ send(generate_method, attr_name)
+ else
+ method_name = matcher.method_name(attr_name)
- generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
- if method_defined?(:#{method_name})
- undef :#{method_name}
- end
- def #{method_name}(*args)
- send(:#{matcher.method_missing_target}, '#{attr_name}', *args)
- end
- STR
- end
+ generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
+ if method_defined?('#{method_name}')
+ undef :'#{method_name}'
+ end
+ define_method('#{method_name}') do |*args|
+ send('#{matcher.method_missing_target}', '#{attr_name}', *args)
+ end
+ STR
end
end
end
- @attribute_methods_generated = true
end
# Removes all the previously dynamically defined methods from the class
@@ -288,7 +294,6 @@ module ActiveModel
generated_attribute_methods.module_eval do
instance_methods.each { |m| undef_method(m) }
end
- @attribute_methods_generated = nil
end
# Returns true if the attribute methods defined have been generated.
@@ -300,11 +305,6 @@ module ActiveModel
end
end
- # Returns true if the attribute methods defined have been generated.
- def attribute_methods_generated?
- @attribute_methods_generated ||= nil
- end
-
protected
def instance_method_already_implemented?(method_name)
method_defined?(method_name)
@@ -312,7 +312,7 @@ module ActiveModel
private
class AttributeMethodMatcher
- attr_reader :prefix, :suffix
+ attr_reader :prefix, :suffix, :method_missing_target
AttributeMethodMatch = Struct.new(:target, :attr_name)
@@ -320,40 +320,34 @@ module ActiveModel
options.symbolize_keys!
@prefix, @suffix = options[:prefix] || '', options[:suffix] || ''
@regex = /^(#{Regexp.escape(@prefix)})(.+?)(#{Regexp.escape(@suffix)})$/
+ @method_missing_target = "#{@prefix}attribute#{@suffix}"
+ @method_name = "#{prefix}%s#{suffix}"
end
def match(method_name)
- if matchdata = @regex.match(method_name)
- AttributeMethodMatch.new(method_missing_target, matchdata[2])
+ if @regex =~ method_name
+ AttributeMethodMatch.new(method_missing_target, $2)
else
nil
end
end
def method_name(attr_name)
- "#{prefix}#{attr_name}#{suffix}"
- end
-
- def method_missing_target
- :"#{prefix}attribute#{suffix}"
+ @method_name % attr_name
end
end
-
- def attribute_method_matchers #:nodoc:
- read_inheritable_attribute(:attribute_method_matchers) || write_inheritable_attribute(:attribute_method_matchers, [])
- end
end
- # Allows access to the object attributes, which are held in the
- # <tt>@attributes</tt> hash, as though they were first-class methods. So a
- # Person class with a name attribute can use Person#name and Person#name=
+ # Allows access to the object attributes, which are held in the
+ # <tt>@attributes</tt> hash, as though they were first-class methods. So a
+ # Person class with a name attribute can use Person#name and Person#name=
# and never directly use the attributes hash -- except for multiple assigns
- # with ActiveRecord#attributes=. A Milestone class can also ask
- # Milestone#completed? to test that the completed attribute is not +nil+
+ # with ActiveRecord#attributes=. A Milestone class can also ask
+ # Milestone#completed? to test that the completed attribute is not +nil+
# or 0.
#
- # It's also possible to instantiate related objects, so a Client class
- # belonging to the clients table with a +master_id+ foreign key can
+ # It's also possible to instantiate related objects, so a Client class
+ # belonging to the clients table with a +master_id+ foreign key can
# instantiate master through Client#master.
def method_missing(method_id, *args, &block)
method_name = method_id.to_s
@@ -390,7 +384,7 @@ module ActiveModel
# Returns a struct representing the matching attribute method.
# The struct's attributes are prefix, base and suffix.
def match_attribute_method?(method_name)
- self.class.send(:attribute_method_matchers).each do |method|
+ self.class.attribute_method_matchers.each do |method|
if (match = method.match(method_name)) && attribute_method?(match.attr_name)
return match
end
@@ -401,7 +395,7 @@ module ActiveModel
# prevent method_missing from calling private methods with #send
def guard_private_attribute_method!(method_name, args)
if self.class.private_method_defined?(method_name)
- raise NoMethodError.new("Attempt to call private method", method_name, args)
+ raise NoMethodError.new("Attempt to call private method `#{method_name}'", method_name, args)
end
end
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
index 8c10c54b54..2a1f51a9a7 100644
--- a/activemodel/lib/active_model/callbacks.rb
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -3,49 +3,46 @@ require 'active_support/callbacks'
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 :create and :update methods. To implement, you need to wrap the methods
+ # both the :create and :update 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_create_callbacks do
+ # run_callbacks :create do
# # Your create action methods here
# end
# end
- #
- # The _run_<method_name>_callbacks methods are dynamically created when you extend
- # the <tt>ActiveModel::Callbacks</tt> module.
- #
+ #
# Then in your class, you can use the +before_create+, +after_create+ and +around_create+
# methods, just as you would in an Active Record module.
- #
+ #
# before_create :action_before_create
- #
+ #
# def action_before_create
# # Your code here
# end
- #
- # You can choose not to have all three callbacks by passing a hash to the
+ #
+ # 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
@@ -56,50 +53,53 @@ module ActiveModel
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 :only option,
+ # you want to overwrite a default. Besides that, it also accepts an :only 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", :scope => [:kind, :name] }.merge(options)
+ options = {
+ :terminator => "result == false",
+ :scope => [:kind, :name],
+ :only => [:before, :around, :after]
+ }.merge(options)
- types = Array.wrap(options.delete(:only))
- types = [:before, :around, :after] if types.empty?
+ types = Array.wrap(options.delete(:only))
callbacks.each do |callback|
define_callbacks(callback, options)
types.each do |type|
- send(:"_define_#{type}_model_callback", self, callback)
+ send("_define_#{type}_model_callback", self, callback)
end
end
end
diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb
index d2bd160dc7..e3992e842a 100644
--- a/activemodel/lib/active_model/conversion.rb
+++ b/activemodel/lib/active_model/conversion.rb
@@ -3,8 +3,6 @@ module ActiveModel
#
# Handles default conversions: to_model, to_key and to_param.
#
- # == Example
- #
# Let's take for example this non persisted object.
#
# class ContactMessage
@@ -22,19 +20,22 @@ module ActiveModel
# cm.to_param # => nil
#
module Conversion
- # If your object is already designed to implement all of the Active Model
- # you can use the default to_model implementation, which simply returns
+ # If your object is already designed to implement all of the Active Model
+ # you can use the default to_model implementation, which simply returns
# self.
- #
- # 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
+ #
+ # 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 (primary) key attributes or nil if
- # persisted? is false
+ # Returns an Enumerable of all key attributes if any is set, regardless
+ # if the object is persisted or not.
+ #
+ # Note the default implementation uses persisted? just because all objects
+ # in Ruby 1.8.x responds to :id.
def to_key
persisted? ? [id] : nil
end
@@ -42,7 +43,7 @@ module ActiveModel
# Returns a string representing the object's key suitable for use in URLs,
# or nil if persisted? is false
def to_param
- to_key ? to_key.join('-') : nil
+ persisted? ? to_key.join('-') : nil
end
end
end
diff --git a/activemodel/lib/active_model/deprecated_error_methods.rb b/activemodel/lib/active_model/deprecated_error_methods.rb
deleted file mode 100644
index adc50773d9..0000000000
--- a/activemodel/lib/active_model/deprecated_error_methods.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-module ActiveModel
- module DeprecatedErrorMethods
- def on(attribute)
- message = "Errors#on have been deprecated, use Errors#[] instead.\n"
- message << "Also note that the behaviour of Errors#[] has changed. Errors#[] now always returns an Array. An empty Array is "
- message << "returned when there are no errors on the specified attribute."
- ActiveSupport::Deprecation.warn(message)
-
- errors = self[attribute]
- errors.size < 2 ? errors.first : errors
- end
-
- def on_base
- ActiveSupport::Deprecation.warn "Errors#on_base have been deprecated, use Errors#[:base] instead"
- ActiveSupport::Deprecation.silence { on(:base) }
- end
-
- def add_to_base(msg)
- ActiveSupport::Deprecation.warn "Errors#add_to_base(msg) has been deprecated, use Errors#add(:base, msg) instead"
- self[:base] << msg
- end
-
- def invalid?(attribute)
- ActiveSupport::Deprecation.warn "Errors#invalid?(attribute) has been deprecated, use Errors#[attribute].any? instead"
- self[attribute].any?
- end
-
- def each_full
- ActiveSupport::Deprecation.warn "Errors#each_full has been deprecated, use Errors#to_a.each instead"
- to_a.each { |error| yield error }
- end
- end
-end
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index 2516377afd..a479795d51 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -1,53 +1,52 @@
require 'active_model/attribute_methods'
-require 'active_support/concern'
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
+ # Provides a way to track changes in your object in the same way as
# Active Record does.
- #
+ #
# The requirements to implement ActiveModel::Dirty are to:
#
# * <tt>include ActiveModel::Dirty</tt> in your object
- # * Call <tt>define_attribute_methods</tt> passing each method you want to
+ # * 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
+ # * 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
+ #
+ # 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
- #
+ #
# == Examples:
#
# A newly instantiated object is unchanged:
@@ -79,7 +78,7 @@ module ActiveModel
# 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
+ # to mark that the attribute is changing. Otherwise ActiveModel can't track changes to
# in-place attributes.
#
# person.name_will_change!
@@ -115,7 +114,7 @@ module ActiveModel
# person.name = 'bob'
# person.changes # => { 'name' => ['bill', 'bob'] }
def changes
- changed.inject(HashWithIndifferentAccess.new){ |h, attr| h[attr] = attribute_change(attr); h }
+ HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
end
# Map of attributes that were changed when the model was saved.
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 272ddb1554..c2f0228785 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -12,77 +12,96 @@ module ActiveModel
#
# Provides a modified +OrderedHash+ 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::Translations
# 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
# p.validate! # => ["can not be nil"]
# p.errors.full_messages # => ["name can not be nil"]
# # etc..
- class Errors < ActiveSupport::OrderedHash
- include DeprecatedErrorMethods
+ class Errors
+ include Enumerable
CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank]
+ attr_reader :messages
+
# Pass in the instance of the object that is using the errors object.
- #
+ #
# class Person
# def initialize
# @errors = ActiveModel::Errors.new(self)
# end
# end
def initialize(base)
- @base = base
- super()
+ @base = base
+ @messages = ActiveSupport::OrderedHash.new
+ end
+
+ # Clear the messages
+ def clear
+ messages.clear
+ end
+
+ # Do the error messages include an error with key +error+?
+ def include?(error)
+ messages.include? error
+ end
+
+ # Get messages for +key+
+ def get(key)
+ messages[key]
end
- alias_method :get, :[]
- alias_method :set, :[]=
+ # Set messages for +key+ to +value+
+ def set(key, value)
+ messages[key] = value
+ end
- # When passed a symbol or a name of a method, returns an array of errors
+ # When passed a symbol or a name of a method, returns an array of errors
# for the method.
- #
+ #
# p.errors[:name] # => ["can not be nil"]
# p.errors['name'] # => ["can not be nil"]
def [](attribute)
@@ -90,7 +109,7 @@ module ActiveModel
end
# Adds to the supplied attribute the supplied error message.
- #
+ #
# p.errors[:name] = "must be set"
# p.errors[:name] # => ['must be set']
def []=(attribute, error)
@@ -100,25 +119,25 @@ module ActiveModel
# 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.
- #
+ #
# p.errors.add(:name, "can't be blank")
# p.errors.each do |attribute, errors_array|
# # Will yield :name and "can't be blank"
# end
- #
+ #
# p.errors.add(:name, "must be specified")
# p.errors.each do |attribute, errors_array|
# # Will yield :name and "can't be blank"
# # then yield :name and "must be specified"
# end
def each
- each_key do |attribute|
+ messages.each_key do |attribute|
self[attribute].each { |error| yield attribute, error }
end
end
# Returns the number of error messages.
- #
+ #
# p.errors.add(:name, "can't be blank")
# p.errors.size # => 1
# p.errors.add(:name, "must be specified")
@@ -127,8 +146,18 @@ module ActiveModel
values.flatten.size
end
+ # Returns all message values
+ def values
+ messages.values
+ end
+
+ # Returns all message keys
+ def keys
+ messages.keys
+ end
+
# Returns an array of error messages, with the attribute name included
- #
+ #
# p.errors.add(:name, "can't be blank")
# p.errors.add(:name, "must be specified")
# p.errors.to_a # => ["name can't be blank", "name must be specified"]
@@ -149,9 +178,9 @@ module ActiveModel
def empty?
all? { |k, v| v && v.empty? }
end
-
+ alias_method :blank?, :empty?
# Returns an xml formatted representation of the Errors hash.
- #
+ #
# p.errors.add(:name, "can't be blank")
# p.errors.add(:name, "must be specified")
# p.errors.to_xml
@@ -167,14 +196,18 @@ module ActiveModel
# Returns an ActiveSupport::OrderedHash that can be used as the JSON representation for this object.
def as_json(options=nil)
- self
+ to_hash
+ end
+
+ def to_hash
+ messages.dup
end
# Adds +message+ to the error messages on +attribute+, which will be returned on a call to
# <tt>on(attribute)</tt> for the same attribute. More than one error can be added to the same
# +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
# If no +message+ is supplied, <tt>:invalid</tt> is assumed.
- #
+ #
# If +message+ is a symbol, it will be translated using the appropriate scope (see +translate_error+).
# If +message+ is a proc, it will be called, allowing for things like <tt>Time.now</tt> to be used within an error.
def add(attribute, message = nil, options = {})
@@ -191,13 +224,6 @@ module ActiveModel
# Will add an error message to each of the attributes in +attributes+ that is empty.
def add_on_empty(attributes, options = {})
- if options && !options.is_a?(Hash)
- options = { :message => options }
- ActiveSupport::Deprecation.warn \
- "ActiveModel::Errors#add_on_empty(attributes, custom_message) has been deprecated.\n" +
- "Instead of passing a custom_message pass an options Hash { :message => custom_message }."
- end
-
[attributes].flatten.each do |attribute|
value = @base.send(:read_attribute_for_validation, attribute)
is_empty = value.respond_to?(:empty?) ? value.empty? : false
@@ -207,13 +233,6 @@ module ActiveModel
# Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
def add_on_blank(attributes, options = {})
- if options && !options.is_a?(Hash)
- options = { :message => options }
- ActiveSupport::Deprecation.warn \
- "ActiveModel::Errors#add_on_blank(attributes, custom_message) has been deprecated.\n" +
- "Instead of passing a custom_message pass an options Hash { :message => custom_message }."
- end
-
[attributes].flatten.each do |attribute|
value = @base.send(:read_attribute_for_validation, attribute)
add(attribute, :blank, options) if value.blank?
@@ -231,41 +250,35 @@ module ActiveModel
# company.errors.full_messages # =>
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
def full_messages
- full_messages = []
-
- each do |attribute, messages|
- messages = Array.wrap(messages)
- next if messages.empty?
-
+ map { |attribute, message|
if attribute == :base
- messages.each {|m| full_messages << m }
+ message
else
attr_name = attribute.to_s.gsub('.', '_').humanize
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
- options = { :default => "%{attribute} %{message}", :attribute => attr_name }
- messages.each do |m|
- full_messages << I18n.t(:"errors.format", options.merge(:message => m))
- end
+ I18n.t(:"errors.format", {
+ :default => "%{attribute} %{message}",
+ :attribute => attr_name,
+ :message => message
+ })
end
- end
-
- full_messages
+ }
end
- # Translates an error message in its default scope
+ # 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
+ # 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+,
+ # <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:
#
# <ol>
@@ -281,13 +294,6 @@ module ActiveModel
def generate_message(attribute, type = :invalid, options = {})
type = options.delete(:message) if options[:message].is_a?(Symbol)
- if options[:default]
- ActiveSupport::Deprecation.warn \
- "ActiveModel::Errors#generate_message(attributes, custom_message) has been deprecated.\n" +
- "Use ActiveModel::Errors#generate_message(attributes, :message => 'your message') instead."
- options[:message] = options.delete(:default)
- end
-
defaults = @base.class.lookup_ancestors.map do |klass|
[ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.underscore}.attributes.#{attribute}.#{type}",
:"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.underscore}.#{type}" ]
diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb
index fe650053d9..b71ef4b22e 100644
--- a/activemodel/lib/active_model/lint.rb
+++ b/activemodel/lib/active_model/lint.rb
@@ -1,19 +1,19 @@
-# == 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.
-#
-# These tests do not attempt to determine the semantic correctness of the
-# returned values. For instance, you could implement valid? 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 to_model. It is perfectly fine for to_model to return self.
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.
+ #
+ # These tests do not attempt to determine the semantic correctness of the
+ # returned values. For instance, you could implement valid? 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 to_model. It is perfectly fine for to_model to return self.
module Tests
# == Responds to <tt>to_key</tt>
@@ -23,7 +23,7 @@ module ActiveModel
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?
+ assert model.to_key.nil?, "to_key should return nil when `persisted?` returns false"
end
# == Responds to <tt>to_param</tt>
@@ -38,8 +38,9 @@ module ActiveModel
# not persisted?, then to_param 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?
+ assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false"
end
# == Responds to <tt>valid?</tt>
@@ -79,7 +80,7 @@ module ActiveModel
end
# == Errors Testing
- #
+ #
# Returns an object that has :[] and :full_messages defined on it. See below
# for more details.
#
diff --git a/activemodel/lib/active_model/mass_assignment_security.rb b/activemodel/lib/active_model/mass_assignment_security.rb
index 66cd9fdde6..be48415739 100644
--- a/activemodel/lib/active_model/mass_assignment_security.rb
+++ b/activemodel/lib/active_model/mass_assignment_security.rb
@@ -20,32 +20,32 @@ module ActiveModel
# For example, a logged in user may need to assign additional attributes depending
# on their role:
#
- # class AccountsController < ApplicationController
- # include ActiveModel::MassAssignmentSecurity
+ # class AccountsController < ApplicationController
+ # include ActiveModel::MassAssignmentSecurity
#
- # attr_accessible :first_name, :last_name
+ # attr_accessible :first_name, :last_name
#
- # def self.admin_accessible_attributes
- # accessible_attributes + [ :plan_id ]
- # end
+ # def self.admin_accessible_attributes
+ # accessible_attributes + [ :plan_id ]
+ # end
#
- # def update
- # ...
- # @account.update_attributes(account_params)
- # ...
- # end
+ # def update
+ # ...
+ # @account.update_attributes(account_params)
+ # ...
+ # end
#
- # protected
+ # protected
#
- # def account_params
- # sanitize_for_mass_assignment(params[:account])
- # end
+ # def account_params
+ # sanitize_for_mass_assignment(params[:account])
+ # end
#
- # def mass_assignment_authorizer
- # admin ? admin_accessible_attributes : super
- # end
+ # def mass_assignment_authorizer
+ # admin ? admin_accessible_attributes : super
+ # end
#
- # end
+ # end
#
module ClassMethods
# Attributes named in this macro are protected from mass-assignment
@@ -54,9 +54,7 @@ module ActiveModel
# Mass-assignment to these attributes will simply be ignored, to assign
# to them you can use direct writer methods. This is meant to protect
# sensitive attributes from being overwritten by malicious users
- # tampering with URLs or forms.
- #
- # == Example
+ # tampering with URLs or forms. Example:
#
# class Customer
# include ActiveModel::MassAssignmentSecurity
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
index b74d669f0a..eb9b847509 100644
--- a/activemodel/lib/active_model/naming.rb
+++ b/activemodel/lib/active_model/naming.rb
@@ -1,19 +1,25 @@
require 'active_support/inflector'
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/module/introspection'
module ActiveModel
class Name < String
- attr_reader :singular, :plural, :element, :collection, :partial_path
+ attr_reader :singular, :plural, :element, :collection, :partial_path, :route_key, :param_key
alias_method :cache_key, :collection
- def initialize(klass)
+ def initialize(klass, namespace = nil)
super(klass.name)
+ @unnamespaced = self.sub(/^#{namespace.name}::/, '') if namespace
+
@klass = klass
- @singular = ActiveSupport::Inflector.underscore(self).tr('/', '_').freeze
+ @singular = _singularize(self).freeze
@plural = ActiveSupport::Inflector.pluralize(@singular).freeze
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self)).freeze
@human = ActiveSupport::Inflector.humanize(@element).freeze
@collection = ActiveSupport::Inflector.tableize(self).freeze
@partial_path = "#{@collection}/#{@element}".freeze
+ @param_key = (namespace ? _singularize(@unnamespaced) : @singular).freeze
+ @route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural).freeze
end
# Transform the model name into a more humane format, using I18n. By default,
@@ -30,35 +36,43 @@ module ActiveModel
klass.model_name.underscore.to_sym
end
- defaults << options.delete(:default) if options[:default]
+ defaults << options[:default] if options[:default]
defaults << @human
- options.reverse_merge! :scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults
+ options = {:scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults}.merge(options.except(:default))
I18n.translate(defaults.shift, options)
end
+
+ private
+ def _singularize(str)
+ ActiveSupport::Inflector.underscore(str).tr('/', '_')
+ 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"
- #
+ #
# Providing the functionality that ActiveModel::Naming provides in your object
# is required to pass the Active Model Lint test. So either extending the provided
- # method below, or rolling your own is required..
+ # method below, or rolling your own is required.
module Naming
# Returns an ActiveModel::Name object for module. It can be
# used to retrieve all kinds of naming-related information.
def model_name
- @_model_name ||= ActiveModel::Name.new(self)
+ @_model_name ||= begin
+ namespace = self.parents.detect { |n| n.respond_to?(:_railtie) }
+ ActiveModel::Name.new(self, namespace)
+ end
end
# Returns the plural class name of a record or class. Examples:
@@ -85,10 +99,38 @@ module ActiveModel
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.route_key(Blog::Post) #=> posts
+ #
+ # For shared engine:
+ # ActiveModel::Naming.route_key(Blog::Post) #=> blog_posts
+ 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
+
private
def self.model_name_from_record_or_class(record_or_class)
- (record_or_class.is_a?(Class) ? record_or_class : record_or_class.class).model_name
+ (record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
+ end
+
+ def self.convert_to_model(object)
+ object.respond_to?(:to_model) ? object.to_model : object
end
end
-
+
end
diff --git a/activemodel/lib/active_model/observing.rb b/activemodel/lib/active_model/observing.rb
index c6a79acf81..ef36f80bec 100644
--- a/activemodel/lib/active_model/observing.rb
+++ b/activemodel/lib/active_model/observing.rb
@@ -10,19 +10,23 @@ module ActiveModel
module ClassMethods
# == Active Model Observers Activation
- #
+ #
# Activates the observers assigned. Examples:
#
+ # class ORM
+ # include ActiveModel::Observing
+ # end
+ #
# # Calls PersonObserver.instance
- # ActiveRecord::Base.observers = :person_observer
+ # ORM.observers = :person_observer
#
# # Calls Cacher.instance and GarbageCollector.instance
- # ActiveRecord::Base.observers = :cacher, :garbage_collector
+ # ORM.observers = :cacher, :garbage_collector
#
# # Same as above, just using explicit class references
- # ActiveRecord::Base.observers = Cacher, GarbageCollector
+ # ORM.observers = Cacher, GarbageCollector
#
- # Note: Setting this does not instantiate the observers yet.
+ # Note: Setting this does not instantiate the observers yet.
# +instantiate_observers+ is called during startup, and before
# each development request.
def observers=(*values)
@@ -34,36 +38,41 @@ module ActiveModel
@observers ||= []
end
+ # Gets the current observer instances.
+ def observer_instances
+ @observer_instances ||= []
+ end
+
# Instantiate the global Active Record observers.
def instantiate_observers
observers.each { |o| instantiate_observer(o) }
end
+ # Add a new observer to the pool.
def add_observer(observer)
unless observer.respond_to? :update
raise ArgumentError, "observer needs to respond to `update'"
end
- @observer_instances ||= []
- @observer_instances << observer
+ observer_instances << observer
end
+ # Notify list of observers of a change.
def notify_observers(*arg)
- if defined? @observer_instances
- for observer in @observer_instances
- observer.update(*arg)
- end
+ for observer in observer_instances
+ observer.update(*arg)
end
end
+ # Total number of observers.
def count_observers
- @observer_instances.size
+ observer_instances.size
end
protected
def instantiate_observer(observer) #:nodoc:
# string/symbol
if observer.respond_to?(:to_sym)
- observer = observer.to_s.camelize.constantize.instance
+ observer.to_s.camelize.constantize.instance
elsif observer.respond_to?(:instance)
observer.instance
else
@@ -93,7 +102,7 @@ module ActiveModel
# == Active Model Observers
#
- # Observer classes respond to lifecycle callbacks to implement trigger-like
+ # Observer classes respond to life cycle callbacks to implement trigger-like
# behavior outside the original class. This is a great way to reduce the
# clutter that normally comes when the model class is burdened with
# functionality that doesn't pertain to the core responsibility of the
@@ -123,9 +132,9 @@ module ActiveModel
#
# Observers will by default be mapped to the class with which they share a
# name. So CommentObserver will be tied to observing Comment, ProductManagerObserver
- # to ProductManager, and so on. If you want to name your observer differently than
- # the class you're interested in observing, you can use the Observer.observe class
- # method which takes either the concrete class (Product) or a symbol for that
+ # to ProductManager, and so on. If you want to name your observer differently than
+ # the class you're interested in observing, you can use the Observer.observe class
+ # method which takes either the concrete class (Product) or a symbol for that
# class (:product):
#
# class AuditObserver < ActiveModel::Observer
@@ -136,7 +145,7 @@ module ActiveModel
# end
# end
#
- # If the audit observer needs to watch more than one kind of object, this can be
+ # If the audit observer needs to watch more than one kind of object, this can be
# specified with multiple arguments:
#
# class AuditObserver < ActiveModel::Observer
@@ -147,9 +156,13 @@ module ActiveModel
# end
# end
#
- # The AuditObserver will now act on both updates to Account and Balance by treating
+ # The AuditObserver will now act on both updates to Account and Balance by treating
# them both as records.
#
+ # If you're using an Observer in a Rails application with Active Record, be sure to
+ # read about the necessary configuration in the documentation for
+ # ActiveRecord::Observer.
+ #
class Observer
include Singleton
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
new file mode 100644
index 0000000000..957d0ddaaa
--- /dev/null
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -0,0 +1,66 @@
+require 'bcrypt'
+
+module ActiveModel
+ module SecurePassword
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Adds methods to set and authenticate against a BCrypt password.
+ # This mechanism requires you to have a password_digest attribute.
+ #
+ # Validations for presence of password, confirmation of password (using
+ # a "password_confirmation" attribute) are automatically added.
+ # You can add more validations by hand if need be.
+ #
+ # Example using Active Record (which automatically includes ActiveModel::SecurePassword):
+ #
+ # # Schema: User(name:string, password_digest:string)
+ # class User < ActiveRecord::Base
+ # has_secure_password
+ # end
+ #
+ # user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
+ # user.save # => false, password required
+ # user.password = "mUc3m00RsqyRe"
+ # user.save # => false, confirmation doesn't match
+ # user.password_confirmation = "mUc3m00RsqyRe"
+ # user.save # => true
+ # user.authenticate("notright") # => false
+ # user.authenticate("mUc3m00RsqyRe") # => user
+ # User.find_by_name("david").try(:authenticate, "notright") # => nil
+ # User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user
+ def has_secure_password
+ attr_reader :password
+ attr_accessor :password_confirmation
+
+ validates_confirmation_of :password
+ validates_presence_of :password_digest
+
+ include InstanceMethodsOnActivation
+
+ if respond_to?(:attributes_protected_by_default)
+ def self.attributes_protected_by_default
+ super + ['password_digest']
+ end
+ end
+ end
+ end
+
+ module InstanceMethodsOnActivation
+ # Returns self if the password is correct, otherwise false.
+ def authenticate(unencrypted_password)
+ if BCrypt::Password.new(password_digest) == unencrypted_password
+ self
+ else
+ false
+ end
+ end
+
+ # Encrypts the password into the password_digest attribute.
+ def password=(unencrypted_password)
+ @password = unencrypted_password
+ self.password_digest = BCrypt::Password.create(unencrypted_password)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
index e675937f4d..caf44a2ee0 100644
--- a/activemodel/lib/active_model/serialization.rb
+++ b/activemodel/lib/active_model/serialization.rb
@@ -3,25 +3,25 @@ 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
- # @attributes ||= {'name' => 'nil'}
+ # {'name' => name}
# end
- #
+ #
# end
- #
+ #
# Which would provide you with:
- #
+ #
# person = Person.new
# person.serializable_hash # => {"name"=>nil}
# person.name = "Bob"
@@ -29,63 +29,58 @@ module ActiveModel
#
# You need to declare some sort of attributes hash which contains the attributes
# you want to serialize and their current value.
- #
- # Most of the time though, you will want to include the JSON or XML
- # serializations. Both of these modules automatically include the
+ #
+ # Most of the time though, you will want to include the JSON or XML
+ # serializations. Both of these modules automatically include the
# ActiveModel::Serialization module, so there is no need to explicitly
# include it.
- #
+ #
# So a minimal implementation including XML and JSON would be:
- #
+ #
# class Person
- #
+ #
# include ActiveModel::Serializers::JSON
# include ActiveModel::Serializers::Xml
- #
+ #
# attr_accessor :name
- #
+ #
# def attributes
- # @attributes ||= {'name' => 'nil'}
+ # {'name' => name}
# 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> and <tt>:methods</tt> .
+ # Valid options are <tt>:only</tt>, <tt>:except</tt> and <tt>:methods</tt> .
module Serialization
def serializable_hash(options = nil)
options ||= {}
- options[:only] = Array.wrap(options[:only]).map { |n| n.to_s }
- options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
+ only = Array.wrap(options[:only]).map(&:to_s)
+ except = Array.wrap(options[:except]).map(&:to_s)
attribute_names = attributes.keys.sort
- if options[:only].any?
- attribute_names &= options[:only]
- elsif options[:except].any?
- attribute_names -= options[:except]
- end
-
- method_names = Array.wrap(options[:methods]).inject([]) do |methods, name|
- methods << name if respond_to?(name.to_s)
- methods
+ if only.any?
+ attribute_names &= only
+ elsif except.any?
+ attribute_names -= except
end
- (attribute_names + method_names).inject({}) { |hash, name|
- hash[name] = send(name)
- hash
- }
+ method_names = Array.wrap(options[:methods]).map { |n| n if respond_to?(n.to_s) }.compact
+ Hash[(attribute_names + method_names).map { |n| [n, send(n)] }]
end
end
end
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index e1dbc522de..0bfbf2aa06 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -18,17 +18,17 @@ module ActiveModel
# Returns a JSON string representing the model. Some configuration can be
# passed through +options+.
#
- # The option <tt>ActiveModel::Base.include_root_in_json</tt> controls the
- # top-level behavior of +to_json+. If true (the default) +to_json+ will
- # emit a single root node named after the object's type. For example:
+ # The option <tt>include_root_in_json</tt> controls the top-level behavior
+ # of +as_json+. If true (the default) +as_json+ will emit a single root
+ # node named after the object's type. For example:
#
# konata = User.find(1)
- # konata.to_json
+ # konata.as_json
# # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
# "created_at": "2006/08/01", "awesome": true} }
#
# ActiveRecord::Base.include_root_in_json = false
- # konata.to_json
+ # konata.as_json
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
# "created_at": "2006/08/01", "awesome": true}
#
@@ -39,29 +39,29 @@ module ActiveModel
# attributes. For example:
#
# konata = User.find(1)
- # konata.to_json
+ # konata.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. For example:
#
- # konata.to_json(:only => [ :id, :name ])
+ # konata.as_json(:only => [ :id, :name ])
# # => {"id": 1, "name": "Konata Izumi"}
#
- # konata.to_json(:except => [ :id, :created_at, :age ])
+ # konata.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>:
#
- # konata.to_json(:methods => :permalink)
+ # konata.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>:
#
- # konata.to_json(:include => :posts)
+ # konata.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"},
@@ -69,7 +69,7 @@ module ActiveModel
#
# Second level and higher order associations work as well:
#
- # konata.to_json(:include => { :posts => {
+ # konata.as_json(:include => { :posts => {
# :include => { :comments => {
# :only => :body } },
# :only => :title } })
@@ -79,18 +79,16 @@ module ActiveModel
# "title": "Welcome to the weblog"},
# {"comments": [{"body": "Don't think too hard"}],
# "title": "So I was thinking"}]}
- def encode_json(encoder)
- hash = serializable_hash(encoder.options)
+
+ def as_json(options = nil)
+ hash = serializable_hash(options)
+
if include_root_in_json
- custom_root = encoder.options && encoder.options[:root]
+ custom_root = options && options[:root]
hash = { custom_root || self.class.model_name.element => hash }
end
- ActiveSupport::JSON.encode(hash)
- end
-
- def as_json(options = nil)
- self
+ hash
end
def from_json(json)
diff --git a/activemodel/lib/active_model/serializers/xml.rb b/activemodel/lib/active_model/serializers/xml.rb
index ed64434b8f..d4295e6afe 100644
--- a/activemodel/lib/active_model/serializers/xml.rb
+++ b/activemodel/lib/active_model/serializers/xml.rb
@@ -17,7 +17,8 @@ module ActiveModel
def initialize(name, serializable, raw_value=nil)
@name, @serializable = name, serializable
- @value = value || @serializable.send(name)
+ raw_value = raw_value.in_time_zone if raw_value.respond_to?(:in_time_zone)
+ @value = raw_value || @serializable.send(name)
@type = compute_type
end
@@ -52,7 +53,7 @@ module ActiveModel
@options[:except] = Array.wrap(@options[:except]).map { |n| n.to_s }
end
- # To replicate the behavior in ActiveRecord#attributes, <tt>:except</tt>
+ # To replicate the behavior in ActiveRecord#attributes, <tt>:except</tt>
# takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
# for a N level model but is set for the N+1 level models,
# then because <tt>:except</tt> is set to a default value, the second
@@ -76,10 +77,9 @@ module ActiveModel
end
def serializable_methods
- Array.wrap(options[:methods]).inject([]) do |methods, name|
- methods << self.class::MethodAttribute.new(name.to_s, @serializable) if @serializable.respond_to?(name.to_s)
- methods
- end
+ Array.wrap(options[:methods]).map do |name|
+ self.class::MethodAttribute.new(name.to_s, @serializable) if @serializable.respond_to?(name.to_s)
+ end.compact
end
def serialize
@@ -134,6 +134,29 @@ module ActiveModel
# Returns XML representing the model. Configuration can be
# passed through +options+.
+ #
+ # Without any +options+, the returned XML string will include all the model's
+ # attributes. For example:
+ #
+ # konata = User.find(1)
+ # konata.to_xml
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <user>
+ # <id type="integer">1</id>
+ # <name>David</name>
+ # <age type="integer">16</age>
+ # <created-at type="datetime">2011-01-30T22:29:23Z</created-at>
+ # </user>
+ #
+ # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
+ # included, and work similar to the +attributes+ method.
+ #
+ # To include the result of some method calls on the model use <tt>:methods</tt>.
+ #
+ # To include associations use <tt>:include</tt>.
+ #
+ # For further documentation see activerecord/lib/active_record/serializers/xml_serializer.xml.
def to_xml(options = {}, &block)
Serializer.new(self, options).serialize(&block)
end
diff --git a/activemodel/lib/active_model/translation.rb b/activemodel/lib/active_model/translation.rb
index 0facbd6ce1..dbb76244e4 100644
--- a/activemodel/lib/active_model/translation.rb
+++ b/activemodel/lib/active_model/translation.rb
@@ -3,19 +3,19 @@ require 'active_support/core_ext/hash/reverse_merge'
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
@@ -28,9 +28,9 @@ module ActiveModel
:activemodel
end
- # When localizing a string, it goes through the lookup returned by this
+ # 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::Errors#full_messages and
# ActiveModel::Translation#human_attribute_name.
def lookup_ancestors
self.ancestors.select { |x| x.respond_to?(:model_name) }
@@ -54,11 +54,5 @@ module ActiveModel
options.reverse_merge! :count => 1, :default => defaults
I18n.translate(defaults.shift, options)
end
-
- # Model.human_name is deprecated. Use Model.model_name.human instead.
- def human_name(*args)
- ActiveSupport::Deprecation.warn("human_name has been deprecated, please use model_name.human instead", caller[0,5])
- model_name.human(*args)
- end
end
end
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 3407c59e7a..d968609e67 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -2,30 +2,31 @@ require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/hash/except'
require 'active_model/errors'
require 'active_model/validations/callbacks'
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
@@ -34,11 +35,11 @@ module ActiveModel
# person.valid? # => false
# person.invalid? # => true
# person.errors # => #<OrderedHash {:first_name=>["starts with z."]}>
- #
- # Note that ActiveModel::Validations automatically adds an +errors+ method
- # to your instances initialized with a new ActiveModel::Errors object, so
+ #
+ # 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
include ActiveSupport::Callbacks
@@ -61,7 +62,7 @@ module ActiveModel
#
# class Person
# include ActiveModel::Validations
- #
+ #
# attr_accessor :first_name, :last_name
#
# validates_each :first_name, :last_name do |record, attr, value|
@@ -70,8 +71,8 @@ module ActiveModel
# end
#
# Options:
- # * <tt>:on</tt> - Specifies when this validation is active (default is
- # <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies the context where this validation is active
+ # (e.g. <tt>:on => :create</tt> or <tt>:on => :custom_validation_context</tt>)
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
@@ -95,15 +96,15 @@ module ActiveModel
#
# class Comment
# include ActiveModel::Validations
- #
+ #
# validate :must_be_friends
#
# def must_be_friends
- # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
# end
# end
#
- # Or with a block which is passed with the current record to be validated:
+ # With a block which is passed with the current record to be validated:
#
# class Comment
# include ActiveModel::Validations
@@ -113,7 +114,17 @@ module ActiveModel
# end
#
# def must_be_friends
- # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # end
+ # end
+ #
+ # 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
#
@@ -128,15 +139,17 @@ module ActiveModel
set_callback(:validate, *args, &block)
end
- # List all validators that are being used to validate the model using
+ # List all validators that are being used to validate the model using
# +validates_with+ method.
def validators
_validators.values.flatten.uniq
end
# List all validators that being used to validate a specific attribute.
- def validators_on(attribute)
- _validators[attribute.to_sym]
+ def validators_on(*attributes)
+ attributes.map do |attribute|
+ _validators[attribute.to_sym]
+ end.flatten
end
# Check if method is an attribute method or not.
@@ -152,7 +165,7 @@ module ActiveModel
end
end
- # Returns the Errors object that holds all information about attribute error messages.
+ # Returns the +Errors+ object that holds all information about attribute error messages.
def errors
@errors ||= Errors.new(self)
end
@@ -168,14 +181,14 @@ module ActiveModel
self.validation_context = current_context
end
- # Performs the opposite of <tt>valid?</tt>. Returns true if errors were added,
+ # Performs the opposite of <tt>valid?</tt>. Returns true if errors were added,
# false otherwise.
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
+ # 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:
#
@@ -194,9 +207,9 @@ module ActiveModel
alias :read_attribute_for_validation :send
protected
-
+
def run_validations!
- _run_validate_callbacks
+ run_callbacks :validate
errors.empty?
end
end
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
index 99b8966def..4f390613aa 100644
--- a/activemodel/lib/active_model/validations/acceptance.rb
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -14,8 +14,6 @@ module ActiveModel
end
def setup(klass)
- # Note: instance_methods.map(&:to_s) is important for 1.9 compatibility
- # as instance_methods returns symbols unlike 1.8 which returns strings.
attr_readers = attributes.reject { |name| klass.attribute_method?(name) }
attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") }
klass.send(:attr_reader, *attr_readers)
@@ -24,7 +22,7 @@ module ActiveModel
end
module HelperMethods
- # Encapsulates the pattern of wanting to validate the acceptance of a
+ # Encapsulates the pattern of wanting to validate the acceptance of a
# terms of service check box (or similar agreement). Example:
#
# class Person < ActiveRecord::Base
@@ -32,33 +30,33 @@ module ActiveModel
# validates_acceptance_of :eula, :message => "must be abided"
# end
#
- # If the database column does not exist, the +terms_of_service+ attribute
+ # 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
+ # * <tt>:message</tt> - A custom error message (default is: "must be
# accepted").
- # * <tt>:on</tt> - Specifies when this validation is active (default is
- # <tt>:save</tt>, other options are <tt>:create</tt> and
- # <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default
# is true).
- # * <tt>:accept</tt> - Specifies value that is considered accepted.
+ # * <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
+ # an HTML checkbox. This should be set to +true+ if you are validating
# a database column, since the attribute is typecast from "1" to +true+
# before validation.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false
+ # method, proc or string should return or evaluate to a true or false
# value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to
- # determine if the validation should not occur (for example,
- # <tt>:unless => :skip_validation</tt>, or
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur (for example,
+ # <tt>:unless => :skip_validation</tt>, or
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
- # The method, proc or string should return or evaluate to a true or
+ # The method, proc or string should return or evaluate to a true or
# false value.
def validates_acceptance_of(*attr_names)
validates_with AcceptanceValidator, _merge_attributes(attr_names)
diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb
index afd65d3dd5..adc2867ad0 100644
--- a/activemodel/lib/active_model/validations/callbacks.rb
+++ b/activemodel/lib/active_model/validations/callbacks.rb
@@ -14,7 +14,7 @@ module ActiveModel
# include ActiveModel::Validations::Callbacks
#
# before_validation :do_stuff_before_validation
- # after_validation :do_tuff_after_validation
+ # after_validation :do_stuff_after_validation
# end
#
# Like other before_* callbacks if <tt>before_validation</tt> returns false
@@ -40,7 +40,7 @@ module ActiveModel
options = args.extract_options!
options[:prepend] = true
options[:if] = Array.wrap(options[:if])
- options[:if] << "!halted && value != false"
+ options[:if] << "!halted"
options[:if] << "self.validation_context == :#{options[:on]}" if options[:on]
set_callback(:validation, :after, *(args << options), &block)
end
@@ -50,7 +50,7 @@ module ActiveModel
# Overwrite run validations to include callbacks.
def run_validations!
- _run_validation_callbacks { super }
+ run_callbacks(:validation) { super }
end
end
end
diff --git a/activemodel/lib/active_model/validations/confirmation.rb b/activemodel/lib/active_model/validations/confirmation.rb
index 3a80893866..e6d10cfff8 100644
--- a/activemodel/lib/active_model/validations/confirmation.rb
+++ b/activemodel/lib/active_model/validations/confirmation.rb
@@ -4,24 +4,26 @@ module ActiveModel
module Validations
class ConfirmationValidator < EachValidator
def validate_each(record, attribute, value)
- confirmed = record.send(:"#{attribute}_confirmation")
- return if confirmed.nil? || value == confirmed
- record.errors.add(attribute, :confirmation, options)
+ if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
+ record.errors.add(attribute, :confirmation, options)
+ end
end
def setup(klass)
- klass.send(:attr_accessor, *attributes.map { |attribute| :"#{attribute}_confirmation" })
+ klass.send(:attr_accessor, *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
+ # Encapsulates the pattern of wanting to validate a password or email
# address field with a confirmation. For example:
#
# Model:
# class Person < ActiveRecord::Base
# validates_confirmation_of :user_name, :password
- # validates_confirmation_of :email_address,
+ # validates_confirmation_of :email_address,
# :message => "should match confirmation"
# end
#
@@ -29,12 +31,12 @@ module ActiveModel
# <%= password_field "person", "password" %>
# <%= password_field "person", "password_confirmation" %>
#
- # The added +password_confirmation+ attribute is virtual; it exists only
+ # 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
+ # the validation adds accessors to the model for the confirmation
# attribute.
- #
- # NOTE: This check is performed only if +password_confirmation+ is not
+ #
+ # NOTE: This check is performed only if +password_confirmation+ is not
# +nil+, and by default only on save. To require confirmation, make sure
# to add a presence check for the confirmation attribute:
#
@@ -43,16 +45,17 @@ module ActiveModel
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
# confirmation").
- # * <tt>:on</tt> - Specifies when this validation is active (default is
- # <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false
+ # 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</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_confirmation_of(*attr_names)
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
index 4138892786..e38e565d09 100644
--- a/activemodel/lib/active_model/validations/exclusion.rb
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -29,6 +29,9 @@ module ActiveModel
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
index 104f403492..541f53a834 100644
--- a/activemodel/lib/active_model/validations/format.rb
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -51,7 +51,9 @@ module ActiveModel
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:with</tt> - Regular expression that if the attribute matches will result in a successful validation.
# * <tt>:without</tt> - Regular expression that if the attribute does not match will result in a successful validation.
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index 049b093618..92ac940f36 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/range.rb'
+
module ActiveModel
# == Active Model Inclusion Validator
@@ -9,9 +11,14 @@ module ActiveModel
end
def validate_each(record, attribute, value)
- unless options[:in].include?(value)
- record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
- end
+ record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value)) unless options[:in].send(include?, value)
+ end
+
+ # In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible values in the
+ # range for equality, so it may be slow for large ranges. The new <tt>Range#cover?</tt>
+ # uses the previous logic of comparing a value with the range endpoints.
+ def include?
+ options[:in].is_a?(Range) ? :cover? : :include?
end
end
@@ -26,9 +33,14 @@ module ActiveModel
#
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items.
+ # If the enumerable is a range the test is performed with <tt>Range#cover?</tt>
+ # (backported in Active Support for 1.8), otherwise with <tt>include?</tt>.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index a7af4f2b4d..72735cfb89 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -34,20 +34,17 @@ module ActiveModel
end
end
end
-
+
def validate_each(record, attribute, value)
value = options[:tokenizer].call(value) if value.kind_of?(String)
CHECKS.each do |key, validity_check|
next unless check_value = options[key]
- valid_value = if key == :maximum
- value.nil? || value.size.send(validity_check, check_value)
- else
- value && value.size.send(validity_check, check_value)
- end
+ value ||= [] if key == :maximum
- next if valid_value
+ value_length = value.respond_to?(:length) ? value.length : value.to_s.length
+ next if value_length.send(validity_check, check_value)
errors_options = options.except(*RESERVED_OPTIONS)
errors_options[:count] = check_value
@@ -87,7 +84,9 @@ module ActiveModel
# * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %{count} characters)").
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %{count} characters)").
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index b6aff7aa6b..ae576462e6 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -24,7 +24,7 @@ module ActiveModel
def validate_each(record, attr_name, value)
before_type_cast = "#{attr_name}_before_type_cast"
- raw_value = record.send("#{attr_name}_before_type_cast") if record.respond_to?(before_type_cast.to_sym)
+ raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast.to_sym)
raw_value ||= value
return if options[:allow_nil] && raw_value.nil?
@@ -93,7 +93,9 @@ module ActiveModel
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
# * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
diff --git a/activemodel/lib/active_model/validations/presence.rb b/activemodel/lib/active_model/validations/presence.rb
index 28c4640b17..cfb4c33dcc 100644
--- a/activemodel/lib/active_model/validations/presence.rb
+++ b/activemodel/lib/active_model/validations/presence.rb
@@ -26,8 +26,9 @@ module ActiveModel
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "can't be blank").
- # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>,
- # <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb
index 3260e6bc5a..7ff42de00b 100644
--- a/activemodel/lib/active_model/validations/validates.rb
+++ b/activemodel/lib/active_model/validations/validates.rb
@@ -9,7 +9,7 @@ module ActiveModel
# 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
@@ -21,25 +21,25 @@ module ActiveModel
# validates :age, :numericality => true
# validates :username, :presence => true
# validates :username, :uniqueness => true
- #
+ #
# The power of the +validates+ method comes when using custom validators
# and default validators in one call for a given attribute e.g.
#
# 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
+ # 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 e.g.
#
@@ -48,21 +48,30 @@ module ActiveModel
#
# class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
- # record.errors[attribute] << "must start with 'the'" unless =~ /^the/i
+ # record.errors[attribute] << "must start with 'the'" unless value =~ /\Athe/i
# end
# end
#
# validates :name, :title => true
# end
#
- # The validators hash can also handle regular expressions, ranges and arrays:
+ # Additionally validator classes may be in another namespace and still used within any class.
+ #
+ # validates :name, :'file/title' => true
+ #
+ # The validators hash can also handle regular expressions, ranges,
+ # arrays and strings in shortcut form, e.g.
#
# validates :email, :format => /@/
# validates :gender, :inclusion => %w(male female)
# validates :password, :length => 6..20
#
- # Finally, the options :if, :unless, :on, :allow_blank and :allow_nil can be given
- # to one specific validator:
+ # When using shortcut form, ranges and arrays are passed to your
+ # validator's initializer as +options[:in]+ while other types including
+ # regular expressions and strings are passed as +options[:with]+
+ #
+ # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+ and +:allow_nil+ can be given
+ # to one specific validator, as a hash:
#
# validates :password, :presence => { :if => :password_required? }, :confirmation => true
#
@@ -72,17 +81,18 @@ module ActiveModel
#
def validates(*attributes)
defaults = attributes.extract_options!
- validations = defaults.slice!(:if, :unless, :on, :allow_blank, :allow_nil)
+ validations = defaults.slice!(*_validates_default_keys)
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
- raise ArgumentError, "Attribute names must be symbols" if attributes.any?{ |attribute| !attribute.is_a?(Symbol) }
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
defaults.merge!(:attributes => attributes)
validations.each do |key, options|
+ key = "#{key.to_s.camelize}Validator"
+
begin
- validator = const_get("#{key.to_s.camelize}Validator")
+ validator = key.include?('::') ? key.constantize : const_get(key)
rescue NameError
raise ArgumentError, "Unknown validator: '#{key}'"
end
@@ -93,18 +103,24 @@ module ActiveModel
protected
+ # When creating custom validators, it might be useful to be able to specify
+ # additional default keys. This can be done by overwriting this method.
+ def _validates_default_keys
+ [ :if, :unless, :on, :allow_blank, :allow_nil ]
+ end
+
def _parse_validates_options(options) #:nodoc:
case options
when TrueClass
{}
when Hash
options
- when Regexp
- { :with => options }
when Range, Array
{ :in => options }
+ else
+ { :with => options }
end
end
end
end
-end \ No newline at end of file
+end
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index 200efd4eb5..65ae18a769 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -8,6 +8,18 @@ module ActiveModel
end
end
+ class WithValidator < EachValidator
+ def validate_each(record, attr, val)
+ method_name = options[:with]
+
+ if record.method(method_name).arity == 0
+ record.send method_name
+ else
+ record.send method_name, attr
+ end
+ end
+ end
+
module ClassMethods
# Passes the record off to the class or classes specified and allows them
# to add errors based on more complex conditions.
@@ -38,9 +50,9 @@ module ActiveModel
# end
#
# Configuration options:
- # * <tt>on</tt> - Specifies when this validation is active
+ # * <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
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
index 163124d531..c5ed8d22d3 100644
--- a/activemodel/lib/active_model/validator.rb
+++ b/activemodel/lib/active_model/validator.rb
@@ -5,9 +5,9 @@ require 'active_support/core_ext/object/blank'
module ActiveModel #:nodoc:
# == Active Model Validator
- #
- # A simple base class that can be used along with
- # +ActiveModel::Validations::ClassMethods.validates_with+
+ #
+ # A simple base class that can be used along with
+ # ActiveModel::Validations::ClassMethods.validates_with
#
# class Person
# include ActiveModel::Validations
@@ -42,7 +42,7 @@ module ActiveModel #:nodoc:
# end
# end
#
- # To cause a validation error, you must add to the <tt>record<tt>'s errors directly
+ # To cause a validation error, you must add to the <tt>record</tt>'s errors directly
# from within the validators message
#
# class MyValidator < ActiveModel::Validator
@@ -61,31 +61,31 @@ module ActiveModel #:nodoc:
# @my_custom_field = options[:field_name] || :first_name
# end
# end
- #
+ #
# The easiest way to add custom validators for validating individual attributes
- # is with the convenient ActiveModel::EachValidator for example:
- #
+ # is with the convenient <tt>ActiveModel::EachValidator</tt>. For example:
+ #
# class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
# record.errors[attribute] << 'must be Mr. Mrs. or Dr.' unless ['Mr.', 'Mrs.', 'Dr.'].include?(value)
# end
# end
- #
+ #
# This can now be used in combination with the +validates+ method
- # (see ActiveModel::Validations::ClassMethods.validates for more on this)
- #
+ # (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this)
+ #
# class Person
# include ActiveModel::Validations
# attr_accessor :title
- #
- # validates :title, :presence => true, :title => true
+ #
+ # 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 it's argument. This can be
- # useful when there are prerequisites such as an attr_accessor being present
+ # with the class that using that validator as its argument. This can be
+ # useful when there are prerequisites such as an +attr_accessor+ being present
# for example:
- #
+ #
# class MyValidator < ActiveModel::Validator
# def setup(klass)
# klass.send :attr_accessor, :custom_attribute
@@ -94,13 +94,11 @@ module ActiveModel #:nodoc:
#
# This setup method is only called when used with validation macros or the
# class level <tt>validates_with</tt> method.
- #
+ #
class Validator
attr_reader :options
- # Returns the kind of the validator.
- #
- # == Examples
+ # Returns the kind of the validator. Examples:
#
# PresenceValidator.kind # => :presence
# UniquenessValidator.kind # => :uniqueness
@@ -122,18 +120,18 @@ module ActiveModel #:nodoc:
# Override this method in subclasses with validation logic, adding errors
# to the records +errors+ array where necessary.
def validate(record)
- raise NotImplementedError
+ 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 validate_each method passing in the
+ # +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.
+ # All Active Model validations are built on top of this validator.
class EachValidator < Validator
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.
@@ -158,19 +156,18 @@ module ActiveModel #:nodoc:
# 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
+ 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.
+ # +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.
+ # +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
def initialize(options, &block)
@block = block
diff --git a/activemodel/lib/active_model/version.rb b/activemodel/lib/active_model/version.rb
index f2f4b15520..23ba42bf35 100644
--- a/activemodel/lib/active_model/version.rb
+++ b/activemodel/lib/active_model/version.rb
@@ -1,10 +1,10 @@
module ActiveModel
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb
index c60caf90d7..022c6716bd 100644
--- a/activemodel/test/cases/attribute_methods_test.rb
+++ b/activemodel/test/cases/attribute_methods_test.rb
@@ -2,9 +2,15 @@ require 'cases/helper'
class ModelWithAttributes
include ActiveModel::AttributeMethods
-
+
attribute_method_suffix ''
+ class << self
+ define_method(:bar) do
+ 'original bar'
+ end
+ end
+
def attributes
{ :foo => 'value of foo' }
end
@@ -17,29 +23,110 @@ end
class ModelWithAttributes2
include ActiveModel::AttributeMethods
-
+
attribute_method_suffix '_test'
end
+class ModelWithAttributesWithSpaces
+ include ActiveModel::AttributeMethods
+
+ attribute_method_suffix ''
+
+ def attributes
+ { :'foo bar' => 'value of foo bar'}
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithWeirdNamesAttributes
+ include ActiveModel::AttributeMethods
+
+ attribute_method_suffix ''
+
+ 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 AttributeMethodsTest < ActiveModel::TestCase
test 'unrelated classes should not share attribute method matchers' do
assert_not_equal ModelWithAttributes.send(:attribute_method_matchers),
ModelWithAttributes2.send(:attribute_method_matchers)
end
+ test '#define_attribute_method generates attribute method' do
+ ModelWithAttributes.define_attribute_method(:foo)
+
+ assert_respond_to ModelWithAttributes.new, :foo
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ end
+
+ test '#define_attribute_method generates attribute method with invalid identifier characters' do
+ ModelWithWeirdNamesAttributes.define_attribute_method(:'a?b')
+ 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 generates attribute methods' do
ModelWithAttributes.define_attribute_methods([:foo])
- assert ModelWithAttributes.attribute_methods_generated?
assert_respond_to ModelWithAttributes.new, :foo
assert_equal "value of foo", ModelWithAttributes.new.foo
end
+ test '#define_attribute_methods generates attribute methods with spaces in their names' do
+ ModelWithAttributesWithSpaces.define_attribute_methods([:'foo bar'])
+
+ assert_respond_to ModelWithAttributesWithSpaces.new, :'foo bar'
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.send(:'foo bar')
+ end
+
+ test '#define_attr_method generates attribute method' do
+ ModelWithAttributes.define_attr_method(:bar, 'bar')
+
+ assert_respond_to ModelWithAttributes, :bar
+ assert_equal "original bar", ModelWithAttributes.original_bar
+ assert_equal "bar", ModelWithAttributes.bar
+ ModelWithAttributes.define_attr_method(:bar)
+ assert !ModelWithAttributes.bar
+ end
+
+ test '#define_attr_method generates attribute method with invalid identifier characters' do
+ ModelWithWeirdNamesAttributes.define_attr_method(:'c?d', 'c?d')
+
+ assert_respond_to ModelWithWeirdNamesAttributes, :'c?d'
+ assert_equal "original c?d", ModelWithWeirdNamesAttributes.send('original_c?d')
+ assert_equal "c?d", ModelWithWeirdNamesAttributes.send('c?d')
+ end
+
+ test '#alias_attribute works with attributes with spaces in their names' do
+ ModelWithAttributesWithSpaces.define_attribute_methods([:'foo bar'])
+ ModelWithAttributesWithSpaces.alias_attribute(:'foo_bar', :'foo bar')
+
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.foo_bar
+ end
+
test '#undefine_attribute_methods removes attribute methods' do
ModelWithAttributes.define_attribute_methods([:foo])
ModelWithAttributes.undefine_attribute_methods
- assert !ModelWithAttributes.attribute_methods_generated?
assert !ModelWithAttributes.new.respond_to?(:foo)
assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
end
diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
index 9675b5d450..086e7266ff 100644
--- a/activemodel/test/cases/callbacks_test.rb
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -16,6 +16,8 @@ class CallbacksTest < ActiveModel::TestCase
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
@@ -35,7 +37,7 @@ class CallbacksTest < ActiveModel::TestCase
end
def create
- _run_create_callbacks do
+ run_callbacks :create do
@callbacks << :create
@valid
end
@@ -67,4 +69,46 @@ class CallbacksTest < ActiveModel::TestCase
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 differnt lines" do
+ assert_equal ["callback1", "callback2"], Violin2.new.create.history
+ end
+
end
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index 79b45bb298..a24cac40ad 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -25,7 +25,19 @@ class ErrorsTest < ActiveModel::TestCase
def self.lookup_ancestors
[self]
end
+ end
+
+ def test_include?
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ assert errors.include?(:foo), 'errors should include :foo'
+ end
+ test "should return true if no errors" do
+ person = Person.new
+ person.errors[:foo]
+ assert person.errors.empty?
+ assert person.errors.blank?
end
test "method validate! should work" do
@@ -62,4 +74,9 @@ class ErrorsTest < ActiveModel::TestCase
end
+ test 'to_hash should return an ordered hash' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_instance_of ActiveSupport::OrderedHash, person.errors.to_hash
+ end
end
diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb
index a32f11484a..01f0158678 100644
--- a/activemodel/test/cases/helper.rb
+++ b/activemodel/test/cases/helper.rb
@@ -6,16 +6,9 @@ $:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'config'
require 'active_model'
require 'active_support/core_ext/string/access'
-require 'active_support/core_ext/hash/except'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
require 'rubygems'
require 'test/unit'
-
-begin
- require 'ruby-debug'
- Debugger.start
-rescue LoadError
-end
diff --git a/activemodel/test/cases/mass_assignment_security_test.rb b/activemodel/test/cases/mass_assignment_security_test.rb
index c25b0fdf00..f84e55e8d9 100644
--- a/activemodel/test/cases/mass_assignment_security_test.rb
+++ b/activemodel/test/cases/mass_assignment_security_test.rb
@@ -25,13 +25,13 @@ class MassAssignmentSecurityTest < ActiveModel::TestCase
end
def test_mass_assignment_protection_inheritance
- assert LoosePerson.accessible_attributes.blank?
+ assert_blank LoosePerson.accessible_attributes
assert_equal Set.new([ 'credit_rating', 'administrator']), LoosePerson.protected_attributes
- assert LooseDescendant.accessible_attributes.blank?
+ assert_blank LooseDescendant.accessible_attributes
assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number']), LooseDescendant.protected_attributes
- assert LooseDescendantSecond.accessible_attributes.blank?
+ assert_blank LooseDescendantSecond.accessible_attributes
assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number', 'name']), LooseDescendantSecond.protected_attributes,
'Running attr_protected twice in one class should merge the protections'
diff --git a/activemodel/test/cases/naming_test.rb b/activemodel/test/cases/naming_test.rb
index 5a8bff378a..a7dde2c433 100644
--- a/activemodel/test/cases/naming_test.rb
+++ b/activemodel/test/cases/naming_test.rb
@@ -2,6 +2,7 @@ require 'cases/helper'
require 'models/contact'
require 'models/sheep'
require 'models/track_back'
+require 'models/blog_post'
class NamingTest < ActiveModel::TestCase
def setup
@@ -27,6 +28,90 @@ class NamingTest < ActiveModel::TestCase
def test_partial_path
assert_equal 'post/track_backs/track_back', @model_name.partial_path
end
+
+ def test_human
+ assert_equal 'Track back', @model_name.human
+ 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_partial_path
+ assert_equal 'blog/posts/post', @model_name.partial_path
+ 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_recognizing_namespace
+ assert_equal 'Post', Blog::Post.model_name.instance_variable_get("@unnamespaced")
+ 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_partial_path
+ assert_equal 'blog/posts/post', @model_name.partial_path
+ 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
end
class NamingHelpersTest < Test::Unit::TestCase
@@ -36,6 +121,12 @@ class NamingHelpersTest < Test::Unit::TestCase
@singular = 'contact'
@plural = 'contacts'
@uncountable = Sheep
+ @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
@@ -54,6 +145,22 @@ class NamingHelpersTest < Test::Unit::TestCase
assert_equal @plural, plural(@klass)
end
+ def test_route_key
+ assert_equal @route_key, route_key(@record)
+ end
+
+ def test_route_key_for_class
+ assert_equal @route_key, 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 uncoutable"
assert !uncountable?(@klass), "Expected 'contact' to be countable"
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
new file mode 100644
index 0000000000..4a47a7a226
--- /dev/null
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -0,0 +1,45 @@
+require 'cases/helper'
+require 'models/user'
+require 'models/visitor'
+require 'models/administrator'
+
+class SecurePasswordTest < ActiveModel::TestCase
+
+ setup do
+ @user = User.new
+ end
+
+ test "password must be present" do
+ assert !@user.valid?
+ assert_equal 1, @user.errors.size
+ end
+
+ test "password must match confirmation" do
+ @user.password = "thiswillberight"
+ @user.password_confirmation = "wrong"
+
+ assert !@user.valid?
+
+ @user.password_confirmation = "thiswillberight"
+
+ assert @user.valid?
+ end
+
+ test "authenticate" do
+ @user.password = "secret"
+
+ assert !@user.authenticate("wrong")
+ assert @user.authenticate("secret")
+ end
+
+ test "visitor#password_digest should be protected against mass assignment" do
+ assert Visitor.active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::BlackList)
+ assert Visitor.active_authorizer.include?(:password_digest)
+ end
+
+ test "Administrator's mass_assignment_authorizer should be WhiteList" do
+ assert Administrator.active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::WhiteList)
+ assert !Administrator.active_authorizer.include?(:password_digest)
+ assert Administrator.active_authorizer.include?(:name)
+ end
+end
diff --git a/activemodel/test/cases/serialization_test.rb b/activemodel/test/cases/serialization_test.rb
new file mode 100644
index 0000000000..8cc1ccb1e7
--- /dev/null
+++ b/activemodel/test/cases/serialization_test.rb
@@ -0,0 +1,45 @@
+require "cases/helper"
+
+class SerializationTest < ActiveModel::TestCase
+ class User
+ include ActiveModel::Serialization
+
+ attr_accessor :name, :email, :gender
+
+ def attributes
+ @attributes ||= {'name' => 'nil', 'email' => 'nil', 'gender' => 'nil'}
+ end
+
+ def foo
+ 'i_am_foo'
+ end
+ end
+
+ setup do
+ @user = User.new
+ @user.name = 'David'
+ @user.email = 'david@example.com'
+ @user.gender = 'male'
+ end
+
+ def test_method_serializable_hash_should_work
+ expected = {"name"=>"David", "gender"=>"male", "email"=>"david@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@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@example.com"}
+ assert_equal expected , @user.serializable_hash(:methods => [:foo])
+ end
+
+end
diff --git a/activemodel/test/cases/serializeration/json_serialization_test.rb b/activemodel/test/cases/serializeration/json_serialization_test.rb
index 1ac991a8f1..500a5c575f 100644
--- a/activemodel/test/cases/serializeration/json_serialization_test.rb
+++ b/activemodel/test/cases/serializeration/json_serialization_test.rb
@@ -1,10 +1,12 @@
require 'cases/helper'
require 'models/contact'
+require 'models/automobile'
require 'active_support/core_ext/object/instance_variables'
class Contact
extend ActiveModel::Naming
include ActiveModel::Serializers::JSON
+ include ActiveModel::Validations
def attributes
instance_values
@@ -104,16 +106,43 @@ class JsonSerializationTest < ActiveModel::TestCase
end
test "should return OrderedHash for errors" do
- car = Automobile.new
-
- # run the validation
- car.valid?
-
+ 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 = ActiveSupport::OrderedHash.new
- hash[:make] = "can't be blank"
- hash[:model] = "is too short (minimum is 2 characters)"
- assert_equal hash.to_json, car.errors.to_json
+ 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" do
+ 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 "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
+
end
diff --git a/activemodel/test/cases/serializeration/xml_serialization_test.rb b/activemodel/test/cases/serializeration/xml_serialization_test.rb
index ff786658b7..b6a2f88667 100644
--- a/activemodel/test/cases/serializeration/xml_serialization_test.rb
+++ b/activemodel/test/cases/serializeration/xml_serialization_test.rb
@@ -70,6 +70,13 @@ class XmlSerializationTest < ActiveModel::TestCase
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 allow skipped types" do
@xml = @contact.to_xml :skip_types => true
assert_match %r{<age>25</age>}, @xml
@@ -107,7 +114,7 @@ class XmlSerializationTest < ActiveModel::TestCase
end
test "should serialize yaml" do
- assert_match %r{<preferences type=\"yaml\">--- !ruby/struct:Customer \nname: John\n</preferences>}, @contact.to_xml
+ assert_match %r{<preferences type=\"yaml\">--- !ruby/struct:Customer(\s*)\nname: John\n</preferences>}, @contact.to_xml
end
test "should call proc on object" do
diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb
index e25d308ca1..1b1d972d5c 100644
--- a/activemodel/test/cases/translation_test.rb
+++ b/activemodel/test/cases/translation_test.rb
@@ -6,7 +6,7 @@ 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')
@@ -16,7 +16,24 @@ class ActiveModelI18nTests < ActiveModel::TestCase
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)
@@ -32,6 +49,13 @@ class ActiveModelI18nTests < ActiveModel::TestCase
assert_equal 'person name attribute', Child.human_attribute_name('name')
end
+ def test_translated_model_attributes_with_attribute_matching_namespaced_model_name
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:gender => 'person gender'}, :"person/gender" => {:attribute => 'person gender attribute'}}}
+
+ assert_equal 'person gender', Person.human_attribute_name('gender')
+ assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute')
+ end
+
def test_translated_model_names
I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
assert_equal 'person model', Person.model_name.human
@@ -46,5 +70,11 @@ class ActiveModelI18nTests < ActiveModel::TestCase
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
end
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index 0716b4f087..62f2ec785d 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -10,6 +10,15 @@ class InclusionValidationTest < ActiveModel::TestCase
Topic.reset_callbacks(:validate)
end
+ def test_validates_inclusion_of_range
+ Topic.validates_inclusion_of( :title, :in => 'aaa'..'bbb' )
+ assert Topic.new("title" => "bbc", "content" => "abc").invalid?
+ assert Topic.new("title" => "aa", "content" => "abc").invalid?
+ assert Topic.new("title" => "aaa", "content" => "abc").valid?
+ assert Topic.new("title" => "abc", "content" => "abc").valid?
+ assert Topic.new("title" => "bbb", "content" => "abc").valid?
+ end
+
def test_validates_inclusion_of
Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
index 1e6180a938..f02514639b 100644
--- a/activemodel/test/cases/validations/length_validation_test.rb
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -342,6 +342,17 @@ class LengthValidationTest < ActiveModel::TestCase
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
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
index e1d7d40c47..08f6169ca5 100644
--- a/activemodel/test/cases/validations/numericality_validation_test.rb
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -14,7 +14,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
NIL = [nil]
BLANK = ["", " ", " \t \r \n"]
- BIGDECIMAL_STRINGS = %w(12345678901234567890.1234567890) # 30 significent digits
+ 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
diff --git a/activemodel/test/cases/validations/validates_test.rb b/activemodel/test/cases/validations/validates_test.rb
index b85e491a9c..779f6c8448 100644
--- a/activemodel/test/cases/validations/validates_test.rb
+++ b/activemodel/test/cases/validations/validates_test.rb
@@ -1,8 +1,10 @@
# encoding: utf-8
require 'cases/helper'
require 'models/person'
+require 'models/topic'
require 'models/person_with_validator'
require 'validators/email_validator'
+require 'validators/namespace/email_validator'
class ValidatesTest < ActiveModel::TestCase
setup :reset_callbacks
@@ -10,6 +12,7 @@ class ValidatesTest < ActiveModel::TestCase
def reset_callbacks
Person.reset_callbacks(:validate)
+ Topic.reset_callbacks(:validate)
PersonWithValidator.reset_callbacks(:validate)
end
@@ -20,13 +23,24 @@ class ValidatesTest < ActiveModel::TestCase
assert_equal ['is not a number'], person.errors[:title]
end
+ def test_validates_with_attribute_specified_as_string
+ Person.validates "title", :numericality => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not a number'], person.errors[:title]
+
+ person = Person.new
+ person.title = 123
+ assert person.valid?
+ end
+
def test_validates_with_built_in_validation_and_options
Person.validates :salary, :numericality => { :message => 'my custom message' }
person = Person.new
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
@@ -34,6 +48,13 @@ class ValidatesTest < ActiveModel::TestCase
assert_equal ['is not an email'], person.errors[:karma]
end
+ def test_validates_with_namespaced_validator_class
+ Person.validates :karma, :'namespace/email' => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not an email'], person.errors[:karma]
+ end
+
def test_validates_with_if_as_local_conditions
Person.validates :karma, :presence => true, :email => { :unless => :condition_is_true }
person = Person.new
@@ -93,22 +114,40 @@ class ValidatesTest < ActiveModel::TestCase
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]
+ end
end
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index 6d825cd316..07c1bd0533 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -171,4 +171,25 @@ class ValidatesWithTest < ActiveModel::TestCase
assert topic.errors[:title].empty?
assert topic.errors[:content].empty?
end
+
+ test "validates_with can validate with an instance method" do
+ Topic.validates :title, :with => :my_validation
+
+ topic = Topic.new :title => "foo"
+ assert topic.valid?
+ assert topic.errors[:title].empty?
+
+ topic = Topic.new
+ assert !topic.valid?
+ assert_equal ['is missing'], topic.errors[:title]
+ end
+
+ test "optionally pass in the attribute being validated when validating with an instance method" do
+ Topic.validates :title, :content, :with => :my_validation_with_arg
+
+ topic = Topic.new :title => "foo"
+ assert !topic.valid?
+ assert topic.errors[:title].empty?
+ assert_equal ['is missing'], topic.errors[:content]
+ end
end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index 8d6bdeb6a5..2f36195627 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -25,9 +25,11 @@ class ValidationsTest < ActiveModel::TestCase
r = Reply.new
r.title = "There's no content!"
assert r.invalid?, "A reply without content shouldn't be saveable"
+ assert r.after_validation_performed, "after_validation callback should be called"
r.content = "Messa content!"
assert r.valid?, "A reply with content should be saveable"
+ assert r.after_validation_performed, "after_validation callback should be called"
end
def test_single_attr_validation_and_error_msg
@@ -146,6 +148,14 @@ class ValidationsTest < ActiveModel::TestCase
end
def test_validate_block
+ Topic.validate { errors.add("title", "will never be valid") }
+ t = Topic.new("title" => "Title", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["will never be valid"], t.errors["title"]
+ end
+
+ def test_validate_block_with_params
Topic.validate { |topic| topic.errors.add("title", "will never be valid") }
t = Topic.new("title" => "Title", "content" => "whatever")
assert t.invalid?
@@ -170,10 +180,10 @@ class ValidationsTest < ActiveModel::TestCase
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 = ActiveSupport::OrderedHash.new
- hash[:title] = "can't be blank"
- hash[:content] = "can't be blank"
+ hash[:title] = ["can't be blank"]
+ hash[:content] = ["can't be blank"]
assert_equal t.errors.to_json, hash.to_json
end
@@ -185,7 +195,7 @@ class ValidationsTest < ActiveModel::TestCase
assert t.invalid?
assert_equal "can't be blank", t.errors["title"].first
Topic.validates_presence_of :title, :author_name
- Topic.validate {|topic| topic.errors.add('author_email_address', 'will never be valid')}
+ Topic.validate {errors.add('author_email_address', 'will never be valid')}
Topic.validates_length_of :title, :content, :minimum => 2
t = Topic.new :title => ''
@@ -213,42 +223,6 @@ class ValidationsTest < ActiveModel::TestCase
assert !t.invalid?
end
- def test_deprecated_error_messages_on
- Topic.validates_presence_of :title
-
- t = Topic.new
- assert t.invalid?
-
- [:title, "title"].each do |attribute|
- assert_deprecated { assert_equal "can't be blank", t.errors.on(attribute) }
- end
-
- Topic.validates_each(:title) do |record, attribute|
- record.errors[attribute] << "invalid"
- end
-
- assert t.invalid?
-
- [:title, "title"].each do |attribute|
- assert_deprecated do
- assert t.errors.on(attribute).include?("invalid")
- assert t.errors.on(attribute).include?("can't be blank")
- end
- end
- end
-
- def test_deprecated_errors_on_base_and_each
- t = Topic.new
- assert t.valid?
-
- assert_deprecated { t.errors.add_to_base "invalid topic" }
- assert_deprecated { assert_equal "invalid topic", t.errors.on_base }
- assert_deprecated { assert t.errors.invalid?(:base) }
-
- all_errors = t.errors.to_a
- assert_deprecated { assert_equal all_errors, t.errors.each_full{|err| err} }
- end
-
def test_validation_with_message_as_proc
Topic.validates_presence_of(:title, :message => proc { "no blanks here".upcase })
@@ -280,6 +254,24 @@ class ValidationsTest < ActiveModel::TestCase
assert_equal 10, Topic.validators_on(:title).first.options[:minimum]
end
+ def test_list_of_validators_on_multiple_attributes
+ Topic.validates :title, :length => { :minimum => 10 }
+ Topic.validates :author_name, :presence => true, :format => /a/
+
+ validators = Topic.validators_on(:title, :author_name)
+
+ assert_equal [
+ ActiveModel::Validations::FormatValidator,
+ ActiveModel::Validations::LengthValidator,
+ ActiveModel::Validations::PresenceValidator
+ ], validators.map { |v| v.class }.sort_by { |c| c.to_s }
+ end
+
+ def test_list_of_validators_will_be_empty_when_empty
+ Topic.validates :title, :length => { :minimum => 10 }
+ assert_equal [], Topic.validators_on(:author_name)
+ end
+
def test_validations_on_the_instance_level
auto = Automobile.new
diff --git a/activemodel/test/models/administrator.rb b/activemodel/test/models/administrator.rb
new file mode 100644
index 0000000000..a48f8b064f
--- /dev/null
+++ b/activemodel/test/models/administrator.rb
@@ -0,0 +1,10 @@
+class Administrator
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+ include ActiveModel::MassAssignmentSecurity
+
+ attr_accessor :name, :password_digest
+ attr_accessible :name
+
+ has_secure_password
+end
diff --git a/activemodel/test/models/blog_post.rb b/activemodel/test/models/blog_post.rb
new file mode 100644
index 0000000000..d289177259
--- /dev/null
+++ b/activemodel/test/models/blog_post.rb
@@ -0,0 +1,13 @@
+module Blog
+ def self._railtie
+ Object.new
+ end
+
+ def self.table_name_prefix
+ "blog_"
+ end
+
+ class Post
+ extend ActiveModel::Naming
+ end
+end
diff --git a/activemodel/test/models/custom_reader.rb b/activemodel/test/models/custom_reader.rb
index 14a8be9ebc..2fbcf79c3d 100644
--- a/activemodel/test/models/custom_reader.rb
+++ b/activemodel/test/models/custom_reader.rb
@@ -4,11 +4,11 @@ class CustomReader
def initialize(data = {})
@data = data
end
-
+
def []=(key, value)
@data[key] = value
end
-
+
def read_attribute_for_validation(key)
@data[key]
end
diff --git a/activemodel/test/models/person.rb b/activemodel/test/models/person.rb
index cf16a38618..e896e90f98 100644
--- a/activemodel/test/models/person.rb
+++ b/activemodel/test/models/person.rb
@@ -9,5 +9,9 @@ class Person
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
index f9763ea853..505ed880c1 100644
--- a/activemodel/test/models/person_with_validator.rb
+++ b/activemodel/test/models/person_with_validator.rb
@@ -1,11 +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/sheep.rb b/activemodel/test/models/sheep.rb
index 175dbe6477..7aba055c4f 100644
--- a/activemodel/test/models/sheep.rb
+++ b/activemodel/test/models/sheep.rb
@@ -1,4 +1,3 @@
class Sheep
extend ActiveModel::Naming
end
- \ No newline at end of file
diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb
index f25b774cd7..c9af78f595 100644
--- a/activemodel/test/models/topic.rb
+++ b/activemodel/test/models/topic.rb
@@ -1,7 +1,15 @@
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|
@@ -16,4 +24,17 @@ class Topic
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
index d137e4ff8f..768c96ecf0 100644
--- a/activemodel/test/models/track_back.rb
+++ b/activemodel/test/models/track_back.rb
@@ -1,4 +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 0000000000..e221bb8091
--- /dev/null
+++ b/activemodel/test/models/user.rb
@@ -0,0 +1,8 @@
+class User
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+
+ has_secure_password
+
+ attr_accessor :password_digest, :password_salt
+end
diff --git a/activemodel/test/models/visitor.rb b/activemodel/test/models/visitor.rb
new file mode 100644
index 0000000000..36c0a16688
--- /dev/null
+++ b/activemodel/test/models/visitor.rb
@@ -0,0 +1,9 @@
+class Visitor
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+ include ActiveModel::MassAssignmentSecurity
+
+ has_secure_password
+
+ attr_accessor :password_digest
+end
diff --git a/activemodel/test/validators/namespace/email_validator.rb b/activemodel/test/validators/namespace/email_validator.rb
new file mode 100644
index 0000000000..57e2793ce2
--- /dev/null
+++ b/activemodel/test/validators/namespace/email_validator.rb
@@ -0,0 +1,6 @@
+require 'validators/email_validator'
+
+module Namespace
+ class EmailValidator < ::EmailValidator
+ end
+end
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index 20b2286fc0..6be46349fb 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -1,4 +1,273 @@
-*Rails 3.0.0 [release candidate] (July 26th, 2010)*
+*Rails 3.1.0 (unreleased)*
+
+* Associations with a :through option can now use *any* association as the
+ through or source association, including other associations which have a
+ :through option and has_and_belongs_to_many associations
+
+ [Jon Leighton]
+
+* The configuration for the current database connection is now accessible via
+ ActiveRecord::Base.connection_config. [fxn]
+
+* limits and offsets are removed from COUNT queries unless both are supplied.
+ For example:
+
+ People.limit(1).count # => 'SELECT COUNT(*) FROM people'
+ People.offset(1).count # => 'SELECT COUNT(*) FROM people'
+ People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'
+
+ [lighthouse #6262]
+
+* ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class
+ (and subclasses) which are responsible for operating on associations, and then a separate,
+ thin wrapper called CollectionProxy, which proxies collection associations.
+
+ This prevents namespace pollution, separates concerns, and will allow further refactorings.
+
+ Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return
+ the associated record or nil. This means that you should not use undocumented methods such
+ as bob.mother.create - use bob.create_mother instead.
+
+ [Jon Leighton]
+
+* Make has_many :through associations work correctly when you build a record and then save it. This
+ requires you to set the :inverse_of option on the source reflection on the join model, like so:
+
+ class Post < ActiveRecord::Base
+ has_many :taggings
+ has_many :tags, :through => :taggings
+ end
+
+ class Tagging < ActiveRecord::Base
+ belongs_to :post
+ belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set!
+ end
+
+ class Tag < ActiveRecord::Base
+ has_many :taggings
+ has_many :posts, :through => :taggings
+ end
+
+ post = Post.first
+ tag = post.tags.build :name => "ruby"
+ tag.save # will save a Taggable linking to the post
+
+ [Jon Leighton]
+
+* Support the :dependent option on has_many :through associations. For historical and practical
+ reasons, :delete_all is the default deletion strategy employed by association.delete(*records),
+ despite the fact that the default strategy is :nullify for regular has_many. Also, this only
+ works at all if the source reflection is a belongs_to. For other situations, you should directly
+ modify the through association.
+
+ [Jon Leighton]
+
+* Changed the behaviour of association.destroy for has_and_belongs_to_many and has_many :through.
+ From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link',
+ not (necessarily) 'get rid of the associated records'.
+
+ Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It
+ would not delete any records in the join table. Now, it deletes the records in the join table.
+
+ Previously, has_many_through.destroy(*records) would destroy the records themselves, and the
+ records in the join table. [Note: This has not always been the case; previous version of Rails
+ only deleted the records themselves.] Now, it destroys only the records in the join table.
+
+ Note that this change is backwards-incompatible to an extent, but there is unfortunately no
+ way to 'deprecate' it before changing it. The change is being made in order to have
+ consistency as to the meaning of 'destroy' or 'delete' across the different types of associations.
+
+ If you wish to destroy the records themselves, you can do records.association.each(&:destroy)
+
+ [Jon Leighton]
+
+* Add :bulk => true option to change_table to make all the schema changes defined in change_table block using a single ALTER statement. [Pratik Naik]
+
+ Example:
+
+ change_table(:users, :bulk => true) do |t|
+ t.string :company_name
+ t.change :birthdate, :datetime
+ end
+
+ This will now result in:
+
+ ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL
+
+* Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been
+ documented as deprecated behaviour since April 2006. Please use has_many :through instead.
+ [Jon Leighton]
+
+* Added a create_association! method for has_one and belongs_to associations. [Jon Leighton]
+
+* Migration files generated from model and constructive migration generators
+ (for example, add_name_to_users) use the reversible migration's `change`
+ method instead of the ordinary `up` and `down` methods. [Prem Sichanugrist]
+
+* Removed support for interpolating string SQL conditions on associations. Instead, you should
+ use a proc, like so:
+
+ Before:
+
+ has_many :things, :conditions => 'foo = #{bar}'
+
+ After:
+
+ has_many :things, :conditions => proc { "foo = #{bar}" }
+
+ Inside the proc, 'self' is the object which is the owner of the association, unless you are
+ eager loading the association, in which case 'self' is the class which the association is within.
+
+ You can have any "normal" conditions inside the proc, so the following will work too:
+
+ has_many :things, :conditions => proc { ["foo = ?", bar] }
+
+ Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call
+ 'record' to get the record being inserted or deleted. This is now passed as an argument to
+ the proc.
+
+* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example:
+
+ # Schema: User(name:string, password_digest:string, password_salt:string)
+ class User < ActiveRecord::Base
+ has_secure_password
+ end
+
+ user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
+ user.save # => false, password required
+ user.password = "mUc3m00RsqyRe"
+ user.save # => false, confirmation doesn't match
+ user.password_confirmation = "mUc3m00RsqyRe"
+ user.save # => true
+ user.authenticate("notright") # => false
+ user.authenticate("mUc3m00RsqyRe") # => user
+ User.find_by_name("david").try(:authenticate, "notright") # => nil
+ User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user
+
+
+* When a model is generated add_index is added by default for belongs_to or references columns
+
+ rails g model post user:belongs_to will generate the following:
+
+ class CreatePosts < ActiveRecord::Migration
+ def up
+ create_table :posts do |t|
+ t.belongs_to :user
+
+ t.timestamps
+ end
+
+ add_index :posts, :user_id
+ end
+
+ def down
+ drop_table :posts
+ end
+ end
+
+ [Santiago Pastorino]
+
+* Setting the id of a belongs_to object will update the reference to the
+object. [#2989 state:resolved]
+
+* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed
+to closer match normal Ruby dup and clone semantics.
+
+* Calling ActiveRecord::Base#clone will result in a shallow copy of the record,
+including copying the frozen state. No callbacks will be called.
+
+* Calling ActiveRecord::Base#dup will duplicate the record, including calling
+after initialize hooks. Frozen state will not be copied, and all associations
+will be cleared. A duped record will return true for new_record?, have a nil
+id field, and is saveable.
+
+* Migrations can be defined as reversible, meaning that the migration system
+will figure out how to reverse your migration. To use reversible migrations,
+just define the "change" method. For example:
+
+ class MyMigration < ActiveRecord::Migration
+ def change
+ create_table(:horses) do
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+ end
+
+Some things cannot be automatically reversed for you. If you know how to
+reverse those things, you should define 'up' and 'down' in your migration. If
+you define something in `change` that cannot be reversed, an
+IrreversibleMigration exception will be raised when going down.
+
+* Migrations should use instance methods rather than class methods:
+ class FooMigration < ActiveRecord::Migration
+ def up
+ ...
+ end
+ end
+
+ [Aaron Patterson]
+
+* has_one maintains the association with separate after_create/after_update instead
+ of a single after_save. [fxn]
+
+* The following code:
+
+ Model.limit(10).scoping { Model.count }
+
+ now generates the following SQL:
+
+ SELECT COUNT(*) FROM models LIMIT 10
+
+ This may not return what you want. Instead, you may with to do something
+ like this:
+
+ Model.limit(10).scoping { Model.all.size }
+
+ [Aaron Patterson]
+
+
+*Rails 3.0.3 (November 16, 2010)*
+
+* Support find by class like this: Post.where(:name => Post)
+
+
+*Rails 3.0.2 (November 15, 2010)*
+
+* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) [Aaron Patterson]
+
+* reorder is deprecated in favor of except(:order).order(...) [Santiago Pastorino]
+
+* except is now AR public API
+
+ Model.order('name').except(:order).order('salary')
+
+ generates:
+
+ SELECT * FROM models ORDER BY salary
+
+ [Santiago Pastorino]
+
+* The following code:
+
+ Model.limit(10).scoping { Model.count }
+
+ now generates the following SQL:
+
+ SELECT COUNT(*) FROM models LIMIT 10
+
+ This may not return what you want. Instead, you may with to do something
+ like this:
+
+ Model.limit(10).scoping { Model.all.size }
+
+ [Aaron Patterson]
+
+*Rails 3.0.1 (October 15, 2010)*
+
+* Introduce a fix for CVE-2010-3993
+
+*Rails 3.0.0 (August 29, 2010)*
* Changed update_attribute to not run callbacks and update the record directly in the database [Neeraj Singh]
@@ -10,9 +279,6 @@
* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 [Aaron Patterson]
-
-*Rails 3.0.0 [beta 4] (June 8th, 2010)*
-
* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 [Andrew Bloomgarden, Andrew White]
* Add index length support for MySQL. #1852 [Emili Parreno, Pratik Naik]
@@ -37,9 +303,6 @@
* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 [Mislav Marohnić]
-
-*Rails 3.0.0 [beta 3] (April 13th, 2010)*
-
* Add Relation extensions. [Pratik Naik]
users = User.where(:admin => true).extending(User::AdminPowers)
@@ -54,9 +317,6 @@
* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development [DHH]
-
-*Rails 3.0.0 [Beta 1] (February 4th, 2010)*
-
* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 [Jack Christensen]
* Allow relations to be used as scope.
@@ -966,7 +1226,7 @@ during calendar reform. #7649, #7724 [fedot, Geoff Buesing]
* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method [Jamis Buck]
* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however [Tobias Lütke]
- Task.cache { Task.find(1); Task.find(1) } #=> 1 query
+ Task.cache { Task.find(1); Task.find(1) } # => 1 query
* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. [Jamis Buck]
@@ -2039,7 +2299,7 @@ during calendar reform. #7649, #7724 [fedot, Geoff Buesing]
end
end
-* Fixed that schema changes while the database was open would break any connections to a SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson]
+* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson]
* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney]
@@ -3554,7 +3814,7 @@ in effect. Added :readonly finder constraint. Calling an association collectio
end
end
-* Fixed that schema changes while the database was open would break any connections to a SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson]
+* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson]
* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney]
@@ -5218,7 +5478,7 @@ in effect. Added :readonly finder constraint. Calling an association collectio
NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox.
-* Added validation macros to make the stackable just like the lifecycle callbacks. Examples:
+* Added validation macros to make the stackable just like the life cycle callbacks. Examples:
class Person < ActiveRecord::Base
validate { |record| record.errors.add("name", "too short") unless name.size > 10 }
diff --git a/activerecord/MIT-LICENSE b/activerecord/MIT-LICENSE
index 86bcb23b7c..c73d1af096 100644
--- a/activerecord/MIT-LICENSE
+++ b/activerecord/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc
index 8dbd6c82b5..a27640eac9 100644
--- a/activerecord/README.rdoc
+++ b/activerecord/README.rdoc
@@ -19,19 +19,19 @@ A short rundown of some of the major features:
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]
@@ -51,7 +51,7 @@ A short rundown of some of the major features:
class Account < ActiveRecord::Base
composed_of :balance, :class_name => "Money",
:mapping => %w(balance amount)
- composed_of :address,
+ composed_of :address,
:mapping => [%w(address_street street), %w(address_city city)]
end
@@ -70,7 +70,7 @@ A short rundown of some of the major features:
{Learn more}[link:classes/ActiveRecord/Validations.html]
-* Callbacks available for the entire lifecycle (instantiation, saving, destroying, validating, etc.)
+* Callbacks available for the entire life cycle (instantiation, saving, destroying, validating, etc.)
class Person < ActiveRecord::Base
before_destroy :invalidate_payment_plan
@@ -84,14 +84,14 @@ A short rundown of some of the major features:
class CommentObserver < ActiveRecord::Observer
def after_create(comment) # is called just after Comment#save
- Notifications.deliver_new_comment("david@loudthinking.com", comment)
+ CommentMailer.new_comment_email("david@loudthinking.com", comment)
end
end
{Learn more}[link:classes/ActiveRecord/Observer.html]
-* Inheritance hierarchies
+* Inheritance hierarchies
class Company < ActiveRecord::Base; end
class Firm < Company; end
@@ -128,7 +128,7 @@ A short rundown of some of the major features:
# connect to MySQL with authentication
ActiveRecord::Base.establish_connection(
- :adapter => "mysql",
+ :adapter => "mysql2",
:host => "localhost",
:username => "me",
:password => "secret",
@@ -170,7 +170,7 @@ A short rundown of some of the major features:
{Learn more}[link:classes/ActiveRecord/Migration.html]
-== Philosophy
+== Philosophy
Active Record is an implementation of the object-relational mapping (ORM)
pattern[http://www.martinfowler.com/eaaCatalog/activeRecord.html] by the same
@@ -179,7 +179,7 @@ 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
+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
@@ -188,7 +188,7 @@ 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
+* Magic is not inherently a bad word
Admit the Database:
* Lets you drop down to SQL for odd cases and performance
@@ -203,7 +203,7 @@ The latest version of Active Record can be installed with Rubygems:
Source code can be downloaded as part of the Rails project on GitHub
-* http://github.com/rails/rails/tree/master/activerecord/
+* https://github.com/rails/rails/tree/master/activerecord/
== License
diff --git a/activerecord/RUNNING_UNIT_TESTS b/activerecord/RUNNING_UNIT_TESTS
index 03e561a50b..b3d376772e 100644
--- a/activerecord/RUNNING_UNIT_TESTS
+++ b/activerecord/RUNNING_UNIT_TESTS
@@ -1,13 +1,13 @@
== Creating the test database
-The default names for the test databases are "activerecord_unittest" and
-"activerecord_unittest2". If you want to use another database name then be sure
-to update the connection adapter setups you want to test with in
-test/connections/<your database>/connection.rb.
-When you have the database online, you can import the fixture tables with
+The default names for the test databases are "activerecord_unittest" and
+"activerecord_unittest2". If you want to use another database name, then be sure
+to update the connection adapter setups you want to test within
+test/connections/<your database>/connection.rb.
+When you have the database online, you can import the fixture tables with
the test/schema/*.sql files.
-Make sure that you create database objects with the same user that you specified in
+Make sure that you create database objects with the same user that you specified in
connection.rb otherwise (on Postgres, at least) tests for default values will fail.
== Running with Rake
@@ -22,17 +22,22 @@ Rake can be found at http://rake.rubyforge.org
== Running by hand
-Unit tests are located in test/cases directory. If you only want to run a single test suite,
+Unit tests are located in test/cases directory. If you only want to run a single test suite,
you can do so with:
rake test_mysql TEST=test/cases/base_test.rb
-
+
That'll run the base suite using the MySQL-Ruby adapter. Some tests rely on the schema
being initialized - you can initialize the schema with:
rake test_mysql TEST=test/cases/aaa_create_tables_test.rb
+ rake mysql:build_databases
+
+To setup the testing environment for PostgreSQL use this command:
+
+ rake postgresql:build_databases
The incantation for running a particular test looks like this
- ruby -w -I"lib:test:test/connections/native_postgresql" test/cases/datatype_test_postgresql.rb -n test_timestamp_with_zone_values_without_rails_time_zone_support
+ rake test TEST=test/cases/datatype_test_postgresql.rb TESTOPTS="-n test_timestamp_with_zone_values_without_rails_time_zone_support"
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
index c1e90cc099..e414c4fb1c 100644..100755
--- a/activerecord/Rakefile
+++ b/activerecord/Rakefile
@@ -1,8 +1,5 @@
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
-require 'rake'
+#!/usr/bin/env rake
require 'rake/testtask'
-require 'rdoc/task'
require 'rake/packagetask'
require 'rake/gempackagetask'
@@ -44,7 +41,7 @@ namespace :test do
end
end
-%w( mysql mysql2 postgresql sqlite3 firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
+%w( mysql mysql2 postgresql sqlite3 sqlite3_mem firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
Rake::TestTask.new("test_#{adapter}") { |t|
connection_path = "test/connections/#{adapter =~ /jdbc/ ? 'jdbc' : 'native'}_#{adapter}"
adapter_short = adapter == 'db2' ? adapter : adapter[/^[a-z0-9]+/]
@@ -65,7 +62,7 @@ end
(Dir["test/cases/**/*_test.rb"].reject {
|x| x =~ /\/adapters\//
} + Dir["test/cases/adapters/#{adapter_short}/**/*_test.rb"]).all? do |file|
- system(ruby, "-Ilib:test:#{connection_path}", file)
+ sh(ruby, "-Ilib:test:#{connection_path}", file)
end or raise "Failures"
end
@@ -75,11 +72,20 @@ end
end
end
+rule '.sqlite3' do |t|
+ sh %Q{sqlite3 "#{t.name}" "create table a (a integer); drop table a;"}
+end
+
+task :test_sqlite3 => [
+ 'test/fixtures/fixture_database.sqlite3',
+ 'test/fixtures/fixture_database_2.sqlite3'
+]
+
namespace :mysql do
desc 'Build the MySQL test databases'
task :build_databases do
- %x( echo "create DATABASE activerecord_unittest DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci " | mysql --user=#{MYSQL_DB_USER})
- %x( echo "create DATABASE activerecord_unittest2 DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci " | mysql --user=#{MYSQL_DB_USER})
+ %x( mysql --user=#{MYSQL_DB_USER} -e "create DATABASE activerecord_unittest DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci ")
+ %x( mysql --user=#{MYSQL_DB_USER} -e "create DATABASE activerecord_unittest2 DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci ")
end
desc 'Drop the MySQL test databases'
@@ -163,28 +169,6 @@ end
task :build_frontbase_databases => 'frontbase:build_databases'
task :rebuild_frontbase_databases => 'frontbase:rebuild_databases'
-
-# Generate the RDoc documentation
-
-RDoc::Task.new { |rdoc|
- rdoc.rdoc_dir = 'doc'
- rdoc.title = "Active Record -- Object-relation mapping put on rails"
- rdoc.options << '-f' << 'horo'
- rdoc.options << '--main' << 'README.rdoc'
- rdoc.options << '--charset' << 'utf-8'
- rdoc.rdoc_files.include('README.rdoc', 'RUNNING_UNIT_TESTS', 'CHANGELOG')
- rdoc.rdoc_files.include('lib/**/*.rb')
- rdoc.rdoc_files.exclude('lib/active_record/vendor/*')
- rdoc.rdoc_files.include('dev-utils/*.rb')
-}
-
-# Enhance rdoc task to copy referenced images also
-task :rdoc do
- FileUtils.mkdir_p "doc/files/examples/"
- FileUtils.copy "examples/associations.png", "doc/files/examples/associations.png"
-end
-
-
spec = eval(File.read('activerecord.gemspec'))
Rake::GemPackageTask.new(spec) do |p|
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index 67d521d56b..b1df24844a 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -23,6 +23,6 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
- s.add_dependency('arel', '~> 0.4.0')
- s.add_dependency('tzinfo', '~> 0.3.22')
+ s.add_dependency('arel', '~> 2.0.2')
+ s.add_dependency('tzinfo', '~> 0.3.23')
end
diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb
index a985cfcb66..63822731d5 100644
--- a/activerecord/examples/performance.rb
+++ b/activerecord/examples/performance.rb
@@ -1,31 +1,9 @@
-#!/usr/bin/env ruby -KU
-
TIMES = (ENV['N'] || 10000).to_i
-require 'rubygems'
-
-gem 'addressable', '~>2.0'
-gem 'faker', '~>0.3.1'
-gem 'rbench', '~>0.2.3'
-require 'addressable/uri'
-require 'faker'
-require 'rbench'
-
-require File.expand_path("../../../load_paths", __FILE__)
+require 'rubygems'
require "active_record"
-conn = { :adapter => 'mysql',
- :database => 'activerecord_unittest',
- :username => 'rails', :password => '',
- :encoding => 'utf8' }
-
-conn[:socket] = Pathname.glob(%w[
- /opt/local/var/run/mysql5/mysqld.sock
- /tmp/mysqld.sock
- /tmp/mysql.sock
- /var/mysql/mysql.sock
- /var/run/mysqld/mysqld.sock
-]).find { |path| path.socket? }
+conn = { :adapter => 'sqlite3', :database => ':memory:' }
ActiveRecord::Base.establish_connection(conn)
@@ -55,108 +33,126 @@ class Exhibit < ActiveRecord::Base
def self.feel(exhibits) exhibits.each { |e| e.feel } end
end
-sqlfile = File.expand_path("../performance.sql", __FILE__)
-
-if File.exists?(sqlfile)
- mysql_bin = %w[mysql mysql5].detect { |bin| `which #{bin}`.length > 0 }
- `#{mysql_bin} -u #{conn[:username]} #{"-p#{conn[:password]}" unless conn[:password].blank?} #{conn[:database]} < #{sqlfile}`
-else
- puts 'Generating data...'
-
- # pre-compute the insert statements and fake data compilation,
- # so the benchmarks below show the actual runtime for the execute
- # method, minus the setup steps
-
- # Using the same paragraph for all exhibits because it is very slow
- # to generate unique paragraphs for all exhibits.
- notes = Faker::Lorem.paragraphs.join($/)
- today = Date.today
-
- puts 'Inserting 10,000 users and exhibits...'
- 10_000.times do
- user = User.create(
- :created_at => today,
- :name => Faker::Name.name,
- :email => Faker::Internet.email
- )
-
- Exhibit.create(
- :created_at => today,
- :name => Faker::Company.name,
- :user => user,
- :notes => notes
- )
- end
-
- mysqldump_bin = %w[mysqldump mysqldump5].select { |bin| `which #{bin}`.length > 0 }
- `#{mysqldump_bin} -u #{conn[:username]} #{"-p#{conn[:password]}" unless conn[:password].blank?} #{conn[:database]} exhibits users > #{sqlfile}`
+puts 'Generating data...'
+
+module ActiveRecord
+ class Faker
+ LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. Praesent varius tincidunt commodo".split
+ def self.name
+ LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join ' '
+ end
+
+ def self.email
+ LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join('@') + ".com"
+ end
+ end
+end
+
+# pre-compute the insert statements and fake data compilation,
+# so the benchmarks below show the actual runtime for the execute
+# method, minus the setup steps
+
+# Using the same paragraph for all exhibits because it is very slow
+# to generate unique paragraphs for all exhibits.
+notes = ActiveRecord::Faker::LOREM.join ' '
+today = Date.today
+
+puts 'Inserting 10,000 users and exhibits...'
+10_000.times do
+ user = User.create(
+ :created_at => today,
+ :name => ActiveRecord::Faker.name,
+ :email => ActiveRecord::Faker.email
+ )
+
+ Exhibit.create(
+ :created_at => today,
+ :name => ActiveRecord::Faker.name,
+ :user => user,
+ :notes => notes
+ )
end
-RBench.run(TIMES) do
- column :times
- column :ar
+require 'benchmark'
- report 'Model#id', (TIMES * 100).ceil do
- ar_obj = Exhibit.find(1)
+Benchmark.bm(46) do |x|
+ ar_obj = Exhibit.find(1)
+ attrs = { :name => 'sam' }
+ attrs_first = { :name => 'sam' }
+ attrs_second = { :name => 'tom' }
+ exhibit = {
+ :name => ActiveRecord::Faker.name,
+ :notes => notes,
+ :created_at => Date.today
+ }
- ar { ar_obj.id }
+ x.report("Model#id (x#{(TIMES * 100).ceil})") do
+ (TIMES * 100).ceil.times { ar_obj.id }
end
- report 'Model.new (instantiation)' do
- ar { Exhibit.new }
+ x.report 'Model.new (instantiation)' do
+ TIMES.times { Exhibit.new }
end
- report 'Model.new (setting attributes)' do
- attrs = { :name => 'sam' }
- ar { Exhibit.new(attrs) }
+ x.report 'Model.new (setting attributes)' do
+ TIMES.times { Exhibit.new(attrs) }
end
- report 'Model.first' do
- ar { Exhibit.first.look }
+ x.report 'Model.first' do
+ TIMES.times { Exhibit.first.look }
end
- report 'Model.all limit(100)', (TIMES / 10).ceil do
- ar { Exhibit.look Exhibit.limit(100) }
+ x.report("Model.all limit(100) (x#{(TIMES / 10).ceil})") do
+ (TIMES / 10).ceil.times { Exhibit.look Exhibit.limit(100) }
end
- report 'Model.all limit(100) with relationship', (TIMES / 10).ceil do
- ar { Exhibit.feel Exhibit.limit(100).includes(:user) }
+ x.report "Model.all limit(100) with relationship (x#{(TIMES / 10).ceil})" do
+ (TIMES / 10).ceil.times { Exhibit.feel Exhibit.limit(100).includes(:user) }
end
- report 'Model.all limit(10,000)', (TIMES / 1000).ceil do
- ar { Exhibit.look Exhibit.limit(10000) }
+ x.report "Model.all limit(10,000) x(#{(TIMES / 1000).ceil})" do
+ (TIMES / 1000).ceil.times { Exhibit.look Exhibit.limit(10000) }
end
- exhibit = {
- :name => Faker::Company.name,
- :notes => Faker::Lorem.paragraphs.join($/),
- :created_at => Date.today
- }
+ x.report 'Model.create' do
+ TIMES.times { Exhibit.create(exhibit) }
+ end
- report 'Model.create' do
- ar { Exhibit.create(exhibit) }
+ x.report 'Resource#attributes=' do
+ TIMES.times {
+ exhibit = Exhibit.new(attrs_first)
+ exhibit.attributes = attrs_second
+ }
end
- report 'Resource#attributes=' do
- attrs_first = { :name => 'sam' }
- attrs_second = { :name => 'tom' }
- ar { exhibit = Exhibit.new(attrs_first); exhibit.attributes = attrs_second }
+ x.report 'Resource#update' do
+ TIMES.times { Exhibit.first.update_attributes(:name => 'bob') }
end
- report 'Resource#update' do
- ar { Exhibit.first.update_attributes(:name => 'bob') }
+ x.report 'Resource#destroy' do
+ TIMES.times { Exhibit.first.destroy }
end
- report 'Resource#destroy' do
- ar { Exhibit.first.destroy }
+ x.report 'Model.transaction' do
+ TIMES.times { Exhibit.transaction { Exhibit.new } }
end
- report 'Model.transaction' do
- ar { Exhibit.transaction { Exhibit.new } }
+ x.report 'Model.find(id)' do
+ id = Exhibit.first.id
+ TIMES.times { Exhibit.find(id) }
end
- summary 'Total'
-end
+ x.report 'Model.find_by_sql' do
+ TIMES.times {
+ Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first
+ }
+ end
+
+ x.report "Model.log x(#{TIMES * 10})" do
+ (TIMES * 10).times { Exhibit.connection.send(:log, "hello", "world") {} }
+ end
-ActiveRecord::Migration.drop_table "exhibits"
-ActiveRecord::Migration.drop_table "users"
+ x.report "AR.execute(query) (#{TIMES / 2})" do
+ (TIMES / 2).times { ActiveRecord::Base.connection.execute("Select * from exhibits where id = #{(rand * 1000 + 1).to_i}") }
+ end
+end
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index e2f2508ae8..59cf42a377 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -33,17 +33,16 @@ require 'active_support/i18n'
require 'active_model'
require 'arel'
+require 'active_record/version'
+
module ActiveRecord
extend ActiveSupport::Autoload
eager_autoload do
- autoload :VERSION
-
autoload :ActiveRecordError, 'active_record/errors'
autoload :ConnectionNotEstablished, 'active_record/errors'
autoload :Aggregations
- autoload :AssociationPreload
autoload :Associations
autoload :AttributeMethods
autoload :AutosaveAssociation
@@ -79,6 +78,11 @@ module ActiveRecord
autoload :Timestamp
autoload :Transactions
autoload :Validations
+ autoload :IdentityMap
+ end
+
+ module Coders
+ autoload :YAMLColumn, 'active_record/coders/yaml_column'
end
module AttributeMethods
@@ -118,7 +122,7 @@ module ActiveRecord
end
ActiveSupport.on_load(:active_record) do
- Arel::Table.engine = Arel::Sql::Engine.new(self)
+ Arel::Table.engine = self
end
I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index 83a9ab46c5..90d3b58c78 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -4,17 +4,15 @@ module ActiveRecord
extend ActiveSupport::Concern
def clear_aggregation_cache #:nodoc:
- self.class.reflect_on_all_aggregations.to_a.each do |assoc|
- instance_variable_set "@#{assoc.name}", nil
- end unless self.new_record?
+ @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
+ # 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
@@ -70,9 +68,9 @@ module ActiveRecord
# 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
+ # 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 any other attribute, though:
#
# customer.balance = Money.new(20) # sets the Money value object and the attribute
@@ -82,8 +80,8 @@ module ActiveRecord
# 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.
+ # 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"
@@ -94,42 +92,42 @@ module ActiveRecord
#
# == 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
+ # 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
+ # 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. This
- # is exemplified by the Money#exchange_to method that returns a new value object instead of changing
- # its own values. Active Record won't persist value objects that have been changed through means
+ # 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. This
+ # is exemplified by the Money#exchange_to method that 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
+ # The immutable requirement is enforced by Active Record by freezing any object assigned as a value
# object. Attempting to change it afterwards will result in a ActiveSupport::FrozenObjectError.
#
- # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
+ # 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
+ # 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
+ # 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
+ # 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
@@ -157,38 +155,38 @@ module ActiveRecord
#
# == 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
+ # 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.find(:all, :conditions => {:balance => Money.new(20, "USD")})
+ # Customer.where(:balance => Money.new(20, "USD")).all
#
module ClassMethods
# Adds reader and writer methods for manipulating a value object:
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
#
# Options are:
- # * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
- # can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
- # to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
+ # * <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 the attribute in the value object. The
- # order in which mappings are defined determine the order in which attributes are sent to the
+ # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
+ # object. Each mapping is represented as an array where the first item is the name of the
+ # entity attribute and the second item is the name the attribute in the value object. The
+ # order in which mappings are defined determine the order in which attributes are sent to the
# 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
+ # 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
+ # * <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
+ # * <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>.
#
# Option examples:
@@ -222,53 +220,32 @@ module ActiveRecord
private
def reader_method(name, class_name, mapping, allow_nil, constructor)
- module_eval do
- define_method(name) do |*args|
- force_reload = args.first || false
-
- unless instance_variable_defined?("@#{name}")
- instance_variable_set("@#{name}", nil)
- end
-
- if (instance_variable_get("@#{name}").nil? || force_reload) && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
- attrs = mapping.collect {|pair| read_attribute(pair.first)}
- object = case constructor
- when Symbol
- class_name.constantize.send(constructor, *attrs)
- when Proc, Method
- constructor.call(*attrs)
- else
- raise ArgumentError, 'Constructor must be a symbol denoting the constructor method to call or a Proc to be invoked.'
- end
- instance_variable_set("@#{name}", object)
- end
- instance_variable_get("@#{name}")
+ define_method(name) do
+ if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
+ attrs = mapping.collect {|pair| read_attribute(pair.first)}
+ object = constructor.respond_to?(:call) ?
+ constructor.call(*attrs) :
+ class_name.constantize.send(constructor, *attrs)
+ @aggregation_cache[name] = object
end
+ @aggregation_cache[name]
end
-
end
def writer_method(name, class_name, mapping, allow_nil, converter)
- module_eval do
- define_method("#{name}=") do |part|
- if part.nil? && allow_nil
- mapping.each { |pair| self[pair.first] = nil }
- instance_variable_set("@#{name}", nil)
- else
- unless part.is_a?(class_name.constantize) || converter.nil?
- part = case converter
- when Symbol
- class_name.constantize.send(converter, part)
- when Proc, Method
- converter.call(part)
- else
- raise ArgumentError, 'Converter must be a symbol denoting the converter method to call or a Proc to be invoked.'
- end
- end
-
- mapping.each { |pair| self[pair.first] = part.send(pair.last) }
- instance_variable_set("@#{name}", part.freeze)
+ define_method("#{name}=") do |part|
+ if part.nil? && allow_nil
+ mapping.each { |pair| self[pair.first] = nil }
+ @aggregation_cache[name] = nil
+ else
+ unless part.is_a?(class_name.constantize) || converter.nil?
+ part = converter.respond_to?(:call) ?
+ converter.call(part) :
+ class_name.constantize.send(converter, part)
end
+
+ mapping.each { |pair| self[pair.first] = part.send(pair.last) }
+ @aggregation_cache[name] = part.freeze
end
end
end
diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb
deleted file mode 100644
index 0f0fdc2e21..0000000000
--- a/activerecord/lib/active_record/association_preload.rb
+++ /dev/null
@@ -1,403 +0,0 @@
-require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/enumerable'
-
-module ActiveRecord
- # See ActiveRecord::AssociationPreload::ClassMethods for documentation.
- module AssociationPreload #:nodoc:
- extend ActiveSupport::Concern
-
- # Implements the details of eager loading of Active Record associations.
- # Application developers should not use this module directly.
- #
- # <tt>ActiveRecord::Base</tt> is extended with this module. The source code in
- # <tt>ActiveRecord::Base</tt> references methods defined in this module.
- #
- # Note that 'eager loading' and 'preloading' are actually the same thing.
- # However, there are two different eager loading strategies.
- #
- # The first one is by using table joins. This was only strategy available
- # prior to Rails 2.1. Suppose that you have an Author model with columns
- # 'name' and 'age', and a Book model with columns 'name' and 'sales'. Using
- # this strategy, Active Record would try to retrieve all data for an author
- # and all of its books via a single query:
- #
- # SELECT * FROM authors
- # LEFT OUTER JOIN books ON authors.id = books.id
- # WHERE authors.name = 'Ken Akamatsu'
- #
- # However, this could result in many rows that contain redundant data. After
- # having received the first row, we already have enough data to instantiate
- # the Author object. In all subsequent rows, only the data for the joined
- # 'books' table is useful; the joined 'authors' data is just redundant, and
- # processing this redundant data takes memory and CPU time. The problem
- # quickly becomes worse and worse as the level of eager loading increases
- # (i.e. if Active Record is to eager load the associations' associations as
- # well).
- #
- # The second strategy is to use multiple database queries, one for each
- # level of association. Since Rails 2.1, this is the default strategy. In
- # situations where a table join is necessary (e.g. when the +:conditions+
- # option references an association's column), it will fallback to the table
- # join strategy.
- #
- # See also ActiveRecord::Associations::ClassMethods, which explains eager
- # loading in a more high-level (application developer-friendly) manner.
- module ClassMethods
- protected
-
- # Eager loads the named associations for the given Active Record record(s).
- #
- # In this description, 'association name' shall refer to the name passed
- # to an association creation method. For example, a model that specifies
- # <tt>belongs_to :author</tt>, <tt>has_many :buyers</tt> has association
- # names +:author+ and +:buyers+.
- #
- # == Parameters
- # +records+ is an array of ActiveRecord::Base. This array needs not be flat,
- # i.e. +records+ itself may also contain arrays of records. In any case,
- # +preload_associations+ will preload the all associations records by
- # flattening +records+.
- #
- # +associations+ specifies one or more associations that you want to
- # preload. It may be:
- # - a Symbol or a String which specifies a single association name. For
- # example, specifying +:books+ allows this method to preload all books
- # for an Author.
- # - an Array which specifies multiple association names. This array
- # is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
- # allows this method to preload an author's avatar as well as all of his
- # books.
- # - a Hash which specifies multiple association names, as well as
- # association names for the to-be-preloaded association objects. For
- # example, specifying <tt>{ :author => :avatar }</tt> will preload a
- # book's author, as well as that author's avatar.
- #
- # +:associations+ has the same format as the +:include+ option for
- # <tt>ActiveRecord::Base.find</tt>. So +associations+ could look like this:
- #
- # :books
- # [ :books, :author ]
- # { :author => :avatar }
- # [ :books, { :author => :avatar } ]
- #
- # +preload_options+ contains options that will be passed to ActiveRecord::Base#find
- # (which is called under the hood for preloading records). But it is passed
- # only one level deep in the +associations+ argument, i.e. it's not passed
- # to the child associations when +associations+ is a Hash.
- def preload_associations(records, associations, preload_options={})
- records = Array.wrap(records).compact.uniq
- return if records.empty?
- case associations
- when Array then associations.each {|association| preload_associations(records, association, preload_options)}
- when Symbol, String then preload_one_association(records, associations.to_sym, preload_options)
- when Hash then
- associations.each do |parent, child|
- raise "parent must be an association name" unless parent.is_a?(String) || parent.is_a?(Symbol)
- preload_associations(records, parent, preload_options)
- reflection = reflections[parent]
- parents = records.sum { |record| Array.wrap(record.send(reflection.name)) }
- unless parents.empty?
- parents.first.class.preload_associations(parents, child)
- end
- end
- end
- end
-
- private
-
- # Preloads a specific named association for the given records. This is
- # called by +preload_associations+ as its base case.
- def preload_one_association(records, association, preload_options={})
- class_to_reflection = {}
- # Not all records have the same class, so group then preload
- # group on the reflection itself so that if various subclass share the same association then
- # we do not split them unnecessarily
- records.group_by { |record| class_to_reflection[record.class] ||= record.class.reflections[association]}.each do |reflection, _records|
- raise ConfigurationError, "Association named '#{ association }' was not found; perhaps you misspelled it?" unless reflection
-
- # 'reflection.macro' can return 'belongs_to', 'has_many', etc. Thus,
- # the following could call 'preload_belongs_to_association',
- # 'preload_has_many_association', etc.
- send("preload_#{reflection.macro}_association", _records, reflection, preload_options)
- end
- end
-
- def add_preloaded_records_to_collection(parent_records, reflection_name, associated_record)
- parent_records.each do |parent_record|
- association_proxy = parent_record.send(reflection_name)
- association_proxy.loaded
- association_proxy.target.push(*Array.wrap(associated_record))
-
- association_proxy.__send__(:set_inverse_instance, associated_record, parent_record)
- end
- end
-
- def add_preloaded_record_to_collection(parent_records, reflection_name, associated_record)
- parent_records.each do |parent_record|
- parent_record.send("set_#{reflection_name}_target", associated_record)
- end
- end
-
- def set_association_collection_records(id_to_record_map, reflection_name, associated_records, key)
- associated_records.each do |associated_record|
- mapped_records = id_to_record_map[associated_record[key].to_s]
- add_preloaded_records_to_collection(mapped_records, reflection_name, associated_record)
- end
- end
-
- def set_association_single_records(id_to_record_map, reflection_name, associated_records, key)
- seen_keys = {}
- associated_records.each do |associated_record|
- #this is a has_one or belongs_to: there should only be one record.
- #Unfortunately we can't (in portable way) ask the database for
- #'all records where foo_id in (x,y,z), but please
- # only one row per distinct foo_id' so this where we enforce that
- next if seen_keys[associated_record[key].to_s]
- seen_keys[associated_record[key].to_s] = true
- mapped_records = id_to_record_map[associated_record[key].to_s]
- mapped_records.each do |mapped_record|
- association_proxy = mapped_record.send("set_#{reflection_name}_target", associated_record)
- association_proxy.__send__(:set_inverse_instance, associated_record, mapped_record)
- end
- end
-
- id_to_record_map.each do |id, records|
- next if seen_keys.include?(id.to_s)
- records.each {|record| record.send("set_#{reflection_name}_target", nil) }
- end
- end
-
- # Given a collection of Active Record objects, constructs a Hash which maps
- # the objects' IDs to the relevant objects. Returns a 2-tuple
- # <tt>(id_to_record_map, ids)</tt> where +id_to_record_map+ is the Hash,
- # and +ids+ is an Array of record IDs.
- def construct_id_map(records, primary_key=nil)
- id_to_record_map = {}
- ids = []
- records.each do |record|
- primary_key ||= record.class.primary_key
- ids << record[primary_key]
- mapped_records = (id_to_record_map[ids.last.to_s] ||= [])
- mapped_records << record
- end
- ids.uniq!
- return id_to_record_map, ids
- end
-
- def preload_has_and_belongs_to_many_association(records, reflection, preload_options={})
- table_name = reflection.klass.quoted_table_name
- id_to_record_map, ids = construct_id_map(records)
- records.each {|record| record.send(reflection.name).loaded}
- options = reflection.options
-
- conditions = "t0.#{reflection.primary_key_name} #{in_or_equals_for_ids(ids)}"
- conditions << append_conditions(reflection, preload_options)
-
- associated_records = reflection.klass.unscoped.where([conditions, ids]).
- includes(options[:include]).
- joins("INNER JOIN #{connection.quote_table_name options[:join_table]} t0 ON #{reflection.klass.quoted_table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}").
- select("#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as the_parent_record_id").
- order(options[:order]).to_a
-
- set_association_collection_records(id_to_record_map, reflection.name, associated_records, 'the_parent_record_id')
- end
-
- def preload_has_one_association(records, reflection, preload_options={})
- return if records.first.send("loaded_#{reflection.name}?")
- id_to_record_map, ids = construct_id_map(records, reflection.options[:primary_key])
- options = reflection.options
- records.each {|record| record.send("set_#{reflection.name}_target", nil)}
- if options[:through]
- through_records = preload_through_records(records, reflection, options[:through])
- through_reflection = reflections[options[:through]]
- through_primary_key = through_reflection.primary_key_name
- unless through_records.empty?
- source = reflection.source_reflection.name
- through_records.first.class.preload_associations(through_records, source)
- if through_reflection.macro == :belongs_to
- rev_id_to_record_map, rev_ids = construct_id_map(records, through_primary_key)
- rev_primary_key = through_reflection.klass.primary_key
- through_records.each do |through_record|
- add_preloaded_record_to_collection(rev_id_to_record_map[through_record[rev_primary_key].to_s],
- reflection.name, through_record.send(source))
- end
- else
- through_records.each do |through_record|
- add_preloaded_record_to_collection(id_to_record_map[through_record[through_primary_key].to_s],
- reflection.name, through_record.send(source))
- end
- end
- end
- else
- set_association_single_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options), reflection.primary_key_name)
- end
- end
-
- def preload_has_many_association(records, reflection, preload_options={})
- return if records.first.send(reflection.name).loaded?
- options = reflection.options
-
- primary_key_name = reflection.through_reflection_primary_key_name
- id_to_record_map, ids = construct_id_map(records, primary_key_name || reflection.options[:primary_key])
- records.each {|record| record.send(reflection.name).loaded}
-
- if options[:through]
- through_records = preload_through_records(records, reflection, options[:through])
- through_reflection = reflections[options[:through]]
- unless through_records.empty?
- source = reflection.source_reflection.name
- through_records.first.class.preload_associations(through_records, source, options)
- through_records.each do |through_record|
- through_record_id = through_record[reflection.through_reflection_primary_key].to_s
- add_preloaded_records_to_collection(id_to_record_map[through_record_id], reflection.name, through_record.send(source))
- end
- end
-
- else
- set_association_collection_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options),
- reflection.primary_key_name)
- end
- end
-
- def preload_through_records(records, reflection, through_association)
- through_reflection = reflections[through_association]
- through_primary_key = through_reflection.primary_key_name
-
- through_records = []
- if reflection.options[:source_type]
- interface = reflection.source_reflection.options[:foreign_type]
- preload_options = {:conditions => ["#{connection.quote_column_name interface} = ?", reflection.options[:source_type]]}
-
- records.compact!
- records.first.class.preload_associations(records, through_association, preload_options)
-
- # Dont cache the association - we would only be caching a subset
- records.each do |record|
- proxy = record.send(through_association)
-
- if proxy.respond_to?(:target)
- through_records.concat Array.wrap(proxy.target)
- proxy.reset
- else # this is a has_one :through reflection
- through_records << proxy if proxy
- end
- end
- else
- options = {}
- options[:include] = reflection.options[:include] || reflection.options[:source] if reflection.options[:conditions]
- options[:order] = reflection.options[:order]
- options[:conditions] = reflection.options[:conditions]
- records.first.class.preload_associations(records, through_association, options)
-
- records.each do |record|
- through_records.concat Array.wrap(record.send(through_association))
- end
- end
- through_records
- end
-
- def preload_belongs_to_association(records, reflection, preload_options={})
- return if records.first.send("loaded_#{reflection.name}?")
- options = reflection.options
- primary_key_name = reflection.primary_key_name
-
- if options[:polymorphic]
- polymorph_type = options[:foreign_type]
- klasses_and_ids = {}
-
- # Construct a mapping from klass to a list of ids to load and a mapping of those ids back
- # to their parent_records
- records.each do |record|
- if klass = record.send(polymorph_type)
- klass_id = record.send(primary_key_name)
- if klass_id
- id_map = klasses_and_ids[klass] ||= {}
- id_list_for_klass_id = (id_map[klass_id.to_s] ||= [])
- id_list_for_klass_id << record
- end
- end
- end
- klasses_and_ids = klasses_and_ids.to_a
- else
- id_map = {}
- records.each do |record|
- key = record.send(primary_key_name)
- if key
- mapped_records = (id_map[key.to_s] ||= [])
- mapped_records << record
- end
- end
- klasses_and_ids = [[reflection.klass.name, id_map]]
- end
-
- klasses_and_ids.each do |klass_and_id|
- klass_name, id_map = *klass_and_id
- next if id_map.empty?
- klass = klass_name.constantize
-
- table_name = klass.quoted_table_name
- primary_key = reflection.options[:primary_key] || klass.primary_key
- column_type = klass.columns.detect{|c| c.name == primary_key}.type
-
- ids = id_map.keys.map do |id|
- if column_type == :integer
- id.to_i
- elsif column_type == :float
- id.to_f
- else
- id
- end
- end
-
- conditions = "#{table_name}.#{connection.quote_column_name(primary_key)} #{in_or_equals_for_ids(ids)}"
- conditions << append_conditions(reflection, preload_options)
-
- associated_records = klass.unscoped.where([conditions, ids]).apply_finder_options(options.slice(:include, :select, :joins, :order)).to_a
-
- set_association_single_records(id_map, reflection.name, associated_records, primary_key)
- end
- end
-
- def find_associated_records(ids, reflection, preload_options)
- options = reflection.options
- table_name = reflection.klass.quoted_table_name
-
- if interface = reflection.options[:as]
- conditions = "#{reflection.klass.quoted_table_name}.#{connection.quote_column_name "#{interface}_id"} #{in_or_equals_for_ids(ids)} and #{reflection.klass.quoted_table_name}.#{connection.quote_column_name "#{interface}_type"} = '#{self.base_class.sti_name}'"
- else
- foreign_key = reflection.primary_key_name
- conditions = "#{reflection.klass.quoted_table_name}.#{foreign_key} #{in_or_equals_for_ids(ids)}"
- end
-
- conditions << append_conditions(reflection, preload_options)
-
- find_options = {
- :select => preload_options[:select] || options[:select] || "#{table_name}.*",
- :include => preload_options[:include] || options[:include],
- :conditions => [conditions, ids],
- :joins => options[:joins],
- :group => preload_options[:group] || options[:group],
- :order => preload_options[:order] || options[:order]
- }
-
- reflection.klass.scoped.apply_finder_options(find_options).to_a
- end
-
-
- def interpolate_sql_for_preload(sql)
- instance_eval("%@#{sql.gsub('@', '\@')}@", __FILE__, __LINE__)
- end
-
- def append_conditions(reflection, preload_options)
- sql = ""
- sql << " AND (#{interpolate_sql_for_preload(reflection.sanitized_conditions)})" if reflection.sanitized_conditions
- sql << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions]
- sql
- end
-
- def in_or_equals_for_ids(ids)
- ids.size > 1 ? "IN (?)" : "= ?"
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 73c0900c8b..08fb6bf3c4 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -4,6 +4,7 @@ require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/conversions'
require 'active_support/core_ext/module/remove_method'
+require 'active_support/core_ext/class/attribute'
module ActiveRecord
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
@@ -18,32 +19,36 @@ module ActiveRecord
end
end
- class HasManyThroughAssociationPolymorphicError < ActiveRecordError #:nodoc:
+ class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection, source_reflection)
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}'.")
end
end
+ class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection)
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
+ end
+ end
+
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection, source_reflection)
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
end
end
+ class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection, through_reflection)
+ super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
+ end
+ end
+
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
def initialize(reflection)
through_reflection = reflection.through_reflection
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(&: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 HasManyThroughSourceAssociationMacroError < ActiveRecordError #:nodoc:
- def initialize(reflection)
- through_reflection = reflection.through_reflection
- source_reflection = reflection.source_reflection
- super("Invalid source reflection macro :#{source_reflection.macro}#{" :through" if source_reflection.options[:through]} for has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}. Use :source to specify the source reflection.")
+ 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
@@ -65,6 +70,12 @@ module ActiveRecord
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 HasAndBelongsToManyAssociationWithPrimaryKeyError < ActiveRecordError #:nodoc:
def initialize(reflection)
super("Primary key is not allowed in a has_and_belongs_to_many join table (#{reflection.options[:join_table]}).")
@@ -93,8 +104,8 @@ module ActiveRecord
# (has_many, has_one) when there is at least 1 child associated instance.
# ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
class DeleteRestrictionError < ActiveRecordError #:nodoc:
- def initialize(reflection)
- super("Cannot delete record because of dependent #{reflection.name}")
+ def initialize(name)
+ super("Cannot delete record because of dependent #{name}")
end
end
@@ -104,44 +115,75 @@ module ActiveRecord
# These classes will be loaded when associations are created.
# So there is no need to eager load them.
- autoload :AssociationCollection, 'active_record/associations/association_collection'
- autoload :AssociationProxy, 'active_record/associations/association_proxy'
- autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
+ autoload :Association, 'active_record/associations/association'
+ autoload :SingularAssociation, 'active_record/associations/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/collection_association'
+ autoload :CollectionProxy, 'active_record/associations/collection_proxy'
+
+ autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
- autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
- autoload :HasManyAssociation, 'active_record/associations/has_many_association'
- autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
- autoload :HasOneAssociation, 'active_record/associations/has_one_association'
- autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
+ autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
+ autoload :HasManyAssociation, 'active_record/associations/has_many_association'
+ autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
+ autoload :HasOneAssociation, 'active_record/associations/has_one_association'
+ autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
+ autoload :ThroughAssociation, 'active_record/associations/through_association'
+
+ module Builder #:nodoc:
+ autoload :Association, 'active_record/associations/builder/association'
+ autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
+
+ autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
+ autoload :HasOne, 'active_record/associations/builder/has_one'
+ autoload :HasMany, 'active_record/associations/builder/has_many'
+ autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
+ end
+
+ autoload :Preloader, 'active_record/associations/preloader'
+ autoload :JoinDependency, 'active_record/associations/join_dependency'
+ autoload :AssociationScope, 'active_record/associations/association_scope'
+ autoload :AliasTracker, 'active_record/associations/alias_tracker'
+ autoload :JoinHelper, 'active_record/associations/join_helper'
# Clears out the association cache.
def clear_association_cache #:nodoc:
- self.class.reflect_on_all_associations.to_a.each do |assoc|
- instance_variable_set "@#{assoc.name}", nil
- end unless self.new_record?
+ @association_cache.clear if persisted?
+ end
+
+ # :nodoc:
+ attr_reader :association_cache
+
+ # Returns the association instance for the given name, instantiating it if it doesn't already exist
+ def association(name) #:nodoc:
+ association = association_instance_get(name)
+
+ if association.nil?
+ reflection = self.class.reflect_on_association(name)
+ association = reflection.association_class.new(self, reflection)
+ association_instance_set(name, association)
+ end
+
+ association
end
private
# Returns the specified association instance if it responds to :loaded?, nil otherwise.
def association_instance_get(name)
- ivar = "@#{name}"
- if instance_variable_defined?(ivar)
- association = instance_variable_get(ivar)
- association if association.respond_to?(:loaded?)
- end
+ @association_cache[name.to_sym]
end
# Set the specified association instance.
def association_instance_set(name, association)
- instance_variable_set("@#{name}", association)
+ @association_cache[name] = association
end
- # Associations are a set of macro-like class methods for tying objects together through
- # 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
+ # 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.
+ # methods.
#
# class Project < ActiveRecord::Base
# belongs_to :portfolio
@@ -150,7 +192,7 @@ module ActiveRecord
# has_and_belongs_to_many :categories
# end
#
- # The project class now has the following methods (and more) to ease the traversal and
+ # 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>
@@ -162,8 +204,8 @@ module ActiveRecord
#
# === 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
+ # 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.
#
@@ -177,7 +219,7 @@ module ActiveRecord
# other=(other) | X | X | X
# build_other(attributes={}) | X | | X
# create_other(attributes={}) | X | | X
- # other.create!(attributes={}) | | | X
+ # create_other!(attributes={}) | X | | X
#
# ===Collection associations (one-to-many / many-to-many)
# | | | has_many
@@ -200,10 +242,9 @@ module ActiveRecord
# others.empty? | X | X | X
# others.clear | X | X | X
# others.delete(other,other,...) | X | X | X
- # others.delete_all | X | X |
+ # others.delete_all | X | X | X
# others.destroy_all | X | X | X
# others.find(*args) | X | X | X
- # others.find_first | X | |
# others.exists? | X | X | X
# others.uniq | X | X | X
# others.reset | X | X | X
@@ -274,7 +315,7 @@ module ActiveRecord
#
# == Is it a +belongs_to+ or +has_one+ association?
#
- # Both express a 1-1 relationship. The difference is mostly where to place the foreign
+ # 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
@@ -304,43 +345,49 @@ module ActiveRecord
#
# == 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
+ # 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.
+ # _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 primary
- # keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
- # * If either of these saves fail (due to one of the objects being invalid) the assignment
- # statement returns +false+ and the assignment is cancelled.
- # * If you wish to assign an object to a +has_one+ association without saving it,
- # use the <tt>association.build</tt> method (documented below).
- # * Assigning an object to a +belongs_to+ association does not save the object, since
- # the foreign key field belongs on the parent. It does not save the parent either.
+ # * 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+.
- # * 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.
+ # * 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.
#
# === Association callbacks
#
- # Similar to the normal callbacks that hook into the lifecycle of an Active Record object,
- # you can also define callbacks that get triggered when you add an object to or remove an
+ # 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
@@ -354,20 +401,20 @@ module ActiveRecord
# It's possible to stack callbacks by passing them as an array. Example:
#
# class Project
- # has_and_belongs_to_many :developers,
+ # 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
+ # 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
+ # 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
@@ -383,8 +430,8 @@ module ActiveRecord
# 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.
+ # 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)
@@ -401,10 +448,10 @@ module ActiveRecord
# has_many :people, :extend => FindOrCreateByNameExtension
# end
#
- # If you need to use multiple named extension modules, you can specify an array of modules
+ # If you need to use multiple named extension modules, you can specify an array of modules
# with the <tt>:extend</tt> option.
- # In the case of name conflicts between methods in the modules, methods in modules later
- # in the array supercede those earlier in the array.
+ # In the case of name conflicts between methods in the modules, methods in modules later
+ # in the array supercede those earlier in the array.
#
# class Account < ActiveRecord::Base
# has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
@@ -415,13 +462,13 @@ module ActiveRecord
#
# * +proxy_owner+ - Returns the object the association is part of.
# * +proxy_reflection+ - Returns the reflection object that describes the association.
- # * +proxy_target+ - Returns the associated object for +belongs_to+ and +has_one+, or
+ # * +proxy_target+ - 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+.
#
# === 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 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:
#
@@ -479,17 +526,76 @@ module ActiveRecord
# @group.users.collect { |u| u.avatar }.flatten # 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
+ # 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
+ # 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
@@ -502,15 +608,15 @@ module ActiveRecord
#
# @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
+ # 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
+ # 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+
+ # 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
@@ -534,8 +640,8 @@ module ActiveRecord
#
# == 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
+ # 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.
#
@@ -547,9 +653,9 @@ module ActiveRecord
#
# == 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
+ # 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
@@ -565,54 +671,54 @@ module ActiveRecord
# 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
+ # To iterate over these one hundred posts, we'll generate 201 database queries. Let's
# first just optimize it for retrieving the author:
#
# for post in Post.find(:all, :include => :author)
#
- # 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
+ # 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:
#
# for post in Post.find(:all, :include => [ :author, :comments ])
#
- # 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
+ # 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:
#
# for post in Post.find(:all, :include => [ :author, { :comments => { :author => :gravatar } } ])
#
- # 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
+ # 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
+ # 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
+ # 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.find(:all, :include => [ :author, :comments ], :conditions => ['comments.approved = ?', true])
+ # Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all
#
- # This will result in a single SQL query with joins along the lines of:
+ # 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
+ # <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.
+ # 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
+ # If you do want eager load only some members of an association it is usually more natural
# to <tt>:include</tt> an association which has conditions defined on it:
#
# class Post < ActiveRecord::Base
@@ -621,10 +727,10 @@ module ActiveRecord
#
# Post.find(:all, :include => :approved_comments)
#
- # This will load posts and eager load the +approved_comments+ association, which contains
+ # 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,
+ # 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
@@ -633,7 +739,7 @@ module ActiveRecord
#
# Picture.find(:first, :include => :most_recent_comments).most_recent_comments # => returns all associated comments.
#
- # When eager loaded, conditions are interpolated in the context of the model class, not
+ # When eager loaded, conditions are interpolated in the context of the model class, not
# the model instance. Conditions are lazily interpolated before the actual model exists.
#
# Eager loading is supported with polymorphic associations.
@@ -646,20 +752,20 @@ module ActiveRecord
#
# Address.find(:all, :include => :addressable)
#
- # This will execute one query to load the addresses and load the addressables with one
+ # 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
+ # 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
+ # 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>.
+ # 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.find :all, :joins => :comments
@@ -693,7 +799,7 @@ module ActiveRecord
# 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 a <tt>:joins</tt> option, those table
+ # If you wish to specify your own custom joins using a <tt>:joins</tt> option, those table
# names will take precedence over the eager associations:
#
# Post.find :all, :joins => :comments, :joins => "inner join comments ..."
@@ -703,7 +809,7 @@ module ActiveRecord
# INNER JOIN comments special_comments_posts ...
# INNER JOIN comments ...
#
- # Table aliases are automatically truncated according to the maximum length of table identifiers
+ # Table aliases are automatically truncated according to the maximum length of table identifiers
# according to the specific database.
#
# == Modules
@@ -720,9 +826,9 @@ module ActiveRecord
# end
# end
#
- # When <tt>Firm#clients</tt> is called, it will in turn call
+ # 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
+ # If you want to associate with a class in another module scope, this can be done by
# specifying the complete class name.
#
# module MyApplication
@@ -739,7 +845,7 @@ module ActiveRecord
#
# == Bi-directional associations
#
- # When you specify an association there is usually an association on the associated model
+ # 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
@@ -755,10 +861,10 @@ module ActiveRecord
# belongs_to :dungeon
# end
#
- # The +traps+ association on +Dungeon+ and the the +dungeon+ association on +Trap+ are
- # the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
+ # 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
+ # Active Record doesn't know anything about these inverse relationships and so no object
# loading optimisation is possible. For example:
#
# d = Dungeon.first
@@ -767,10 +873,10 @@ module ActiveRecord
# 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
+ # 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
+ # Active Record about inverse relationships and it will optimise object loading. For
# example, if we changed our model definitions to:
#
# class Dungeon < ActiveRecord::Base
@@ -786,7 +892,7 @@ module ActiveRecord
# belongs_to :dungeon, :inverse_of => :evil_wizard
# end
#
- # Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
+ # 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:
@@ -795,14 +901,81 @@ module ActiveRecord
# * does not work with <tt>:polymorphic</tt> associations.
# * for +belongs_to+ associations +has_many+ inverse associations are ignored.
#
+ # == Deleting from associations
+ #
+ # === Dependent associations
+ #
+ # +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
+ # This allows you to specify that associated records should be deleted when the owner is
+ # deleted.
+ #
+ # For example:
+ #
+ # class Author
+ # has_many :posts, :dependent => :destroy
+ # end
+ # Author.find(1).destroy # => Will destroy all of the author's posts, too
+ #
+ # The <tt>:dependent</tt> option can have different values which specify how the deletion
+ # is done. For more information, see the documentation for this option on the different
+ # specific association types.
+ #
+ # === Delete or destroy?
+ #
+ # +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
+ # <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
+ #
+ # For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
+ # cause the records in the join table to be removed.
+ #
+ # For +has_many+, <tt>destroy</tt> will always call the <tt>destroy</tt> method of the
+ # record(s) being removed so that callbacks are run. However <tt>delete</tt> will either
+ # do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
+ # if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
+ # The default strategy is <tt>:nullify</tt> (set the foreign keys to <tt>nil</tt>), except for
+ # +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
+ # the join records, without running their callbacks).
+ #
+ # There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
+ # it returns the association rather than the records which have been deleted.
+ #
+ # === What gets deleted?
+ #
+ # There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
+ # associations have records in join tables, as well as the associated records. So when we
+ # call one of these deletion methods, what exactly should be deleted?
+ #
+ # The answer is that it is assumed that deletion on an association is about removing the
+ # <i>link</i> between the owner and the associated object(s), rather than necessarily the
+ # associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
+ # <tt>:through</tt>, the join records will be deleted, but the associated records won't.
+ #
+ # This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by_name('food'))</tt>
+ # you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
+ # to be removed from the database.
+ #
+ # However, there are examples where this strategy doesn't make sense. For example, suppose
+ # a person has many projects, and each project has many tasks. If we deleted one of a person's
+ # tasks, we would probably not want the project to be deleted. In this scenario, the delete method
+ # won't actually work: it can only be used if the association on the join model is a
+ # +belongs_to+. In other situations you are expected to perform operations directly on
+ # either the associated records or the <tt>:through</tt> association.
+ #
+ # With a regular +has_many+ there is no distinction between the "associated records"
+ # and the "link", so there is only one choice for what gets deleted.
+ #
+ # With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
+ # associated records themselves, you can always do something along the lines of
+ # <tt>person.tasks.each(&:destroy)</tt>.
+ #
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
#
- # If you attempt to assign an object to an association that doesn't match the inferred
+ # 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
+ # 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
@@ -813,12 +986,16 @@ module ActiveRecord
# 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
+ # Note that this operation instantly fires update sql without waiting for the save or update call on the
# parent object.
# [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=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
@@ -874,24 +1051,24 @@ module ActiveRecord
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
- # === Supported options
+ # === Options
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
- # from the association name. So <tt>has_many :products</tt> will by default be linked
- # to the Product class, but if the real class name is SpecialProduct, you'll have to
+ # from the association name. So <tt>has_many :products</tt> will by default be linked
+ # to the Product class, but if the real class name is SpecialProduct, you'll have to
# specify it with this option.
# [:conditions]
# Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from
- # the association are scoped if a hash is used.
- # <tt>has_many :posts, :conditions => {:published => true}</tt> will create published
+ # SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from
+ # the association are scoped if a hash is used.
+ # <tt>has_many :posts, :conditions => {:published => true}</tt> will create published
# posts with <tt>@blog.posts.create</tt> or <tt>@blog.posts.build</tt>.
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
- # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
+ # 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+.
@@ -902,15 +1079,17 @@ module ActiveRecord
# objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. If set to
# <tt>:restrict</tt> this object cannot be deleted if it has any associated object.
#
- # *Warning:* This option is ignored when used with <tt>:through</tt> option.
+ # If using with the <tt>:through</tt> option, the association on the join model must be
+ # a +belongs_to+, and the records which get deleted are the join records, rather than
+ # the associated records.
#
# [:finder_sql]
# Specify a complete SQL statement to fetch the association. This is a good way to go for complex
- # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+
+ # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+
# is _not_ added.
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
- # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
+ # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
# replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
# [:extend]
# Specify a named module for extending the proxy. See "Association extensions".
@@ -919,30 +1098,38 @@ module ActiveRecord
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:having]
- # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt>
+ # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt>
# returns. Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
- # An integer determining the offset from where the rows should be fetched. So at 5,
+ # An integer determining the offset from where the rows should be fetched. So at 5,
# it would skip the first 4 rows.
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
- # you, for example, want to do a join but not include the joined columns. Do not forget
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
+ # you, for example, want to do a join but not include the joined columns. Do not forget
# to include the primary and foreign keys, otherwise it will raise an error.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:through]
- # Specifies a join model through which to perform the query. Options for <tt>:class_name</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>belongs_to</tt>, <tt>has_one</tt>
- # or <tt>has_many</tt> association on the join model. The collection of join models
- # can be managed via the collection API. For example, new join models are created for
- # newly associated objects, and if some are gone their rows are deleted (directly,
- # no destroy callbacks are triggered).
+ # 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.
+ # 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]
@@ -953,15 +1140,14 @@ module ActiveRecord
# [: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.
+ # 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.
+ # 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.
# [: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
+ # 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.
#
@@ -979,16 +1165,8 @@ module ActiveRecord
# 'FROM people p, post_subscriptions ps ' +
# 'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
# 'ORDER BY p.first_name'
- def has_many(association_id, options = {}, &extension)
- reflection = create_has_many_reflection(association_id, options, &extension)
- configure_dependency_for_has_many(reflection)
- add_association_callbacks(reflection.name, reflection.options)
-
- if options[:through]
- collection_accessor_methods(reflection, HasManyThroughAssociation)
- else
- collection_accessor_methods(reflection, HasManyAssociation)
- end
+ def has_many(name, options = {}, &extension)
+ Builder::HasMany.build(self, name, options, &extension)
end
# Specifies a one-to-one association with another class. This method should only be used
@@ -1006,12 +1184,14 @@ module ActiveRecord
# [build_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not
- # yet been saved. <b>Note:</b> This ONLY works if an association already exists.
- # It will NOT work if the association is +nil+.
+ # yet been saved.
# [create_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
+ # [create_association!(attributes = {})]
+ # Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
+ # if the record is invalid.
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
@@ -1023,6 +1203,7 @@ module ActiveRecord
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
+ # * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
#
# === Options
#
@@ -1036,19 +1217,19 @@ module ActiveRecord
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>rank = 5</tt>. Record creation from the association is scoped if a hash
- # is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create
+ # is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create
# an enabled account with <tt>@company.create_account</tt> or <tt>@company.build_account</tt>.
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# [:dependent]
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
- # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
- # If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+.
+ # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
+ # If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+.
# Also, association is assigned.
# [: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
+ # 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+.
@@ -1057,17 +1238,17 @@ module ActiveRecord
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
- # you want to do a join but not include the joined columns. Do not forget to include the
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
+ # you want to do a join but not include the joined columns. Do not forget to include the
# primary and foreign keys, otherwise it will raise an error.
# [:through]
- # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>
- # 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.
+ # 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.
+ # 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]
@@ -1076,20 +1257,20 @@ module ActiveRecord
# [:readonly]
# If true, the associated object is readonly through the association.
# [:validate]
- # If false, don't validate the associated object when saving the parent object. +false+ by default.
+ # 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,
+ # 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.
# [: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
+ # 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
+ # has_one :credit_card, :dependent => :nullify # updates the associated records foreign
# # key value to NULL rather than destroying it
# has_one :last_comment, :class_name => "Comment", :order => "posted_on"
# has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
@@ -1097,17 +1278,8 @@ module ActiveRecord
# has_one :boss, :readonly => :true
# has_one :club, :through => :membership
# has_one :primary_address, :through => :addressables, :conditions => ["addressable.primary = ?", true], :source => :addressable
- def has_one(association_id, options = {})
- if options[:through]
- reflection = create_has_one_through_reflection(association_id, options)
- association_accessor_methods(reflection, ActiveRecord::Associations::HasOneThroughAssociation)
- else
- reflection = create_has_one_reflection(association_id, options)
- association_accessor_methods(reflection, HasOneAssociation)
- association_constructor_method(:build, reflection, HasOneAssociation)
- association_constructor_method(:create, reflection, HasOneAssociation)
- configure_dependency_for_has_one(reflection)
- end
+ def has_one(name, options = {})
+ Builder::HasOne.build(self, name, options)
end
# Specifies a one-to-one association with another class. This method should only be used
@@ -1129,6 +1301,9 @@ module ActiveRecord
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
+ # [create_association!(attributes = {})]
+ # Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
+ # if the record is invalid.
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
@@ -1140,6 +1315,7 @@ module ActiveRecord
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
+ # * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
# === Options
@@ -1152,33 +1328,38 @@ module ActiveRecord
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>authorized = 1</tt>.
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed
- # if, for example, you want to do a join but not include the joined columns. Do not
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed
+ # if, for example, you want to do a join but not include the joined columns. Do not
# forget to include the primary and foreign keys, otherwise it will raise an error.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
- # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
- # 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 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.
+ # 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
+ # <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
+ # 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). You can also specify a custom counter
- # cache column by providing a column name instead of a +true+/+false+ value to this
+ # is used on the associate class (such as a Post class). 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
+ # Note: Specifying a counter cache will add it to that model's list of readonly attributes
# using +attr_readonly+.
# [:include]
# Specify second-order associations that should be eager loaded when this object is loaded.
@@ -1189,19 +1370,19 @@ module ActiveRecord
# [:readonly]
# If true, the associated object is readonly through the association.
# [:validate]
- # If false, don't validate the associated objects when saving the parent object. +false+ by default.
+ # 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
+ # 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.
# [: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
+ # 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 instead of 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
+ # 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.
#
@@ -1216,29 +1397,16 @@ module ActiveRecord
# belongs_to :post, :counter_cache => true
# belongs_to :company, :touch => true
# belongs_to :company, :touch => :employees_last_updated_at
- def belongs_to(association_id, options = {})
- reflection = create_belongs_to_reflection(association_id, options)
-
- if reflection.options[:polymorphic]
- association_accessor_methods(reflection, BelongsToPolymorphicAssociation)
- else
- association_accessor_methods(reflection, BelongsToAssociation)
- association_constructor_method(:build, reflection, BelongsToAssociation)
- association_constructor_method(:create, reflection, BelongsToAssociation)
- end
-
- add_counter_cache_callbacks(reflection) if options[:counter_cache]
- add_touch_callbacks(reflection, options[:touch]) if options[:touch]
-
- configure_dependency_for_belongs_to(reflection)
+ def belongs_to(name, options = {})
+ Builder::BelongsTo.build(self, name, options)
end
# Specifies a many-to-many relationship with another class. This associates two classes via an
# 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" outranks "P".
- # 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
+ # will give the default join table name of "developers_projects" because "D" outranks "P".
+ # 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",
@@ -1261,12 +1429,6 @@ module ActiveRecord
# end
# end
#
- # Deprecated: Any additional fields added to the join table will be placed as attributes when
- # pulling records out through +has_and_belongs_to_many+ associations. Records returned from join
- # tables with additional attributes will be marked as readonly (because we can't save changes
- # to the additional attributes). It's strongly recommended that you upgrade any
- # associations with attributes to a real join model (see introduction).
- #
# Adds the following methods for retrieval and query:
#
# [collection(force_reload = false)]
@@ -1275,7 +1437,7 @@ module ActiveRecord
# [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
+ # Note that this operation instantly fires update sql without waiting for the save or update call on the
# parent object.
# [collection.delete(object, ...)]
# Removes one or more objects from the collection by removing their associations from the join table.
@@ -1304,7 +1466,7 @@ module ActiveRecord
# 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
+ # 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
@@ -1340,8 +1502,8 @@ module ActiveRecord
# 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
+ # 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.
@@ -1350,7 +1512,7 @@ module ActiveRecord
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
- # SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are
+ # SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are
# scoped if a hash is used.
# <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
# or <tt>@blog.posts.build</tt>.
@@ -1363,7 +1525,7 @@ module ActiveRecord
# Overwrite the default generated SQL statement used to fetch the association with a manual statement
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
- # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
+ # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
# replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
# [:delete_sql]
# Overwrite the default generated SQL statement used to remove links between the associated
@@ -1378,23 +1540,23 @@ module ActiveRecord
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:having]
- # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns.
+ # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns.
# Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
- # An integer determining the offset from where the rows should be fetched. So at 5,
+ # An integer determining the offset from where the rows should be fetched. So at 5,
# it would skip the first 4 rows.
# [:select]
- # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
- # you want to do a join but not include the joined columns. Do not forget to include the primary
+ # By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
+ # you want to do a join but not include the joined columns. Do not forget to include the primary
# and foreign keys, otherwise it will raise an error.
# [:readonly]
# If true, all the associated objects are readonly through the association.
# [:validate]
- # If false, don't validate the associated objects when saving the parent object. +true+ by default.
+ # 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
+ # 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.
@@ -1407,845 +1569,9 @@ module ActiveRecord
# has_and_belongs_to_many :categories, :readonly => true
# has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
# 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
- def has_and_belongs_to_many(association_id, options = {}, &extension)
- reflection = create_has_and_belongs_to_many_reflection(association_id, options, &extension)
- collection_accessor_methods(reflection, HasAndBelongsToManyAssociation)
-
- # Don't use a before_destroy callback since users' before_destroy
- # callbacks will be executed after the association is wiped out.
- include Module.new {
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def destroy # def destroy
- super # super
- #{reflection.name}.clear # posts.clear
- end # end
- RUBY
- }
-
- add_association_callbacks(reflection.name, options)
+ def has_and_belongs_to_many(name, options = {}, &extension)
+ Builder::HasAndBelongsToMany.build(self, name, options, &extension)
end
-
- private
- # Generates a join table name from two provided table names.
- # The names in the join table names end up in lexicographic order.
- #
- # join_table_name("members", "clubs") # => "clubs_members"
- # join_table_name("members", "special_clubs") # => "members_special_clubs"
- def join_table_name(first_table_name, second_table_name)
- if first_table_name < second_table_name
- join_table = "#{first_table_name}_#{second_table_name}"
- else
- join_table = "#{second_table_name}_#{first_table_name}"
- end
-
- table_name_prefix + join_table + table_name_suffix
- end
-
- def association_accessor_methods(reflection, association_proxy_class)
- redefine_method(reflection.name) do |*params|
- force_reload = params.first unless params.empty?
- association = association_instance_get(reflection.name)
-
- if association.nil? || force_reload
- association = association_proxy_class.new(self, reflection)
- retval = force_reload ? reflection.klass.uncached { association.reload } : association.reload
- if retval.nil? and association_proxy_class == BelongsToAssociation
- association_instance_set(reflection.name, nil)
- return nil
- end
- association_instance_set(reflection.name, association)
- end
-
- association.target.nil? ? nil : association
- end
-
- redefine_method("loaded_#{reflection.name}?") do
- association = association_instance_get(reflection.name)
- association && association.loaded?
- end
-
- redefine_method("#{reflection.name}=") do |new_value|
- association = association_instance_get(reflection.name)
-
- if association.nil? || association.target != new_value
- association = association_proxy_class.new(self, reflection)
- end
-
- association.replace(new_value)
- association_instance_set(reflection.name, new_value.nil? ? nil : association)
- end
-
- redefine_method("set_#{reflection.name}_target") do |target|
- return if target.nil? and association_proxy_class == BelongsToAssociation
- association = association_proxy_class.new(self, reflection)
- association.target = target
- association_instance_set(reflection.name, association)
- end
- end
-
- def collection_reader_method(reflection, association_proxy_class)
- redefine_method(reflection.name) do |*params|
- force_reload = params.first unless params.empty?
- association = association_instance_get(reflection.name)
-
- unless association
- association = association_proxy_class.new(self, reflection)
- association_instance_set(reflection.name, association)
- end
-
- reflection.klass.uncached { association.reload } if force_reload
-
- association
- end
-
- redefine_method("#{reflection.name.to_s.singularize}_ids") do
- if send(reflection.name).loaded? || reflection.options[:finder_sql]
- send(reflection.name).map(&:id)
- else
- if reflection.through_reflection && reflection.source_reflection.belongs_to?
- through = reflection.through_reflection
- primary_key = reflection.source_reflection.primary_key_name
- send(through.name).select("DISTINCT #{through.quoted_table_name}.#{primary_key}").map!(&:"#{primary_key}")
- else
- send(reflection.name).select("#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").except(:includes).map!(&:id)
- end
- end
- end
-
- end
-
- def collection_accessor_methods(reflection, association_proxy_class, writer = true)
- collection_reader_method(reflection, association_proxy_class)
-
- if writer
- redefine_method("#{reflection.name}=") do |new_value|
- # Loads proxy class instance (defined in collection_reader_method) if not already loaded
- association = send(reflection.name)
- association.replace(new_value)
- association
- end
-
- redefine_method("#{reflection.name.to_s.singularize}_ids=") do |new_value|
- pk_column = reflection.primary_key_column
- ids = (new_value || []).reject { |nid| nid.blank? }
- ids.map!{ |i| pk_column.type_cast(i) }
- send("#{reflection.name}=", reflection.klass.find(ids).index_by(&:id).values_at(*ids))
- end
- end
- end
-
- def association_constructor_method(constructor, reflection, association_proxy_class)
- redefine_method("#{constructor}_#{reflection.name}") do |*params|
- attributees = params.first unless params.empty?
- replace_existing = params[1].nil? ? true : params[1]
- association = association_instance_get(reflection.name)
-
- unless association
- association = association_proxy_class.new(self, reflection)
- association_instance_set(reflection.name, association)
- end
-
- if association_proxy_class == HasOneAssociation
- association.send(constructor, attributees, replace_existing)
- else
- association.send(constructor, attributees)
- end
- end
- end
-
- def add_counter_cache_callbacks(reflection)
- cache_column = reflection.counter_cache_column
-
- method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym
- define_method(method_name) do
- association = send(reflection.name)
- association.class.increment_counter(cache_column, association.id) unless association.nil?
- end
- after_create(method_name)
-
- method_name = "belongs_to_counter_cache_before_destroy_for_#{reflection.name}".to_sym
- define_method(method_name) do
- association = send(reflection.name)
- association.class.decrement_counter(cache_column, association.id) unless association.nil?
- end
- before_destroy(method_name)
-
- module_eval(
- "#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)", __FILE__, __LINE__
- )
- end
-
- def add_touch_callbacks(reflection, touch_attribute)
- method_name = :"belongs_to_touch_after_save_or_destroy_for_#{reflection.name}"
- redefine_method(method_name) do
- association = send(reflection.name)
-
- if touch_attribute == true
- association.touch unless association.nil?
- else
- association.touch(touch_attribute) unless association.nil?
- end
- end
- after_save(method_name)
- after_touch(method_name)
- after_destroy(method_name)
- end
-
- # Creates before_destroy callback methods that nullify, delete or destroy
- # has_many associated objects, according to the defined :dependent rule.
- #
- # See HasManyAssociation#delete_records for more information. In general
- # - delete children if the option is set to :destroy or :delete_all
- # - set the foreign key to NULL if the option is set to :nullify
- # - do not delete the parent record if there is any child record if the
- # option is set to :restrict
- #
- # The +extra_conditions+ parameter, which is not used within the main
- # Active Record codebase, is meant to allow plugins to define extra
- # finder conditions.
- def configure_dependency_for_has_many(reflection, extra_conditions = nil)
- if reflection.options.include?(:dependent)
- case reflection.options[:dependent]
- when :destroy
- method_name = "has_many_dependent_destroy_for_#{reflection.name}".to_sym
- define_method(method_name) do
- send(reflection.name).each do |o|
- # No point in executing the counter update since we're going to destroy the parent anyway
- counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym
- if(o.respond_to? counter_method) then
- class << o
- self
- end.send(:define_method, counter_method, Proc.new {})
- end
- o.destroy
- end
- end
- before_destroy method_name
- when :delete_all
- before_destroy do |record|
- self.class.send(:delete_all_has_many_dependencies,
- record,
- reflection.name,
- reflection.klass,
- reflection.dependent_conditions(record, self.class, extra_conditions))
- end
- when :nullify
- before_destroy do |record|
- self.class.send(:nullify_has_many_dependencies,
- record,
- reflection.name,
- reflection.klass,
- reflection.primary_key_name,
- reflection.dependent_conditions(record, self.class, extra_conditions))
- end
- when :restrict
- method_name = "has_many_dependent_restrict_for_#{reflection.name}".to_sym
- define_method(method_name) do
- unless send(reflection.name).empty?
- raise DeleteRestrictionError.new(reflection)
- end
- end
- before_destroy method_name
- else
- raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, :nullify or :restrict (#{reflection.options[:dependent].inspect})"
- end
- end
- end
-
- # Creates before_destroy callback methods that nullify, delete or destroy
- # has_one associated objects, according to the defined :dependent rule.
- # If the association is marked as :dependent => :restrict, create a callback
- # that prevents deleting entirely.
- def configure_dependency_for_has_one(reflection)
- if reflection.options.include?(:dependent)
- name = reflection.options[:dependent]
- method_name = :"has_one_dependent_#{name}_for_#{reflection.name}"
-
- case name
- when :destroy, :delete
- class_eval <<-eoruby, __FILE__, __LINE__ + 1
- def #{method_name}
- association = #{reflection.name}
- association.#{name} if association
- end
- eoruby
- when :nullify
- class_eval <<-eoruby, __FILE__, __LINE__ + 1
- def #{method_name}
- association = #{reflection.name}
- association.update_attribute(#{reflection.primary_key_name.inspect}, nil) if association
- end
- eoruby
- when :restrict
- method_name = "has_one_dependent_restrict_for_#{reflection.name}".to_sym
- define_method(method_name) do
- unless send(reflection.name).nil?
- raise DeleteRestrictionError.new(reflection)
- end
- end
- before_destroy method_name
- else
- raise ArgumentError, "The :dependent option expects either :destroy, :delete, :nullify or :restrict (#{reflection.options[:dependent].inspect})"
- end
-
- before_destroy method_name
- end
- end
-
- def configure_dependency_for_belongs_to(reflection)
- if reflection.options.include?(:dependent)
- name = reflection.options[:dependent]
-
- unless [:destroy, :delete].include?(name)
- raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{reflection.options[:dependent].inspect})"
- end
-
- method_name = :"belongs_to_dependent_#{name}_for_#{reflection.name}"
- class_eval <<-eoruby, __FILE__, __LINE__ + 1
- def #{method_name}
- association = #{reflection.name}
- association.#{name} if association
- end
- eoruby
- after_destroy method_name
- end
- end
-
- def delete_all_has_many_dependencies(record, reflection_name, association_class, dependent_conditions)
- association_class.delete_all(dependent_conditions)
- end
-
- def nullify_has_many_dependencies(record, reflection_name, association_class, primary_key_name, dependent_conditions)
- association_class.update_all("#{primary_key_name} = NULL", dependent_conditions)
- end
-
- mattr_accessor :valid_keys_for_has_many_association
- @@valid_keys_for_has_many_association = [
- :class_name, :table_name, :foreign_key, :primary_key,
- :dependent,
- :select, :conditions, :include, :order, :group, :having, :limit, :offset,
- :as, :through, :source, :source_type,
- :uniq,
- :finder_sql, :counter_sql,
- :before_add, :after_add, :before_remove, :after_remove,
- :extend, :readonly,
- :validate, :inverse_of
- ]
-
- def create_has_many_reflection(association_id, options, &extension)
- options.assert_valid_keys(valid_keys_for_has_many_association)
- options[:extend] = create_extension_modules(association_id, extension, options[:extend])
-
- create_reflection(:has_many, association_id, options, self)
- end
-
- mattr_accessor :valid_keys_for_has_one_association
- @@valid_keys_for_has_one_association = [
- :class_name, :foreign_key, :remote, :select, :conditions, :order,
- :include, :dependent, :counter_cache, :extend, :as, :readonly,
- :validate, :primary_key, :inverse_of
- ]
-
- def create_has_one_reflection(association_id, options)
- options.assert_valid_keys(valid_keys_for_has_one_association)
- create_reflection(:has_one, association_id, options, self)
- end
-
- def create_has_one_through_reflection(association_id, options)
- options.assert_valid_keys(
- :class_name, :foreign_key, :remote, :select, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :through, :source, :source_type, :validate
- )
- create_reflection(:has_one, association_id, options, self)
- end
-
- mattr_accessor :valid_keys_for_belongs_to_association
- @@valid_keys_for_belongs_to_association = [
- :class_name, :primary_key, :foreign_key, :foreign_type, :remote, :select, :conditions,
- :include, :dependent, :counter_cache, :extend, :polymorphic, :readonly,
- :validate, :touch, :inverse_of
- ]
-
- def create_belongs_to_reflection(association_id, options)
- options.assert_valid_keys(valid_keys_for_belongs_to_association)
- reflection = create_reflection(:belongs_to, association_id, options, self)
-
- if options[:polymorphic]
- reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
- end
-
- reflection
- end
-
- mattr_accessor :valid_keys_for_has_and_belongs_to_many_association
- @@valid_keys_for_has_and_belongs_to_many_association = [
- :class_name, :table_name, :join_table, :foreign_key, :association_foreign_key,
- :select, :conditions, :include, :order, :group, :having, :limit, :offset,
- :uniq,
- :finder_sql, :counter_sql, :delete_sql, :insert_sql,
- :before_add, :after_add, :before_remove, :after_remove,
- :extend, :readonly,
- :validate
- ]
-
- def create_has_and_belongs_to_many_reflection(association_id, options, &extension)
- options.assert_valid_keys(valid_keys_for_has_and_belongs_to_many_association)
- options[:extend] = create_extension_modules(association_id, extension, options[:extend])
-
- reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self)
-
- if reflection.association_foreign_key == reflection.primary_key_name
- raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
- end
-
- reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))
- if connection.supports_primary_key? && (connection.primary_key(reflection.options[:join_table]) rescue false)
- raise HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection)
- end
-
- reflection
- end
-
- def add_association_callbacks(association_name, options)
- callbacks = %w(before_add after_add before_remove after_remove)
- callbacks.each do |callback_name|
- full_callback_name = "#{callback_name}_for_#{association_name}"
- defined_callbacks = options[callback_name.to_sym]
- if options.has_key?(callback_name.to_sym)
- class_inheritable_reader full_callback_name.to_sym
- write_inheritable_attribute(full_callback_name.to_sym, [defined_callbacks].flatten)
- else
- write_inheritable_attribute(full_callback_name.to_sym, [])
- end
- end
- end
-
- def create_extension_modules(association_id, block_extension, extensions)
- if block_extension
- extension_module_name = "#{self.to_s.demodulize}#{association_id.to_s.camelize}AssociationExtension"
-
- silence_warnings do
- self.parent.const_set(extension_module_name, Module.new(&block_extension))
- end
- Array.wrap(extensions).push("#{self.parent}::#{extension_module_name}".constantize)
- else
- Array.wrap(extensions)
- end
- end
-
- class JoinDependency # :nodoc:
- attr_reader :joins, :reflections, :table_aliases
-
- def initialize(base, associations, joins)
- @joins = [JoinBase.new(base, joins)]
- @associations = associations
- @reflections = []
- @base_records_hash = {}
- @base_records_in_order = []
- @table_aliases = Hash.new { |aliases, table| aliases[table] = 0 }
- @table_aliases[base.table_name] = 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_class)
- end
- self
- end
-
- def join_associations
- @joins[1..-1].to_a
- end
-
- def join_base
- @joins[0]
- end
-
- def count_aliases_from_table_joins(name)
- # quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase
- quoted_name = join_base.active_record.connection.quote_table_name(name.downcase).downcase
- join_sql = join_base.table_joins.to_s.downcase
- join_sql.blank? ? 0 :
- # Table names
- join_sql.scan(/join(?:\s+\w+)?\s+#{quoted_name}\son/).size +
- # Table aliases
- join_sql.scan(/join(?:\s+\w+)?\s+\S+\s+#{quoted_name}\son/).size
- end
-
- def instantiate(rows)
- rows.each_with_index do |row, i|
- primary_id = join_base.record_id(row)
- unless @base_records_hash[primary_id]
- @base_records_in_order << (@base_records_hash[primary_id] = join_base.instantiate(row))
- end
- construct(@base_records_hash[primary_id], @associations, join_associations.dup, row)
- end
- remove_duplicate_results!(join_base.active_record, @base_records_in_order, @associations)
- return @base_records_in_order
- end
-
- def remove_duplicate_results!(base, records, associations)
- case associations
- when Symbol, String
- reflection = base.reflections[associations]
- remove_uniq_by_reflection(reflection, records)
- when Array
- associations.each do |association|
- remove_duplicate_results!(base, records, association)
- end
- when Hash
- associations.keys.each do |name|
- reflection = base.reflections[name]
- remove_uniq_by_reflection(reflection, records)
-
- parent_records = []
- records.each do |record|
- if descendant = record.send(reflection.name)
- if reflection.collection?
- parent_records.concat descendant.target.uniq
- else
- parent_records << descendant
- end
- end
- end
-
- remove_duplicate_results!(reflection.klass, parent_records, associations[name]) unless parent_records.empty?
- end
- end
- end
-
- protected
-
- def build(associations, parent = nil, join_class = Arel::InnerJoin)
- parent ||= @joins.last
- case associations
- when Symbol, String
- reflection = parent.reflections[associations.to_s.intern] or
- raise ConfigurationError, "Association named '#{ associations }' was not found; perhaps you misspelled it?"
- @reflections << reflection
- @joins << build_join_association(reflection, parent).with_join_class(join_class)
- when Array
- associations.each do |association|
- build(association, parent, join_class)
- end
- when Hash
- associations.keys.sort{|a,b|a.to_s<=>b.to_s}.each do |name|
- build(name, parent, join_class)
- build(associations[name], nil, join_class)
- end
- else
- raise ConfigurationError, associations.inspect
- end
- 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, joins, row)
- case associations
- when Symbol, String
- join = joins.detect{|j| j.reflection.name.to_s == associations.to_s && j.parent_table_name == parent.class.table_name }
- raise(ConfigurationError, "No such association") if join.nil?
-
- joins.delete(join)
- construct_association(parent, join, row)
- when Array
- associations.each do |association|
- construct(parent, association, joins, row)
- end
- when Hash
- associations.keys.sort{|a,b|a.to_s<=>b.to_s}.each do |name|
- join = joins.detect{|j| j.reflection.name.to_s == name.to_s && j.parent_table_name == parent.class.table_name }
- raise(ConfigurationError, "No such association") if join.nil?
-
- association = construct_association(parent, join, row)
- joins.delete(join)
- construct(association, associations[name], joins, row) if association
- end
- else
- raise ConfigurationError, associations.inspect
- end
- end
-
- def construct_association(record, join, row)
- case join.reflection.macro
- when :has_many, :has_and_belongs_to_many
- collection = record.send(join.reflection.name)
- collection.loaded
-
- return nil if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
- association = join.instantiate(row)
- collection.target.push(association)
- collection.__send__(:set_inverse_instance, association, record)
- when :has_one
- return if record.id.to_s != join.parent.record_id(row).to_s
- return if record.instance_variable_defined?("@#{join.reflection.name}")
- association = join.instantiate(row) unless row[join.aliased_primary_key].nil?
- set_target_and_inverse(join, association, record)
- when :belongs_to
- return if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
- association = join.instantiate(row)
- set_target_and_inverse(join, association, record)
- else
- raise ConfigurationError, "unknown macro: #{join.reflection.macro}"
- end
- return association
- end
-
- def set_target_and_inverse(join, association, record)
- association_proxy = record.send("set_#{join.reflection.name}_target", association)
- association_proxy.__send__(:set_inverse_instance, association, record)
- end
-
- class JoinBase # :nodoc:
- attr_reader :active_record, :table_joins
- delegate :table_name, :column_names, :primary_key, :reflections, :sanitize_sql, :arel_engine, :to => :active_record
-
- def initialize(active_record, joins = nil)
- @active_record = active_record
- @cached_record = {}
- @table_joins = joins
- end
-
- def ==(other)
- other.class == self.class &&
- other.active_record == active_record &&
- other.table_joins == table_joins
- end
-
- def aliased_prefix
- "t0"
- end
-
- def aliased_primary_key
- "#{aliased_prefix}_r0"
- end
-
- def aliased_table_name
- active_record.table_name
- end
-
- def column_names_with_alias
- unless defined?(@column_names_with_alias)
- @column_names_with_alias = []
-
- ([primary_key] + (column_names - [primary_key])).each_with_index do |column_name, i|
- @column_names_with_alias << [column_name, "#{aliased_prefix}_r#{i}"]
- end
- end
-
- @column_names_with_alias
- end
-
- def extract_record(row)
- column_names_with_alias.inject({}){|record, (cn, an)| record[cn] = row[an]; record}
- end
-
- def record_id(row)
- row[aliased_primary_key]
- end
-
- def instantiate(row)
- @cached_record[record_id(row)] ||= active_record.send(:instantiate, extract_record(row))
- end
- end
-
- class JoinAssociation < JoinBase # :nodoc:
- attr_reader :reflection, :parent, :aliased_table_name, :aliased_prefix, :aliased_join_table_name, :parent_table_name, :join_class
- delegate :options, :klass, :through_reflection, :source_reflection, :to => :reflection
-
- def initialize(reflection, join_dependency, parent = nil)
- reflection.check_validity!
- if reflection.options[:polymorphic]
- raise EagerLoadPolymorphicError.new(reflection)
- end
-
- super(reflection.klass)
- @join_dependency = join_dependency
- @parent = parent
- @reflection = reflection
- @aliased_prefix = "t#{ join_dependency.joins.size }"
- @parent_table_name = parent.active_record.table_name
- @aliased_table_name = aliased_table_name_for(table_name)
- @join = nil
- @join_class = Arel::InnerJoin
-
- if reflection.macro == :has_and_belongs_to_many
- @aliased_join_table_name = aliased_table_name_for(reflection.options[:join_table], "_join")
- end
-
- if [:has_many, :has_one].include?(reflection.macro) && reflection.options[:through]
- @aliased_join_table_name = aliased_table_name_for(reflection.through_reflection.klass.table_name, "_join")
- end
- end
-
- def ==(other)
- other.class == self.class &&
- other.reflection == reflection &&
- other.parent == parent
- end
-
- def find_parent_in(other_join_dependency)
- other_join_dependency.joins.detect do |join|
- self.parent == join
- end
- end
-
- def with_join_class(join_class)
- @join_class = join_class
- self
- end
-
- def association_join
- return @join if @join
-
- aliased_table = Arel::Table.new(table_name, :as => @aliased_table_name, :engine => arel_engine)
- parent_table = Arel::Table.new(parent.table_name, :as => parent.aliased_table_name, :engine => arel_engine)
-
- @join = case reflection.macro
- when :has_and_belongs_to_many
- join_table = Arel::Table.new(options[:join_table], :as => aliased_join_table_name, :engine => arel_engine)
- fk = options[:foreign_key] || reflection.active_record.to_s.foreign_key
- klass_fk = options[:association_foreign_key] || klass.to_s.foreign_key
-
- [
- join_table[fk].eq(parent_table[reflection.active_record.primary_key]),
- aliased_table[klass.primary_key].eq(join_table[klass_fk])
- ]
- when :has_many, :has_one
- if reflection.options[:through]
- join_table = Arel::Table.new(through_reflection.klass.table_name, :as => aliased_join_table_name, :engine => arel_engine)
- jt_foreign_key = jt_as_extra = jt_source_extra = jt_sti_extra = nil
- first_key = second_key = as_extra = nil
-
- if through_reflection.options[:as] # has_many :through against a polymorphic join
- jt_foreign_key = through_reflection.options[:as].to_s + '_id'
- jt_as_extra = join_table[through_reflection.options[:as].to_s + '_type'].eq(parent.active_record.base_class.name)
- else
- jt_foreign_key = through_reflection.primary_key_name
- end
-
- case source_reflection.macro
- when :has_many
- if source_reflection.options[:as]
- first_key = "#{source_reflection.options[:as]}_id"
- second_key = options[:foreign_key] || primary_key
- as_extra = aliased_table["#{source_reflection.options[:as]}_type"].eq(source_reflection.active_record.base_class.name)
- else
- first_key = through_reflection.klass.base_class.to_s.foreign_key
- second_key = options[:foreign_key] || primary_key
- end
-
- unless through_reflection.klass.descends_from_active_record?
- jt_sti_extra = join_table[through_reflection.active_record.inheritance_column].eq(through_reflection.klass.sti_name)
- end
- when :belongs_to
- first_key = primary_key
- if reflection.options[:source_type]
- second_key = source_reflection.association_foreign_key
- jt_source_extra = join_table[reflection.source_reflection.options[:foreign_type]].eq(reflection.options[:source_type])
- else
- second_key = source_reflection.primary_key_name
- end
- end
-
- [
- [parent_table[parent.primary_key].eq(join_table[jt_foreign_key]), jt_as_extra, jt_source_extra, jt_sti_extra].reject{|x| x.blank? },
- aliased_table[first_key].eq(join_table[second_key])
- ]
- elsif reflection.options[:as]
- id_rel = aliased_table["#{reflection.options[:as]}_id"].eq(parent_table[parent.primary_key])
- type_rel = aliased_table["#{reflection.options[:as]}_type"].eq(parent.active_record.base_class.name)
- [id_rel, type_rel]
- else
- foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
- [aliased_table[foreign_key].eq(parent_table[reflection.options[:primary_key] || parent.primary_key])]
- end
- when :belongs_to
- [aliased_table[options[:primary_key] || reflection.klass.primary_key].eq(parent_table[options[:foreign_key] || reflection.primary_key_name])]
- end
-
- unless klass.descends_from_active_record?
- sti_column = aliased_table[klass.inheritance_column]
- sti_condition = sti_column.eq(klass.sti_name)
- klass.descendants.each {|subclass| sti_condition = sti_condition.or(sti_column.eq(subclass.sti_name)) }
-
- @join << sti_condition
- end
-
- [through_reflection, reflection].each do |ref|
- if ref && ref.options[:conditions]
- @join << interpolate_sql(sanitize_sql(ref.options[:conditions], aliased_table_name))
- end
- end
-
- @join
- end
-
- def relation
- aliased = Arel::Table.new(table_name, :as => @aliased_table_name, :engine => arel_engine)
-
- if reflection.macro == :has_and_belongs_to_many
- [Arel::Table.new(options[:join_table], :as => aliased_join_table_name, :engine => arel_engine), aliased]
- elsif reflection.options[:through]
- [Arel::Table.new(through_reflection.klass.table_name, :as => aliased_join_table_name, :engine => arel_engine), aliased]
- else
- aliased
- end
- end
-
- def join_relation(joining_relation, join = nil)
- joining_relation.joins(self.with_join_class(Arel::OuterJoin))
- end
-
- protected
-
- def aliased_table_name_for(name, suffix = nil)
- if @join_dependency.table_aliases[name].zero?
- @join_dependency.table_aliases[name] = @join_dependency.count_aliases_from_table_joins(name)
- end
-
- if !@join_dependency.table_aliases[name].zero? # We need an alias
- name = active_record.connection.table_alias_for "#{pluralize(reflection.name)}_#{parent_table_name}#{suffix}"
- @join_dependency.table_aliases[name] += 1
- if @join_dependency.table_aliases[name] == 1 # First time we've seen this name
- # Also need to count the aliases from the table_aliases to avoid incorrect count
- @join_dependency.table_aliases[name] += @join_dependency.count_aliases_from_table_joins(name)
- end
- table_index = @join_dependency.table_aliases[name]
- name = name[0..active_record.connection.table_alias_length-3] + "_#{table_index}" if table_index > 1
- else
- @join_dependency.table_aliases[name] += 1
- end
-
- name
- end
-
- def pluralize(table_name)
- ActiveRecord::Base.pluralize_table_names ? table_name.to_s.pluralize : table_name
- end
-
- def table_alias_for(table_name, table_alias)
- "#{table_name} #{table_alias if table_name != table_alias}".strip
- end
-
- def table_name_and_alias
- table_alias_for table_name, @aliased_table_name
- end
-
- def interpolate_sql(sql)
- instance_eval("%@#{sql.gsub('@', '\@')}@", __FILE__, __LINE__)
- end
- end
- end
end
end
end
diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb
new file mode 100644
index 0000000000..634dee2289
--- /dev/null
+++ b/activerecord/lib/active_record/associations/alias_tracker.rb
@@ -0,0 +1,85 @@
+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
+
+ # table_joins is an array of arel joins which might conflict with the aliases we assign here
+ def initialize(table_joins = [])
+ @aliases = Hash.new
+ @table_joins = table_joins
+ end
+
+ def aliased_table_for(table_name, aliased_name = nil)
+ table_alias = aliased_name_for(table_name, aliased_name)
+
+ if table_alias == table_name
+ Arel::Table.new(table_name)
+ else
+ Arel::Table.new(table_name).alias(table_alias)
+ end
+ end
+
+ def aliased_name_for(table_name, aliased_name = nil)
+ aliased_name ||= table_name
+
+ initialize_count_for(table_name) if aliases[table_name].nil?
+
+ 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)
+
+ initialize_count_for(aliased_name) if aliases[aliased_name].nil?
+
+ # Update the count
+ aliases[aliased_name] += 1
+
+ if aliases[aliased_name] > 1
+ "#{truncate(aliased_name)}_#{aliases[aliased_name]}"
+ else
+ aliased_name
+ end
+ end
+ end
+
+ def pluralize(table_name)
+ ActiveRecord::Base.pluralize_table_names ? table_name.to_s.pluralize : table_name
+ end
+
+ private
+
+ def initialize_count_for(name)
+ aliases[name] = 0
+
+ unless Arel::Table === table_joins
+ # quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase
+ quoted_name = connection.quote_table_name(name).downcase
+
+ aliases[name] += table_joins.map { |join|
+ # Table names + table aliases
+ join.left.downcase.scan(
+ /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
+ ).size
+ }.sum
+ end
+
+ aliases[name]
+ end
+
+ def truncate(name)
+ name[0..connection.table_alias_length-3]
+ end
+
+ def connection
+ ActiveRecord::Base.connection
+ 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 0000000000..27c446b12c
--- /dev/null
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -0,0 +1,230 @@
+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!
+
+ @target = nil
+ @owner, @reflection = owner, reflection
+ @updated = false
+
+ reset
+ construct_scope
+ end
+
+ # Returns the name of the table of the related class:
+ #
+ # post.comments.aliased_table_name # => "comments"
+ #
+ def aliased_table_name
+ reflection.klass.table_name
+ end
+
+ # Resets the \loaded flag to +false+ and sets the \target to +nil+.
+ def reset
+ @loaded = false
+ IdentityMap.remove(target) if IdentityMap.enabled? && target
+ @target = nil
+ end
+
+ # Reloads the \target and returns +self+ on success.
+ def reload
+ reset
+ construct_scope
+ load_target
+ self unless target.nil?
+ end
+
+ # Has the \target been already \loaded?
+ def loaded?
+ @loaded
+ end
+
+ # Asserts the \target has been loaded setting the \loaded flag to +true+.
+ def loaded!
+ @loaded = true
+ @stale_state = stale_state
+ end
+
+ # The target is stale if the target no longer points to the record(s) that the
+ # relevant foreign_key(s) refers to. If stale, the association accessor method
+ # on the owner will reload the target. It's up to subclasses to implement the
+ # state_state method if relevant.
+ #
+ # Note that if the target has not been loaded, it is not considered stale.
+ def stale_target?
+ loaded? && @stale_state != stale_state
+ end
+
+ # Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
+ def target=(target)
+ @target = target
+ loaded!
+ end
+
+ def scoped
+ target_scope.merge(@association_scope)
+ end
+
+ # Construct the scope for this association.
+ #
+ # Note that the association_scope is merged into the target_scope only when the
+ # scoped method is called. This is because at that point the call may be surrounded
+ # by scope.scoping { ... } or with_scope { ... } etc, which affects the scope which
+ # actually gets built.
+ def construct_scope
+ if klass
+ @association_scope = AssociationScope.new(self).scope
+ end
+ end
+
+ # Set the inverse association, if possible
+ def set_inverse_instance(record)
+ if record && invertible_for?(record)
+ inverse = record.association(inverse_reflection_for(record).name)
+ inverse.target = owner
+ end
+ end
+
+ # This class of the target. belongs_to polymorphic overrides this to look at the
+ # polymorphic_type field on the owner.
+ def klass
+ reflection.klass
+ end
+
+ # Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the
+ # through association's scope)
+ def target_scope
+ klass.scoped
+ end
+
+ # Loads the \target if needed and returns it.
+ #
+ # This method is abstract in the sense that it relies on +find_target+,
+ # which is expected to be provided by descendants.
+ #
+ # If the \target is already \loaded it is just returned. Thus, you can call
+ # +load_target+ unconditionally to get the \target.
+ #
+ # ActiveRecord::RecordNotFound is rescued within the method, and it is
+ # not reraised. The proxy is \reset and +nil+ is the return value.
+ def load_target
+ if find_target?
+ begin
+ if IdentityMap.enabled? && association_class && association_class.respond_to?(:base_class)
+ @target = IdentityMap.get(association_class, owner[reflection.foreign_key])
+ end
+ rescue NameError
+ nil
+ ensure
+ @target ||= find_target
+ end
+ end
+ loaded!
+ target
+ rescue ActiveRecord::RecordNotFound
+ reset
+ end
+
+ private
+
+ def find_target?
+ !loaded? && (!owner.new_record? || foreign_key_present?) && klass
+ end
+
+ def interpolate(sql, record = nil)
+ if sql.respond_to?(:to_proc)
+ owner.send(:instance_exec, record, &sql)
+ else
+ sql
+ end
+ end
+
+ def creation_attributes
+ attributes = {}
+
+ if [:has_one, :has_many].include?(reflection.macro) && !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)
+ if owner.persisted?
+ creation_attributes.each { |key, value| record[key] = value }
+ end
+ end
+
+ # Should be true if there is a foreign key present on the owner which
+ # references the target. This is used to determine whether we can load
+ # the target if the owner is currently a new record (and therefore
+ # without a key).
+ #
+ # Currently implemented by belongs_to (vanilla and polymorphic) and
+ # has_one/has_many :through associations which go through a belongs_to
+ def foreign_key_present?
+ false
+ end
+
+ # Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
+ # the kind of the class of the associated objects. Meant to be used as
+ # a sanity check when you are about to assign an associated record.
+ def raise_on_type_mismatch(record)
+ unless record.is_a?(reflection.klass) || record.is_a?(reflection.class_name.constantize)
+ message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
+ raise ActiveRecord::AssociationTypeMismatch, message
+ end
+ end
+
+ # Can be redefined by subclasses, notably polymorphic belongs_to
+ # The record parameter is necessary to support polymorphic inverses as we must check for
+ # the association in the specific class of the record.
+ def inverse_reflection_for(record)
+ reflection.inverse_of
+ end
+
+ # Is this association invertible? Can be redefined by subclasses.
+ def invertible_for?(record)
+ inverse_reflection_for(record)
+ end
+
+ # This should be implemented to return the values of the relevant key(s) on the owner,
+ # so that when state_state is different from the value stored on the last find_target,
+ # the target is stale.
+ #
+ # This is only relevant to certain associations, which is why it returns nil by default.
+ def stale_state
+ end
+
+ def association_class
+ @reflection.klass
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb
deleted file mode 100644
index b5159eead3..0000000000
--- a/activerecord/lib/active_record/associations/association_collection.rb
+++ /dev/null
@@ -1,557 +0,0 @@
-require 'set'
-require 'active_support/core_ext/array/wrap'
-
-module ActiveRecord
- module Associations
- # = Active Record Association Collection
- #
- # AssociationCollection is an abstract class that provides common stuff to
- # ease the implementation of association proxies that represent
- # collections. See the class hierarchy in AssociationProxy.
- #
- # You need to be careful with assumptions regarding the target: The proxy
- # does not fetch records from the database until it needs them, but new
- # ones created with +build+ are added to the target. So, the target may be
- # non-empty and still lack children waiting to be read from the database.
- # If you look directly to the database you cannot assume that's the entire
- # collection because new records may have been added to the target, etc.
- #
- # If you need to work on all current children, new and existing records,
- # +load_target+ and the +loaded+ flag are your friends.
- class AssociationCollection < AssociationProxy #:nodoc:
- def initialize(owner, reflection)
- super
- construct_sql
- end
-
- delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped
-
- def select(select = nil)
- if block_given?
- load_target
- @target.select.each { |e| yield e }
- else
- scoped.select(select)
- end
- end
-
- def scoped
- with_scope(construct_scope) { @reflection.klass.scoped }
- end
-
- def find(*args)
- options = args.extract_options!
-
- # If using a custom finder_sql, scan the entire collection.
- if @reflection.options[:finder_sql]
- expects_array = args.first.kind_of?(Array)
- ids = args.flatten.compact.uniq.map { |arg| arg.to_i }
-
- if ids.size == 1
- id = ids.first
- record = load_target.detect { |r| id == r.id }
- expects_array ? [ record ] : record
- else
- load_target.select { |r| ids.include?(r.id) }
- end
- else
- merge_options_from_reflection!(options)
- construct_find_options!(options)
-
- find_scope = construct_scope[:find].slice(:conditions, :order)
-
- with_scope(:find => find_scope) do
- relation = @reflection.klass.send(:construct_finder_arel, options, @reflection.klass.send(:current_scoped_methods))
-
- case args.first
- when :first, :last
- relation.send(args.first)
- when :all
- records = relation.all
- @reflection.options[:uniq] ? uniq(records) : records
- else
- relation.find(*args)
- end
- end
- end
- end
-
- # Fetches the first one using SQL if possible.
- def first(*args)
- if fetch_first_or_last_using_find?(args)
- find(:first, *args)
- else
- load_target unless loaded?
- @target.first(*args)
- end
- end
-
- # Fetches the last one using SQL if possible.
- def last(*args)
- if fetch_first_or_last_using_find?(args)
- find(:last, *args)
- else
- load_target unless loaded?
- @target.last(*args)
- end
- end
-
- def to_ary
- load_target
- if @target.is_a?(Array)
- @target.to_ary
- else
- Array.wrap(@target)
- end
- end
- alias_method :to_a, :to_ary
-
- def reset
- reset_target!
- reset_named_scopes_cache!
- @loaded = false
- end
-
- def build(attributes = {}, &block)
- if attributes.is_a?(Array)
- attributes.collect { |attr| build(attr, &block) }
- else
- build_record(attributes) do |record|
- block.call(record) if block_given?
- set_belongs_to_association_for(record)
- end
- end
- end
-
- # Add +records+ to this association. Returns +self+ so method calls may be chained.
- # Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
- def <<(*records)
- result = true
- load_target if @owner.new_record?
-
- transaction do
- flatten_deeper(records).each do |record|
- raise_on_type_mismatch(record)
- add_record_to_target_with_callbacks(record) do |r|
- result &&= insert_record(record) unless @owner.new_record?
- end
- end
- end
-
- result && self
- end
-
- alias_method :push, :<<
- alias_method :concat, :<<
-
- # Starts a transaction in the association class's database connection.
- #
- # class Author < ActiveRecord::Base
- # has_many :books
- # end
- #
- # Author.first.books.transaction do
- # # same effect as calling Book.transaction
- # end
- def transaction(*args)
- @reflection.klass.transaction(*args) do
- yield
- end
- end
-
- # Remove all records from this association
- #
- # See delete for more info.
- def delete_all
- load_target
- delete(@target)
- reset_target!
- reset_named_scopes_cache!
- end
-
- # Calculate sum using SQL, not Enumerable
- def sum(*args)
- if block_given?
- calculate(:sum, *args) { |*block_args| yield(*block_args) }
- else
- calculate(:sum, *args)
- end
- end
-
- # Count all records using SQL. If the +:counter_sql+ option is set for the association, it will
- # be used for the query. If no +:counter_sql+ was supplied, but +:finder_sql+ was set, the
- # descendant's +construct_sql+ method will have set :counter_sql automatically.
- # Otherwise, construct options and pass them with scope to the target class's +count+.
- def count(column_name = nil, options = {})
- column_name, options = nil, column_name if column_name.is_a?(Hash)
-
- if @reflection.options[:counter_sql] && !options.blank?
- raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
- elsif @reflection.options[:counter_sql]
- @reflection.klass.count_by_sql(@counter_sql)
- else
-
- if @reflection.options[:uniq]
- # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
- column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" unless column_name
- options.merge!(:distinct => true)
- end
-
- value = @reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) }
-
- limit = @reflection.options[:limit]
- offset = @reflection.options[:offset]
-
- if limit || offset
- [ [value - offset.to_i, 0].max, limit.to_i ].min
- else
- value
- end
- end
- end
-
- # Removes +records+ from this association calling +before_remove+ and
- # +after_remove+ callbacks.
- #
- # This method is abstract in the sense that +delete_records+ has to be
- # provided by descendants. Note this method does not imply the records
- # are actually removed from the database, that depends precisely on
- # +delete_records+. They are in any case removed from the collection.
- def delete(*records)
- remove_records(records) do |_records, old_records|
- delete_records(old_records) if old_records.any?
- _records.each { |record| @target.delete(record) }
- end
- end
-
- # Destroy +records+ and remove them from this association calling
- # +before_remove+ and +after_remove+ callbacks.
- #
- # Note that this method will _always_ remove records from the database
- # ignoring the +:dependent+ option.
- def destroy(*records)
- records = find(records) if records.any? {|record| record.kind_of?(Fixnum) || record.kind_of?(String)}
- remove_records(records) do |_records, old_records|
- old_records.each { |record| record.destroy }
- end
-
- load_target
- end
-
- # Removes all records from this association. Returns +self+ so method calls may be chained.
- def clear
- return self if length.zero? # forces load_target if it hasn't happened already
-
- if @reflection.options[:dependent] && @reflection.options[:dependent] == :destroy
- destroy_all
- else
- delete_all
- end
-
- self
- end
-
- # Destroy all the records from this association.
- #
- # See destroy for more info.
- def destroy_all
- load_target
- destroy(@target).tap do
- reset_target!
- reset_named_scopes_cache!
- end
- end
-
- def create(attrs = {})
- if attrs.is_a?(Array)
- attrs.collect { |attr| create(attr) }
- else
- create_record(attrs) do |record|
- yield(record) if block_given?
- record.save
- end
- end
- end
-
- def create!(attrs = {})
- create_record(attrs) do |record|
- yield(record) if block_given?
- record.save!
- end
- end
-
- # Returns the size of the collection by executing a SELECT COUNT(*)
- # query if the collection hasn't been loaded, and calling
- # <tt>collection.size</tt> if it has.
- #
- # If the collection has been already loaded +size+ and +length+ are
- # equivalent. If not and you are going to need the records anyway
- # +length+ will take one less query. Otherwise +size+ is more efficient.
- #
- # This method is abstract in the sense that it relies on
- # +count_records+, which is a method descendants have to provide.
- def size
- if @owner.new_record? || (loaded? && !@reflection.options[:uniq])
- @target.size
- elsif !loaded? && @reflection.options[:group]
- load_target.size
- elsif !loaded? && !@reflection.options[:uniq] && @target.is_a?(Array)
- unsaved_records = @target.select { |r| r.new_record? }
- unsaved_records.size + count_records
- else
- count_records
- end
- end
-
- # Returns the size of the collection calling +size+ on the target.
- #
- # If the collection has been already loaded +length+ and +size+ are
- # equivalent. If not and you are going to need the records anyway this
- # method will take one less query. Otherwise +size+ is more efficient.
- def length
- load_target.size
- end
-
- # Equivalent to <tt>collection.size.zero?</tt>. If the collection has
- # not been already loaded and you are going to fetch the records anyway
- # it is better to check <tt>collection.length.zero?</tt>.
- def empty?
- size.zero?
- end
-
- def any?
- if block_given?
- method_missing(:any?) { |*block_args| yield(*block_args) }
- else
- !empty?
- end
- end
-
- # Returns true if the collection has more than 1 record. Equivalent to collection.size > 1.
- def many?
- if block_given?
- method_missing(:many?) { |*block_args| yield(*block_args) }
- else
- size > 1
- end
- end
-
- def uniq(collection = self)
- seen = Set.new
- collection.inject([]) do |kept, record|
- unless seen.include?(record.id)
- kept << record
- seen << record.id
- end
- kept
- end
- end
-
- # Replace this collection with +other_array+
- # This will perform a diff and delete/add only records that have changed.
- def replace(other_array)
- other_array.each { |val| raise_on_type_mismatch(val) }
-
- load_target
- other = other_array.size < 100 ? other_array : other_array.to_set
- current = @target.size < 100 ? @target : @target.to_set
-
- transaction do
- delete(@target.select { |v| !other.include?(v) })
- concat(other_array.select { |v| !current.include?(v) })
- end
- end
-
- def include?(record)
- return false unless record.is_a?(@reflection.klass)
- load_target if @reflection.options[:finder_sql] && !loaded?
- return @target.include?(record) if loaded?
- exists?(record)
- end
-
- def proxy_respond_to?(method, include_private = false)
- super || @reflection.klass.respond_to?(method, include_private)
- end
-
- protected
- def construct_find_options!(options)
- end
-
- def construct_counter_sql
- if @reflection.options[:counter_sql]
- @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
- elsif @reflection.options[:finder_sql]
- # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
- @reflection.options[:counter_sql] = @reflection.options[:finder_sql].sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
- @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
- else
- @counter_sql = @finder_sql
- end
- end
-
- def load_target
- if !@owner.new_record? || foreign_key_present
- begin
- if !loaded?
- if @target.is_a?(Array) && @target.any?
- @target = find_target.map do |f|
- i = @target.index(f)
- if i
- @target.delete_at(i).tap do |t|
- keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
- t.attributes = f.attributes.except(*keys)
- end
- else
- f
- end
- end + @target
- else
- @target = find_target
- end
- end
- rescue ActiveRecord::RecordNotFound
- reset
- end
- end
-
- loaded if target
- target
- end
-
- def method_missing(method, *args)
- match = DynamicFinderMatch.match(method)
- if match && match.creator?
- attributes = match.attribute_names
- return send(:"find_by_#{attributes.join('_and_')}", *args) || create(Hash[attributes.zip(args)])
- end
-
- if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
- if block_given?
- super { |*block_args| yield(*block_args) }
- else
- super
- end
- elsif @reflection.klass.scopes[method]
- @_named_scopes_cache ||= {}
- @_named_scopes_cache[method] ||= {}
- @_named_scopes_cache[method][args] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) }
- else
- with_scope(construct_scope) do
- if block_given?
- @reflection.klass.send(method, *args) { |*block_args| yield(*block_args) }
- else
- @reflection.klass.send(method, *args)
- end
- end
- end
- end
-
- # overloaded in derived Association classes to provide useful scoping depending on association type.
- def construct_scope
- {}
- end
-
- def reset_target!
- @target = Array.new
- end
-
- def reset_named_scopes_cache!
- @_named_scopes_cache = {}
- end
-
- def find_target
- records =
- if @reflection.options[:finder_sql]
- @reflection.klass.find_by_sql(@finder_sql)
- else
- find(:all)
- end
-
- records = @reflection.options[:uniq] ? uniq(records) : records
- records.each do |record|
- set_inverse_instance(record, @owner)
- end
- records
- end
-
- def add_record_to_target_with_callbacks(record)
- callback(:before_add, record)
- yield(record) if block_given?
- @target ||= [] unless loaded?
- if index = @target.index(record)
- @target[index] = record
- else
- @target << record
- end
- callback(:after_add, record)
- set_inverse_instance(record, @owner)
- record
- end
-
- private
- def create_record(attrs)
- attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
- ensure_owner_is_not_new
- record = @reflection.klass.send(:with_scope, :create => construct_scope[:create]) do
- @reflection.build_association(attrs)
- end
- if block_given?
- add_record_to_target_with_callbacks(record) { |*block_args| yield(*block_args) }
- else
- add_record_to_target_with_callbacks(record)
- end
- end
-
- def build_record(attrs)
- attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
- record = @reflection.build_association(attrs)
- if block_given?
- add_record_to_target_with_callbacks(record) { |*block_args| yield(*block_args) }
- else
- add_record_to_target_with_callbacks(record)
- end
- end
-
- def remove_records(*records)
- records = flatten_deeper(records)
- records.each { |record| raise_on_type_mismatch(record) }
-
- transaction do
- records.each { |record| callback(:before_remove, record) }
- old_records = records.reject { |r| r.new_record? }
- yield(records, old_records)
- records.each { |record| callback(:after_remove, record) }
- end
- end
-
- def callback(method, record)
- callbacks_for(method).each do |callback|
- case callback
- when Symbol
- @owner.send(callback, record)
- when Proc
- callback.call(@owner, record)
- else
- callback.send(method, @owner, record)
- end
- end
- end
-
- def callbacks_for(callback_name)
- full_callback_name = "#{callback_name}_for_#{@reflection.name}"
- @owner.class.read_inheritable_attribute(full_callback_name.to_sym) || []
- end
-
- def ensure_owner_is_not_new
- if @owner.new_record?
- raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
- end
- end
-
- def fetch_first_or_last_using_find?(args)
- args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] ||
- @target.any? { |record| record.new_record? } || args.first.kind_of?(Integer))
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb
deleted file mode 100644
index f333f4d603..0000000000
--- a/activerecord/lib/active_record/associations/association_proxy.rb
+++ /dev/null
@@ -1,295 +0,0 @@
-require 'active_support/core_ext/array/wrap'
-
-module ActiveRecord
- module Associations
- # = Active Record Associations
- #
- # This is the root class of all association proxies:
- #
- # AssociationProxy
- # BelongsToAssociation
- # HasOneAssociation
- # BelongsToPolymorphicAssociation
- # AssociationCollection
- # HasAndBelongsToManyAssociation
- # HasManyAssociation
- # HasManyThroughAssociation
- # HasOneThroughAssociation
- #
- # Association proxies in Active Record are middlemen between the object that
- # holds the association, known as the <tt>@owner</tt>, and the actual associated
- # object, known as the <tt>@target</tt>. The kind of association any proxy is
- # about is available in <tt>@reflection</tt>. That's an instance of the class
- # ActiveRecord::Reflection::AssociationReflection.
- #
- # For example, given
- #
- # class Blog < ActiveRecord::Base
- # has_many :posts
- # end
- #
- # blog = Blog.find(:first)
- #
- # the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
- # <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
- # the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
- #
- # This class has most of the basic instance methods removed, and delegates
- # unknown methods to <tt>@target</tt> via <tt>method_missing</tt>. As a
- # corner case, it even removes the +class+ method and that's why you get
- #
- # blog.posts.class # => Array
- #
- # though the object behind <tt>blog.posts</tt> is not an Array, but an
- # ActiveRecord::Associations::HasManyAssociation.
- #
- # The <tt>@target</tt> object is not \loaded until needed. For example,
- #
- # blog.posts.count
- #
- # is computed directly through SQL and does not trigger by itself the
- # instantiation of the actual post records.
- class AssociationProxy #:nodoc:
- alias_method :proxy_respond_to?, :respond_to?
- alias_method :proxy_extend, :extend
- delegate :to_param, :to => :proxy_target
- instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil\?|send|object_id|to_a)$|^__|proxy_/ }
-
- def initialize(owner, reflection)
- @owner, @reflection = owner, reflection
- @updated = false
- reflection.check_validity!
- Array.wrap(reflection.options[:extend]).each { |ext| proxy_extend(ext) }
- reset
- end
-
- # Returns the owner of the proxy.
- def proxy_owner
- @owner
- end
-
- # Returns the reflection object that represents the association handled
- # by the proxy.
- def proxy_reflection
- @reflection
- end
-
- # Returns the \target of the proxy, same as +target+.
- def proxy_target
- @target
- end
-
- # Does the proxy or its \target respond to +symbol+?
- def respond_to?(*args)
- proxy_respond_to?(*args) || (load_target && @target.respond_to?(*args))
- end
-
- # Forwards <tt>===</tt> explicitly to the \target because the instance method
- # removal above doesn't catch it. Loads the \target if needed.
- def ===(other)
- load_target
- other === @target
- end
-
- # Returns the name of the table of the related class:
- #
- # post.comments.aliased_table_name # => "comments"
- #
- def aliased_table_name
- @reflection.klass.table_name
- end
-
- # Returns the SQL string that corresponds to the <tt>:conditions</tt>
- # option of the macro, if given, or +nil+ otherwise.
- def conditions
- @conditions ||= interpolate_sql(@reflection.sanitized_conditions) if @reflection.sanitized_conditions
- end
- alias :sql_conditions :conditions
-
- # Resets the \loaded flag to +false+ and sets the \target to +nil+.
- def reset
- @loaded = false
- @target = nil
- end
-
- # Reloads the \target and returns +self+ on success.
- def reload
- reset
- load_target
- self unless @target.nil?
- end
-
- # Has the \target been already \loaded?
- def loaded?
- @loaded
- end
-
- # Asserts the \target has been loaded setting the \loaded flag to +true+.
- def loaded
- @loaded = true
- end
-
- # Returns the target of this proxy, same as +proxy_target+.
- def target
- @target
- end
-
- # Sets the target of this proxy to <tt>\target</tt>, and the \loaded flag to +true+.
- def target=(target)
- @target = target
- loaded
- end
-
- # Forwards the call to the target. Loads the \target if needed.
- def inspect
- load_target
- @target.inspect
- end
-
- def send(method, *args)
- if proxy_respond_to?(method)
- super
- else
- load_target
- @target.send(method, *args)
- end
- end
-
- protected
- # Does the association have a <tt>:dependent</tt> option?
- def dependent?
- @reflection.options[:dependent]
- end
-
- def interpolate_sql(sql, record = nil)
- @owner.send(:interpolate_sql, sql, record)
- end
-
- # Forwards the call to the reflection class.
- def sanitize_sql(sql, table_name = @reflection.klass.table_name)
- @reflection.klass.send(:sanitize_sql, sql, table_name)
- end
-
- # Assigns the ID of the owner to the corresponding foreign key in +record+.
- # If the association is polymorphic the type of the owner is also set.
- def set_belongs_to_association_for(record)
- if @reflection.options[:as]
- record["#{@reflection.options[:as]}_id"] = @owner.id unless @owner.new_record?
- record["#{@reflection.options[:as]}_type"] = @owner.class.base_class.name.to_s
- else
- unless @owner.new_record?
- primary_key = @reflection.options[:primary_key] || :id
- record[@reflection.primary_key_name] = @owner.send(primary_key)
- end
- end
- end
-
- # Merges into +options+ the ones coming from the reflection.
- def merge_options_from_reflection!(options)
- options.reverse_merge!(
- :group => @reflection.options[:group],
- :having => @reflection.options[:having],
- :limit => @reflection.options[:limit],
- :offset => @reflection.options[:offset],
- :joins => @reflection.options[:joins],
- :include => @reflection.options[:include],
- :select => @reflection.options[:select],
- :readonly => @reflection.options[:readonly]
- )
- end
-
- # Forwards +with_scope+ to the reflection.
- def with_scope(*args, &block)
- @reflection.klass.send :with_scope, *args, &block
- end
-
- private
- # Forwards any missing method call to the \target.
- def method_missing(method, *args)
- if load_target
- unless @target.respond_to?(method)
- message = "undefined method `#{method.to_s}' for \"#{@target}\":#{@target.class.to_s}"
- raise NoMethodError, message
- end
-
- if block_given?
- @target.send(method, *args) { |*block_args| yield(*block_args) }
- else
- @target.send(method, *args)
- end
- end
- end
-
- # Loads the \target if needed and returns it.
- #
- # This method is abstract in the sense that it relies on +find_target+,
- # which is expected to be provided by descendants.
- #
- # If the \target is already \loaded it is just returned. Thus, you can call
- # +load_target+ unconditionally to get the \target.
- #
- # ActiveRecord::RecordNotFound is rescued within the method, and it is
- # not reraised. The proxy is \reset and +nil+ is the return value.
- def load_target
- return nil unless defined?(@loaded)
-
- if !loaded? and (!@owner.new_record? || foreign_key_present)
- @target = find_target
- end
-
- @loaded = true
- @target
- rescue ActiveRecord::RecordNotFound
- reset
- end
-
- # Can be overwritten by associations that might have the foreign key
- # available for an association without having the object itself (and
- # still being a new record). Currently, only +belongs_to+ presents
- # this scenario (both vanilla and polymorphic).
- def foreign_key_present
- false
- end
-
- # Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
- # the kind of the class of the associated objects. Meant to be used as
- # a sanity check when you are about to assign an associated record.
- def raise_on_type_mismatch(record)
- unless record.is_a?(@reflection.klass) || record.is_a?(@reflection.class_name.constantize)
- message = "#{@reflection.class_name}(##{@reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
- raise ActiveRecord::AssociationTypeMismatch, message
- end
- end
-
- if RUBY_VERSION < '1.9.2'
- # Array#flatten has problems with recursive arrays before Ruby 1.9.2.
- # Going one level deeper solves the majority of the problems.
- def flatten_deeper(array)
- array.collect { |element| (element.respond_to?(:flatten) && !element.is_a?(Hash)) ? element.flatten : element }.flatten
- end
- else
- def flatten_deeper(array)
- array.flatten
- end
- end
-
- # Returns the ID of the owner, quoted if needed.
- def owner_quoted_id
- @owner.quoted_id
- end
-
- def set_inverse_instance(record, instance)
- return if record.nil? || !we_can_set_the_inverse_on_this?(record)
- inverse_relationship = @reflection.inverse_of
- unless inverse_relationship.nil?
- record.send(:"set_#{inverse_relationship.name}_target", instance)
- end
- end
-
- # Override in subclasses
- def we_can_set_the_inverse_on_this?(record)
- false
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
new file mode 100644
index 0000000000..ab102b2b8f
--- /dev/null
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -0,0 +1,120 @@
+module ActiveRecord
+ module Associations
+ class AssociationScope #:nodoc:
+ include JoinHelper
+
+ attr_reader :association, :alias_tracker
+
+ delegate :klass, :owner, :reflection, :interpolate, :to => :association
+ delegate :chain, :conditions, :options, :source_options, :active_record, :to => :reflection
+
+ def initialize(association)
+ @association = association
+ @alias_tracker = AliasTracker.new
+ end
+
+ def scope
+ scope = klass.unscoped
+ scope = scope.extending(*Array.wrap(options[:extend]))
+
+ # It's okay to just apply all these like this. The options will only be present if the
+ # association supports that option; this is enforced by the association builder.
+ scope = scope.apply_finder_options(options.slice(
+ :readonly, :include, :order, :limit, :joins, :group, :having, :offset))
+
+ if options[:through] && !options[:include]
+ scope = scope.includes(source_options[:include])
+ end
+
+ if select = select_value
+ scope = scope.select(select)
+ end
+
+ add_constraints(scope)
+ end
+
+ private
+
+ def select_value
+ select_value = options[:select]
+
+ if reflection.collection?
+ select_value ||= options[:uniq] && "DISTINCT #{reflection.quoted_table_name}.*"
+ end
+
+ if reflection.macro == :has_and_belongs_to_many
+ select_value ||= reflection.klass.arel_table[Arel.star]
+ end
+
+ select_value
+ end
+
+ def add_constraints(scope)
+ tables = construct_tables
+
+ 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.active_record_primary_key].
+ eq(join_table[reflection.association_foreign_key])
+ ))
+
+ table, foreign_table = join_table, tables.first
+ end
+
+ if reflection.source_macro == :belongs_to
+ key = reflection.association_primary_key
+ foreign_key = reflection.foreign_key
+ else
+ key = reflection.foreign_key
+ foreign_key = reflection.active_record_primary_key
+ end
+
+ if reflection == chain.last
+ scope = scope.where(table[key].eq(owner[foreign_key]))
+
+ conditions[i].each do |condition|
+ if options[:through] && condition.is_a?(Hash)
+ condition = { table.name => condition }
+ end
+
+ scope = scope.where(interpolate(condition))
+ end
+ else
+ constraint = table[key].eq(foreign_table[foreign_key])
+ join = join(foreign_table, constraint)
+
+ scope = scope.joins(join)
+
+ unless conditions[i].empty?
+ scope = scope.where(sanitize(conditions[i], table))
+ end
+ 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
+
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index 4558872a2b..c263edd2c6 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -1,41 +1,17 @@
module ActiveRecord
# = Active Record Belongs To Associations
module Associations
- class BelongsToAssociation < AssociationProxy #:nodoc:
- def create(attributes = {})
- replace(@reflection.create_association(attributes))
- end
-
- def build(attributes = {})
- replace(@reflection.build_association(attributes))
- end
-
+ class BelongsToAssociation < SingularAssociation #:nodoc:
def replace(record)
- counter_cache_name = @reflection.counter_cache_column
-
- if record.nil?
- if counter_cache_name && !@owner.new_record?
- @reflection.klass.decrement_counter(counter_cache_name, previous_record_id) if @owner[@reflection.primary_key_name]
- end
-
- @target = @owner[@reflection.primary_key_name] = nil
- else
- raise_on_type_mismatch(record)
+ raise_on_type_mismatch(record) if record
- if counter_cache_name && !@owner.new_record? && record.id != @owner[@reflection.primary_key_name]
- @reflection.klass.increment_counter(counter_cache_name, record.id)
- @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
- end
-
- @target = (AssociationProxy === record ? record.target : record)
- @owner[@reflection.primary_key_name] = record_id(record) unless record.new_record?
- @updated = true
- end
+ update_counters(record)
+ replace_keys(record)
+ set_inverse_instance(record)
- set_inverse_instance(record, @owner)
+ @updated = true if record
- loaded
- record
+ self.target = record
end
def updated?
@@ -43,44 +19,52 @@ module ActiveRecord
end
private
- def find_target
- find_method = if @reflection.options[:primary_key]
- "find_by_#{@reflection.options[:primary_key]}"
- else
- "find"
- end
- the_target = @reflection.klass.send(find_method,
- @owner[@reflection.primary_key_name],
- :select => @reflection.options[:select],
- :conditions => conditions,
- :include => @reflection.options[:include],
- :readonly => @reflection.options[:readonly]
- ) if @owner[@reflection.primary_key_name]
- set_inverse_instance(the_target, @owner)
- the_target
+
+ 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
- def foreign_key_present
- !@owner[@reflection.primary_key_name].nil?
+ # Checks whether record is different to the current target, without loading it
+ def different_target?(record)
+ record.nil? && owner[reflection.foreign_key] ||
+ record.id != owner[reflection.foreign_key]
+ end
+
+ def replace_keys(record)
+ owner[reflection.foreign_key] = record && record[reflection.association_primary_key]
+ end
+
+ def foreign_key_present?
+ owner[reflection.foreign_key]
end
# NOTE - for now, we're only supporting inverse setting from belongs_to back onto
# has_one associations.
- def we_can_set_the_inverse_on_this?(record)
- @reflection.has_inverse? && @reflection.inverse_of.macro == :has_one
+ def invertible_for?(record)
+ inverse = inverse_reflection_for(record)
+ inverse && inverse.macro == :has_one
end
- def record_id(record)
- record.send(@reflection.options[:primary_key] || :id)
+ def target_id
+ if options[:primary_key]
+ owner.send(reflection.name).try(:id)
+ else
+ owner[reflection.foreign_key]
+ end
end
- def previous_record_id
- @previous_record_id ||= if @reflection.options[:primary_key]
- previous_record = @owner.send(@reflection.name)
- previous_record.nil? ? nil : previous_record.id
- else
- @owner[@reflection.primary_key_name]
- end
+ def stale_state
+ owner[reflection.foreign_key].to_s
end
end
end
diff --git a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
index 38454ec242..1ca448236e 100644
--- a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
@@ -1,77 +1,33 @@
module ActiveRecord
# = Active Record Belongs To Polymorphic Association
module Associations
- class BelongsToPolymorphicAssociation < AssociationProxy #:nodoc:
- def replace(record)
- if record.nil?
- @target = @owner[@reflection.primary_key_name] = @owner[@reflection.options[:foreign_type]] = nil
- else
- @target = (AssociationProxy === record ? record.target : record)
-
- @owner[@reflection.primary_key_name] = record_id(record)
- @owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s
-
- @updated = true
- end
-
- set_inverse_instance(record, @owner)
- loaded
- record
- end
-
- def updated?
- @updated
- end
-
+ class BelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc:
private
- # NOTE - for now, we're only supporting inverse setting from belongs_to back onto
- # has_one associations.
- def we_can_set_the_inverse_on_this?(record)
- if @reflection.has_inverse?
- inverse_association = @reflection.polymorphic_inverse_of(record.class)
- inverse_association && inverse_association.macro == :has_one
- else
- false
- end
+ def replace_keys(record)
+ super
+ owner[reflection.foreign_type] = record && record.class.base_class.name
end
- def set_inverse_instance(record, instance)
- return if record.nil? || !we_can_set_the_inverse_on_this?(record)
- inverse_relationship = @reflection.polymorphic_inverse_of(record.class)
- unless inverse_relationship.nil?
- record.send(:"set_#{inverse_relationship.name}_target", instance)
- end
+ def different_target?(record)
+ super || record.class != klass
end
- def find_target
- return nil if association_class.nil?
-
- target =
- if @reflection.options[:conditions]
- association_class.find(
- @owner[@reflection.primary_key_name],
- :select => @reflection.options[:select],
- :conditions => conditions,
- :include => @reflection.options[:include]
- )
- else
- association_class.find(@owner[@reflection.primary_key_name], :select => @reflection.options[:select], :include => @reflection.options[:include])
- end
- set_inverse_instance(target, @owner)
- target
+ def inverse_reflection_for(record)
+ reflection.polymorphic_inverse_of(record.class)
end
- def foreign_key_present
- !@owner[@reflection.primary_key_name].nil?
+ def klass
+ type = owner[reflection.foreign_type]
+ type && type.constantize
end
- def record_id(record)
- record.send(@reflection.options[:primary_key] || :id)
+ def raise_on_type_mismatch(record)
+ # A polymorphic association cannot have a type mismatch, by definition
end
- def association_class
- @owner[@reflection.options[:foreign_type]] ? @owner[@reflection.options[:foreign_type]].constantize : nil
+ def stale_state
+ [super, owner[reflection.foreign_type].to_s]
end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
new file mode 100644
index 0000000000..96fca97440
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -0,0 +1,53 @@
+module ActiveRecord::Associations::Builder
+ class Association #:nodoc:
+ class_attribute :valid_options
+ self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate]
+
+ # Set by subclasses
+ class_attribute :macro
+
+ attr_reader :model, :name, :options, :reflection
+
+ def self.build(model, name, options)
+ new(model, name, options).build
+ end
+
+ def initialize(model, name, options)
+ @model, @name, @options = model, name, options
+ end
+
+ def build
+ validate_options
+ reflection = model.create_reflection(self.class.macro, name, options, model)
+ define_accessors
+ reflection
+ end
+
+ private
+
+ def validate_options
+ options.assert_valid_keys(self.class.valid_options)
+ end
+
+ def define_accessors
+ define_readers
+ define_writers
+ end
+
+ def define_readers
+ name = self.name
+
+ model.redefine_method(name) do |*params|
+ association(name).reader(*params)
+ end
+ end
+
+ def define_writers
+ name = self.name
+
+ model.redefine_method("#{name}=") do |value|
+ association(name).writer(value)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
new file mode 100644
index 0000000000..964e7fddc8
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -0,0 +1,83 @@
+module ActiveRecord::Associations::Builder
+ class BelongsTo < SingularAssociation #:nodoc:
+ self.macro = :belongs_to
+
+ self.valid_options += [:foreign_type, :polymorphic, :touch]
+
+ def constructable?
+ !options[:polymorphic]
+ end
+
+ def build
+ reflection = super
+ add_counter_cache_callbacks(reflection) if options[:counter_cache]
+ add_touch_callbacks(reflection) if options[:touch]
+ configure_dependency
+ reflection
+ end
+
+ private
+
+ def add_counter_cache_callbacks(reflection)
+ cache_column = reflection.counter_cache_column
+ name = self.name
+
+ method_name = "belongs_to_counter_cache_after_create_for_#{name}"
+ model.redefine_method(method_name) do
+ record = send(name)
+ record.class.increment_counter(cache_column, record.id) unless record.nil?
+ end
+ model.after_create(method_name)
+
+ method_name = "belongs_to_counter_cache_before_destroy_for_#{name}"
+ model.redefine_method(method_name) do
+ record = send(name)
+ record.class.decrement_counter(cache_column, record.id) unless record.nil?
+ end
+ model.before_destroy(method_name)
+
+ model.send(:module_eval,
+ "#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)", __FILE__, __LINE__
+ )
+ end
+
+ def add_touch_callbacks(reflection)
+ name = self.name
+ method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ touch = options[:touch]
+
+ model.redefine_method(method_name) do
+ record = send(name)
+
+ unless record.nil?
+ if touch == true
+ record.touch
+ else
+ record.touch(touch)
+ end
+ end
+ end
+
+ model.after_save(method_name)
+ model.after_touch(method_name)
+ model.after_destroy(method_name)
+ end
+
+ def configure_dependency
+ if options[:dependent]
+ unless [:destroy, :delete].include?(options[:dependent])
+ raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{options[:dependent].inspect})"
+ end
+
+ method_name = "belongs_to_dependent_#{options[:dependent]}_for_#{name}"
+ model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1)
+ def #{method_name}
+ association = #{name}
+ association.#{options[:dependent]} if association
+ end
+ eoruby
+ model.after_destroy method_name
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb
new file mode 100644
index 0000000000..f62209a226
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/collection_association.rb
@@ -0,0 +1,75 @@
+module ActiveRecord::Associations::Builder
+ class CollectionAssociation < Association #:nodoc:
+ CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
+
+ self.valid_options += [
+ :table_name, :order, :group, :having, :limit, :offset, :uniq, :finder_sql,
+ :counter_sql, :before_add, :after_add, :before_remove, :after_remove
+ ]
+
+ attr_reader :block_extension
+
+ def self.build(model, name, options, &extension)
+ new(model, name, options, &extension).build
+ end
+
+ def initialize(model, name, options, &extension)
+ super(model, name, options)
+ @block_extension = extension
+ end
+
+ def build
+ wrap_block_extension
+ reflection = super
+ CALLBACKS.each { |callback_name| define_callback(callback_name) }
+ reflection
+ end
+
+ def writable?
+ true
+ end
+
+ private
+
+ def wrap_block_extension
+ options[:extend] = Array.wrap(options[:extend])
+
+ if block_extension
+ silence_warnings do
+ model.parent.const_set(extension_module_name, Module.new(&block_extension))
+ end
+ options[:extend].push("#{model.parent}::#{extension_module_name}".constantize)
+ end
+ end
+
+ def extension_module_name
+ @extension_module_name ||= "#{model.to_s.demodulize}#{name.to_s.camelize}AssociationExtension"
+ end
+
+ def define_callback(callback_name)
+ full_callback_name = "#{callback_name}_for_#{name}"
+
+ # TODO : why do i need method_defined? I think its because of the inheritance chain
+ model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name)
+ model.send("#{full_callback_name}=", Array.wrap(options[callback_name.to_sym]))
+ end
+
+ def define_readers
+ super
+
+ name = self.name
+ model.redefine_method("#{name.to_s.singularize}_ids") do
+ association(name).ids_reader
+ end
+ end
+
+ def define_writers
+ super
+
+ name = self.name
+ model.redefine_method("#{name.to_s.singularize}_ids=") do |ids|
+ association(name).ids_writer(ids)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
new file mode 100644
index 0000000000..4b48757da7
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
@@ -0,0 +1,63 @@
+module ActiveRecord::Associations::Builder
+ class HasAndBelongsToMany < CollectionAssociation #:nodoc:
+ self.macro = :has_and_belongs_to_many
+
+ self.valid_options += [:join_table, :association_foreign_key, :delete_sql, :insert_sql]
+
+ def build
+ reflection = super
+ check_validity(reflection)
+ define_after_destroy_method
+ reflection
+ end
+
+ private
+
+ def define_after_destroy_method
+ name = self.name
+ model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1)
+ def #{after_destroy_method_name}
+ association(#{name.to_sym.inspect}).delete_all
+ end
+ eoruby
+ model.after_destroy after_destroy_method_name
+ end
+
+ def after_destroy_method_name
+ "has_and_belongs_to_many_after_destroy_for_#{name}"
+ end
+
+ # TODO: These checks should probably be moved into the Reflection, and we should not be
+ # redefining the options[:join_table] value - instead we should define a
+ # reflection.join_table method.
+ def check_validity(reflection)
+ if reflection.association_foreign_key == reflection.foreign_key
+ raise ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
+ end
+
+ reflection.options[:join_table] ||= join_table_name(
+ model.send(:undecorated_table_name, model.to_s),
+ model.send(:undecorated_table_name, reflection.class_name)
+ )
+
+ if model.connection.supports_primary_key? && (model.connection.primary_key(reflection.options[:join_table]) rescue false)
+ raise ActiveRecord::HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection)
+ end
+ end
+
+ # Generates a join table name from two provided table names.
+ # The names in the join table names end up in lexicographic order.
+ #
+ # join_table_name("members", "clubs") # => "clubs_members"
+ # join_table_name("members", "special_clubs") # => "members_special_clubs"
+ def join_table_name(first_table_name, second_table_name)
+ if first_table_name < second_table_name
+ join_table = "#{first_table_name}_#{second_table_name}"
+ else
+ join_table = "#{second_table_name}_#{first_table_name}"
+ end
+
+ model.table_name_prefix + join_table + model.table_name_suffix
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb
new file mode 100644
index 0000000000..77bb66228d
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_many.rb
@@ -0,0 +1,63 @@
+module ActiveRecord::Associations::Builder
+ class HasMany < CollectionAssociation #:nodoc:
+ self.macro = :has_many
+
+ self.valid_options += [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of]
+
+ def build
+ reflection = super
+ configure_dependency
+ reflection
+ end
+
+ private
+
+ def configure_dependency
+ if options[:dependent]
+ unless [:destroy, :delete_all, :nullify, :restrict].include?(options[:dependent])
+ raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, " \
+ ":nullify or :restrict (#{options[:dependent].inspect})"
+ end
+
+ send("define_#{options[:dependent]}_dependency_method")
+ model.before_destroy dependency_method_name
+ end
+ end
+
+ def define_destroy_dependency_method
+ name = self.name
+ model.send(:define_method, dependency_method_name) do
+ send(name).each do |o|
+ # No point in executing the counter update since we're going to destroy the parent anyway
+ counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym
+ if o.respond_to?(counter_method)
+ class << o
+ self
+ end.send(:define_method, counter_method, Proc.new {})
+ end
+ end
+
+ send(name).delete_all
+ end
+ end
+
+ def define_delete_all_dependency_method
+ name = self.name
+ model.send(:define_method, dependency_method_name) do
+ send(name).delete_all
+ end
+ end
+ alias :define_nullify_dependency_method :define_delete_all_dependency_method
+
+ def define_restrict_dependency_method
+ name = self.name
+ model.send(:define_method, dependency_method_name) do
+ raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).empty?
+ end
+ end
+
+ def dependency_method_name
+ "has_many_dependent_for_#{name}"
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/has_one.rb b/activerecord/lib/active_record/associations/builder/has_one.rb
new file mode 100644
index 0000000000..07ba5d088e
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_one.rb
@@ -0,0 +1,61 @@
+module ActiveRecord::Associations::Builder
+ class HasOne < SingularAssociation #:nodoc:
+ self.macro = :has_one
+
+ self.valid_options += [:order, :as]
+
+ class_attribute :through_options
+ self.through_options = [:through, :source, :source_type]
+
+ def constructable?
+ !options[:through]
+ end
+
+ def build
+ reflection = super
+ configure_dependency unless options[:through]
+ reflection
+ end
+
+ private
+
+ def validate_options
+ valid_options = self.class.valid_options
+ valid_options += self.class.through_options if options[:through]
+ options.assert_valid_keys(valid_options)
+ end
+
+ def configure_dependency
+ if options[:dependent]
+ unless [:destroy, :delete, :nullify, :restrict].include?(options[:dependent])
+ raise ArgumentError, "The :dependent option expects either :destroy, :delete, " \
+ ":nullify or :restrict (#{options[:dependent].inspect})"
+ end
+
+ send("define_#{options[:dependent]}_dependency_method")
+ model.before_destroy dependency_method_name
+ end
+ end
+
+ def dependency_method_name
+ "has_one_dependent_#{options[:dependent]}_for_#{name}"
+ end
+
+ def define_destroy_dependency_method
+ model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1)
+ def #{dependency_method_name}
+ association(#{name.to_sym.inspect}).delete
+ end
+ eoruby
+ end
+ alias :define_delete_dependency_method :define_destroy_dependency_method
+ alias :define_nullify_dependency_method :define_destroy_dependency_method
+
+ def define_restrict_dependency_method
+ name = self.name
+ model.redefine_method(dependency_method_name) do
+ raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).nil?
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/singular_association.rb b/activerecord/lib/active_record/associations/builder/singular_association.rb
new file mode 100644
index 0000000000..06a414b874
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/singular_association.rb
@@ -0,0 +1,32 @@
+module ActiveRecord::Associations::Builder
+ class SingularAssociation < Association #:nodoc:
+ self.valid_options += [:remote, :dependent, :counter_cache, :primary_key, :inverse_of]
+
+ def constructable?
+ true
+ end
+
+ def define_accessors
+ super
+ define_constructors if constructable?
+ end
+
+ private
+
+ def define_constructors
+ name = self.name
+
+ model.redefine_method("build_#{name}") do |*params|
+ association(name).build(*params)
+ end
+
+ model.redefine_method("create_#{name}") do |*params|
+ association(name).create(*params)
+ end
+
+ model.redefine_method("create_#{name}!") do |*params|
+ association(name).create!(*params)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
new file mode 100644
index 0000000000..9f4fc44cc6
--- /dev/null
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -0,0 +1,536 @@
+require 'active_support/core_ext/array/wrap'
+
+module ActiveRecord
+ module Associations
+ # = Active Record Association Collection
+ #
+ # AssociationCollection is an abstract class that provides common stuff to
+ # ease the implementation of association proxies that represent
+ # collections. See the class hierarchy in AssociationProxy.
+ #
+ # You need to be careful with assumptions regarding the target: The proxy
+ # does not fetch records from the database until it needs them, but new
+ # ones created with +build+ are added to the target. So, the target may be
+ # non-empty and still lack children waiting to be read from the database.
+ # If you look directly to the database you cannot assume that's the entire
+ # collection because new records may have been added to the target, etc.
+ #
+ # If you need to work on all current children, new and existing records,
+ # +load_target+ and the +loaded+ flag are your friends.
+ class CollectionAssociation < Association #:nodoc:
+ attr_reader :proxy
+
+ def initialize(owner, reflection)
+ # When scopes are created via method_missing on the proxy, they are stored so that
+ # any records fetched from the database are kept around for future use.
+ @scopes_cache = Hash.new do |hash, method|
+ hash[method] = { }
+ end
+
+ super
+
+ @proxy = CollectionProxy.new(self)
+ end
+
+ # Implements the reader method, e.g. foo.items for Foo.has_many :items
+ def reader(force_reload = false)
+ if force_reload
+ klass.uncached { reload }
+ elsif stale_target?
+ reload
+ end
+
+ proxy
+ end
+
+ # Implements the writer method, e.g. foo.items= for Foo.has_many :items
+ def writer(records)
+ replace(records)
+ end
+
+ # Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items
+ def ids_reader
+ if loaded? || options[:finder_sql]
+ load_target.map do |record|
+ record.send(reflection.association_primary_key)
+ end
+ else
+ column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
+
+ scoped.select(column).except(:includes).map! do |record|
+ record.send(reflection.association_primary_key)
+ end
+ end
+ end
+
+ # Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items
+ def ids_writer(ids)
+ pk_column = reflection.primary_key_column
+ ids = Array.wrap(ids).reject { |id| id.blank? }
+ ids.map! { |i| pk_column.type_cast(i) }
+ replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids))
+ end
+
+ def reset
+ @loaded = false
+ @target = []
+ @scopes_cache.clear
+ end
+
+ def select(select = nil)
+ if block_given?
+ load_target.select.each { |e| yield e }
+ else
+ scoped.select(select)
+ end
+ end
+
+ def find(*args)
+ if options[:finder_sql]
+ find_by_scan(*args)
+ else
+ scoped.find(*args)
+ end
+ end
+
+ def first(*args)
+ first_or_last(:first, *args)
+ end
+
+ def last(*args)
+ first_or_last(:last, *args)
+ end
+
+ def build(attributes = {}, &block)
+ build_or_create(attributes, :build, &block)
+ end
+
+ def create(attributes = {}, &block)
+ unless owner.persisted?
+ raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
+ end
+
+ build_or_create(attributes, :create, &block)
+ end
+
+ def create!(attrs = {}, &block)
+ record = create(attrs, &block)
+ Array.wrap(record).each(&:save!)
+ record
+ end
+
+ # Add +records+ to this association. Returns +self+ so method calls may be chained.
+ # Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
+ def concat(*records)
+ result = true
+ load_target if owner.new_record?
+
+ transaction do
+ records.flatten.each do |record|
+ raise_on_type_mismatch(record)
+ add_to_target(record) do |r|
+ result &&= insert_record(record) unless owner.new_record?
+ end
+ end
+ end
+
+ result && records
+ end
+
+ # Starts a transaction in the association class's database connection.
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :books
+ # end
+ #
+ # Author.first.books.transaction do
+ # # same effect as calling Book.transaction
+ # end
+ def transaction(*args)
+ reflection.klass.transaction(*args) do
+ yield
+ end
+ end
+
+ # Remove all records from this association
+ #
+ # See delete for more info.
+ def delete_all
+ delete(load_target).tap do
+ reset
+ loaded!
+ end
+ end
+
+ # Destroy all the records from this association.
+ #
+ # See destroy for more info.
+ def destroy_all
+ destroy(load_target).tap do
+ reset
+ loaded!
+ end
+ end
+
+ # Calculate sum using SQL, not Enumerable
+ def sum(*args)
+ if block_given?
+ scoped.sum(*args) { |*block_args| yield(*block_args) }
+ else
+ scoped.sum(*args)
+ end
+ end
+
+ # Count all records using SQL. If the +:counter_sql+ or +:finder_sql+ option is set for the
+ # association, it will be used for the query. Otherwise, construct options and pass them with
+ # scope to the target class's +count+.
+ def count(column_name = nil, count_options = {})
+ column_name, count_options = nil, column_name if column_name.is_a?(Hash)
+
+ if options[:counter_sql] || options[:finder_sql]
+ unless count_options.blank?
+ raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
+ end
+
+ reflection.klass.count_by_sql(custom_counter_sql)
+ else
+ if options[:uniq]
+ # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
+ column_name ||= reflection.klass.primary_key
+ count_options.merge!(:distinct => true)
+ end
+
+ value = scoped.count(column_name, count_options)
+
+ limit = options[:limit]
+ offset = options[:offset]
+
+ if limit || offset
+ [ [value - offset.to_i, 0].max, limit.to_i ].min
+ else
+ value
+ end
+ end
+ end
+
+ # Removes +records+ from this association calling +before_remove+ and
+ # +after_remove+ callbacks.
+ #
+ # This method is abstract in the sense that +delete_records+ has to be
+ # provided by descendants. Note this method does not imply the records
+ # are actually removed from the database, that depends precisely on
+ # +delete_records+. They are in any case removed from the collection.
+ def delete(*records)
+ delete_or_destroy(records, options[:dependent])
+ end
+
+ # Destroy +records+ and remove them from this association calling
+ # +before_remove+ and +after_remove+ callbacks.
+ #
+ # Note that this method will _always_ remove records from the database
+ # ignoring the +:dependent+ option.
+ def destroy(*records)
+ records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
+ delete_or_destroy(records, :destroy)
+ end
+
+ # Returns the size of the collection by executing a SELECT COUNT(*)
+ # query if the collection hasn't been loaded, and calling
+ # <tt>collection.size</tt> if it has.
+ #
+ # If the collection has been already loaded +size+ and +length+ are
+ # equivalent. If not and you are going to need the records anyway
+ # +length+ will take one less query. Otherwise +size+ is more efficient.
+ #
+ # This method is abstract in the sense that it relies on
+ # +count_records+, which is a method descendants have to provide.
+ def size
+ if owner.new_record? || (loaded? && !options[:uniq])
+ target.size
+ elsif !loaded? && options[:group]
+ load_target.size
+ elsif !loaded? && !options[:uniq] && target.is_a?(Array)
+ unsaved_records = target.select { |r| r.new_record? }
+ unsaved_records.size + count_records
+ else
+ count_records
+ end
+ end
+
+ # Returns the size of the collection calling +size+ on the target.
+ #
+ # If the collection has been already loaded +length+ and +size+ are
+ # equivalent. If not and you are going to need the records anyway this
+ # method will take one less query. Otherwise +size+ is more efficient.
+ def length
+ load_target.size
+ end
+
+ # Equivalent to <tt>collection.size.zero?</tt>. If the collection has
+ # not been already loaded and you are going to fetch the records anyway
+ # it is better to check <tt>collection.length.zero?</tt>.
+ def empty?
+ size.zero?
+ end
+
+ def any?
+ if block_given?
+ load_target.any? { |*block_args| yield(*block_args) }
+ else
+ !empty?
+ end
+ end
+
+ # Returns true if the collection has more than 1 record. Equivalent to collection.size > 1.
+ def many?
+ if block_given?
+ load_target.many? { |*block_args| yield(*block_args) }
+ else
+ size > 1
+ end
+ end
+
+ def uniq(collection = load_target)
+ seen = {}
+ collection.find_all do |record|
+ seen[record.id] = true unless seen.key?(record.id)
+ end
+ end
+
+ # Replace this collection with +other_array+
+ # This will perform a diff and delete/add only records that have changed.
+ def replace(other_array)
+ other_array.each { |val| raise_on_type_mismatch(val) }
+ original_target = load_target.dup
+
+ transaction do
+ delete(target - other_array)
+
+ unless concat(other_array - target)
+ @target = original_target
+ raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
+ "new records could not be saved."
+ end
+ end
+ end
+
+ def include?(record)
+ if record.is_a?(reflection.klass)
+ if record.new_record?
+ include_in_memory?(record)
+ else
+ load_target if options[:finder_sql]
+ loaded? ? target.include?(record) : scoped.exists?(record)
+ end
+ else
+ false
+ end
+ end
+
+ def cached_scope(method, args)
+ @scopes_cache[method][args] ||= scoped.readonly(nil).send(method, *args)
+ end
+
+ def load_target
+ if find_target?
+ targets = []
+
+ begin
+ targets = find_target
+ rescue ActiveRecord::RecordNotFound
+ reset
+ end
+
+ @target = merge_target_lists(targets, target)
+ end
+
+ loaded!
+ target
+ end
+
+ def add_to_target(record)
+ transaction do
+ callback(:before_add, record)
+ yield(record) if block_given?
+
+ if options[:uniq] && index = @target.index(record)
+ @target[index] = record
+ else
+ @target << record
+ end
+
+ callback(:after_add, record)
+ set_inverse_instance(record)
+ end
+
+ record
+ end
+
+ private
+
+ def custom_counter_sql
+ if options[:counter_sql]
+ interpolate(options[:counter_sql])
+ else
+ # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
+ interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
+ end
+ end
+
+ def custom_finder_sql
+ interpolate(options[:finder_sql])
+ end
+
+ def find_target
+ records =
+ if options[:finder_sql]
+ reflection.klass.find_by_sql(custom_finder_sql)
+ else
+ find(:all)
+ end
+
+ records = options[:uniq] ? uniq(records) : records
+ records.each { |record| set_inverse_instance(record) }
+ records
+ end
+
+ def merge_target_lists(loaded, existing)
+ return loaded if existing.empty?
+ return existing if loaded.empty?
+
+ loaded.map do |f|
+ i = existing.index(f)
+ if i
+ existing.delete_at(i).tap do |t|
+ keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
+ # FIXME: this call to attributes causes many NoMethodErrors
+ attributes = f.attributes
+ (attributes.keys - keys).each do |k|
+ t.send("#{k}=", attributes[k])
+ end
+ end
+ else
+ f
+ end
+ end + existing
+ end
+
+ def build_or_create(attributes, method)
+ records = Array.wrap(attributes).map do |attrs|
+ record = build_record(attrs)
+
+ add_to_target(record) do
+ yield(record) if block_given?
+ insert_record(record) if method == :create
+ end
+ end
+
+ attributes.is_a?(Array) ? records : records.first
+ end
+
+ # Do the relevant stuff to insert the given record into the association collection.
+ def insert_record(record, validate = true)
+ raise NotImplementedError
+ end
+
+ def build_record(attributes)
+ reflection.build_association(scoped.scope_for_create.merge(attributes))
+ end
+
+ def delete_or_destroy(records, method)
+ records = records.flatten
+ records.each { |record| raise_on_type_mismatch(record) }
+ existing_records = records.reject { |r| r.new_record? }
+
+ transaction do
+ records.each { |record| callback(:before_remove, record) }
+
+ delete_records(existing_records, method) if existing_records.any?
+ records.each { |record| target.delete(record) }
+
+ records.each { |record| callback(:after_remove, record) }
+ end
+ end
+
+ # Delete the given records from the association, using one of the methods :destroy,
+ # :delete_all or :nullify (or nil, in which case a default is used).
+ def delete_records(records, method)
+ raise NotImplementedError
+ end
+
+ def callback(method, record)
+ callbacks_for(method).each do |callback|
+ case callback
+ when Symbol
+ owner.send(callback, record)
+ when Proc
+ callback.call(owner, record)
+ else
+ callback.send(method, owner, record)
+ end
+ end
+ end
+
+ def callbacks_for(callback_name)
+ full_callback_name = "#{callback_name}_for_#{reflection.name}"
+ owner.class.send(full_callback_name.to_sym) || []
+ end
+
+ # Should we deal with assoc.first or assoc.last by issuing an independent query to
+ # the database, or by getting the target, and then taking the first/last item from that?
+ #
+ # If the args is just a non-empty options hash, go to the database.
+ #
+ # Otherwise, go to the database only if none of the following are true:
+ # * target already loaded
+ # * owner is new record
+ # * custom :finder_sql exists
+ # * target contains new or changed record(s)
+ # * the first arg is an integer (which indicates the number of records to be returned)
+ def fetch_first_or_last_using_find?(args)
+ if args.first.is_a?(Hash)
+ true
+ else
+ !(loaded? ||
+ owner.new_record? ||
+ options[:finder_sql] ||
+ target.any? { |record| record.new_record? || record.changed? } ||
+ args.first.kind_of?(Integer))
+ end
+ end
+
+ def include_in_memory?(record)
+ if reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
+ owner.send(reflection.through_reflection.name).any? { |source|
+ target = source.send(reflection.source_reflection.name)
+ target.respond_to?(:include?) ? target.include?(record) : target == record
+ } || target.include?(record)
+ else
+ target.include?(record)
+ end
+ end
+
+ # If using a custom finder_sql, #find scans the entire collection.
+ def find_by_scan(*args)
+ expects_array = args.first.kind_of?(Array)
+ ids = args.flatten.compact.uniq.map { |arg| arg.to_i }
+
+ if ids.size == 1
+ id = ids.first
+ record = load_target.detect { |r| id == r.id }
+ expects_array ? [ record ] : record
+ else
+ load_target.select { |r| ids.include?(r.id) }
+ end
+ end
+
+ # Fetches the first/last using SQL if possible, otherwise from the target array.
+ def first_or_last(type, *args)
+ args.shift if args.first.is_a?(Hash) && args.first.empty?
+
+ collection = fetch_first_or_last_using_find?(args) ? scoped : load_target
+ collection.send(type, *args)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
new file mode 100644
index 0000000000..cf77d770c9
--- /dev/null
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -0,0 +1,127 @@
+module ActiveRecord
+ module Associations
+ # Association proxies in Active Record are middlemen between the object that
+ # holds the association, known as the <tt>@owner</tt>, and the actual associated
+ # object, known as the <tt>@target</tt>. The kind of association any proxy is
+ # about is available in <tt>@reflection</tt>. That's an instance of the class
+ # ActiveRecord::Reflection::AssociationReflection.
+ #
+ # For example, given
+ #
+ # class Blog < ActiveRecord::Base
+ # has_many :posts
+ # end
+ #
+ # blog = Blog.find(:first)
+ #
+ # the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
+ # <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
+ # the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
+ #
+ # This class has most of the basic instance methods removed, and delegates
+ # unknown methods to <tt>@target</tt> via <tt>method_missing</tt>. As a
+ # corner case, it even removes the +class+ method and that's why you get
+ #
+ # blog.posts.class # => Array
+ #
+ # though the object behind <tt>blog.posts</tt> is not an Array, but an
+ # ActiveRecord::Associations::HasManyAssociation.
+ #
+ # The <tt>@target</tt> object is not \loaded until needed. For example,
+ #
+ # blog.posts.count
+ #
+ # is computed directly through SQL and does not trigger by itself the
+ # instantiation of the actual post records.
+ class CollectionProxy # :nodoc:
+ alias :proxy_extend :extend
+
+ instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil\?|send|object_id|to_a)$|^__|^respond_to|proxy_/ }
+
+ delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from,
+ :lock, :readonly, :having, :to => :scoped
+
+ delegate :target, :load_target, :loaded?, :scoped,
+ :to => :@association
+
+ delegate :select, :find, :first, :last,
+ :build, :create, :create!,
+ :concat, :delete_all, :destroy_all, :delete, :destroy, :uniq,
+ :sum, :count, :size, :length, :empty?,
+ :any?, :many?, :include?,
+ :to => :@association
+
+ def initialize(association)
+ @association = association
+ Array.wrap(association.options[:extend]).each { |ext| proxy_extend(ext) }
+ end
+
+ def respond_to?(*args)
+ super ||
+ (load_target && target.respond_to?(*args)) ||
+ @association.klass.respond_to?(*args)
+ end
+
+ def method_missing(method, *args, &block)
+ match = DynamicFinderMatch.match(method)
+ if match && match.creator?
+ attributes = match.attribute_names
+ return send(:"find_by_#{attributes.join('_and_')}", *args) || create(Hash[attributes.zip(args)])
+ end
+
+ if target.respond_to?(method) || (!@association.klass.respond_to?(method) && Class.respond_to?(method))
+ if load_target
+ if target.respond_to?(method)
+ target.send(method, *args, &block)
+ else
+ begin
+ super
+ rescue NoMethodError => e
+ raise e, e.message.sub(/ for #<.*$/, " via proxy for #{target}")
+ end
+ end
+ end
+
+ elsif @association.klass.scopes[method]
+ @association.cached_scope(method, args)
+ else
+ scoped.readonly(nil).send(method, *args, &block)
+ end
+ end
+
+ # Forwards <tt>===</tt> explicitly to the \target because the instance method
+ # removal above doesn't catch it. Loads the \target if needed.
+ def ===(other)
+ other === load_target
+ end
+
+ def to_ary
+ load_target.dup
+ end
+ alias_method :to_a, :to_ary
+
+ def <<(*records)
+ @association.concat(records) && self
+ end
+ alias_method :push, :<<
+
+ def clear
+ delete_all
+ self
+ end
+
+ def reload
+ @association.reload
+ self
+ end
+
+ def new(*args, &block)
+ if @association.is_a?(HasManyThroughAssociation)
+ @association.build(*args, &block)
+ else
+ method_missing(:new, *args, &block)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
index bec123e7a2..217213808b 100644
--- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
@@ -1,136 +1,51 @@
module ActiveRecord
# = Active Record Has And Belongs To Many Association
module Associations
- class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
- def create(attributes = {})
- create_record(attributes) { |record| insert_record(record) }
- end
+ class HasAndBelongsToManyAssociation < CollectionAssociation #:nodoc:
+ attr_reader :join_table
- def create!(attributes = {})
- create_record(attributes) { |record| insert_record(record, true) }
+ def initialize(owner, reflection)
+ @join_table = Arel::Table.new(reflection.options[:join_table])
+ super
end
- def columns
- @reflection.columns(@reflection.options[:join_table], "#{@reflection.options[:join_table]} Columns")
- end
+ def insert_record(record, validate = true)
+ return if record.new_record? && !record.save(:validate => validate)
- def reset_column_information
- @reflection.reset_column_information
- 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.connection.insert stmt.to_sql
+ end
- def has_primary_key?
- @has_primary_key ||= @owner.connection.supports_primary_key? && @owner.connection.primary_key(@reflection.options[:join_table])
+ record
end
- protected
- def construct_find_options!(options)
- options[:joins] = @join_sql
- options[:readonly] = finding_with_ambiguous_select?(options[:select] || @reflection.options[:select])
- options[:select] ||= (@reflection.options[:select] || '*')
- end
+ private
def count_records
load_target.size
end
- def insert_record(record, force = true, validate = true)
- if record.new_record?
- if force
- record.save!
- else
- return false unless record.save(:validate => validate)
- end
- end
-
- if @reflection.options[:insert_sql]
- @owner.connection.insert(interpolate_sql(@reflection.options[:insert_sql], record))
+ def delete_records(records, method)
+ if sql = options[:delete_sql]
+ records.each { |record| owner.connection.delete(interpolate(sql, record)) }
else
- relation = Arel::Table.new(@reflection.options[:join_table])
- timestamps = record_timestamp_columns(record)
- timezone = record.send(:current_time_from_proper_timezone) if timestamps.any?
-
- attributes = columns.inject({}) do |attrs, column|
- name = column.name
- case name.to_s
- when @reflection.primary_key_name.to_s
- attrs[relation[name]] = @owner.id
- when @reflection.association_foreign_key.to_s
- attrs[relation[name]] = record.id
- when *timestamps
- attrs[relation[name]] = timezone
- else
- if record.has_attribute?(name)
- value = @owner.send(:quote_value, record[name], column)
- attrs[relation[name]] = value unless value.nil?
- end
- end
- attrs
- end
-
- relation.insert(attributes)
- end
-
- return true
- end
-
- def delete_records(records)
- if sql = @reflection.options[:delete_sql]
- records.each { |record| @owner.connection.delete(interpolate_sql(sql, record)) }
- else
- relation = Arel::Table.new(@reflection.options[:join_table])
- relation.where(relation[@reflection.primary_key_name].eq(@owner.id).
- and(Arel::Predicates::In.new(relation[@reflection.association_foreign_key], records.map(&:id)))
- ).delete
+ relation = join_table
+ stmt = relation.where(relation[reflection.foreign_key].eq(owner.id).
+ and(relation[reflection.association_foreign_key].in(records.map { |x| x.id }.compact))
+ ).compile_delete
+ owner.connection.delete stmt.to_sql
end
end
- def construct_sql
- if @reflection.options[:finder_sql]
- @finder_sql = interpolate_sql(@reflection.options[:finder_sql])
- else
- @finder_sql = "#{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.primary_key_name} = #{owner_quoted_id} "
- @finder_sql << " AND (#{conditions})" if conditions
- end
-
- @join_sql = "INNER JOIN #{@owner.connection.quote_table_name @reflection.options[:join_table]} ON #{@reflection.quoted_table_name}.#{@reflection.klass.primary_key} = #{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.association_foreign_key}"
-
- construct_counter_sql
- end
-
- def construct_scope
- { :find => { :conditions => @finder_sql,
- :joins => @join_sql,
- :readonly => false,
- :order => @reflection.options[:order],
- :include => @reflection.options[:include],
- :limit => @reflection.options[:limit] } }
- end
-
- # Join tables with additional columns on top of the two foreign keys must be considered
- # ambiguous unless a select clause has been explicitly defined. Otherwise you can get
- # broken records back, if, for example, the join column also has an id column. This will
- # then overwrite the id column of the records coming back.
- def finding_with_ambiguous_select?(select_clause)
- !select_clause && columns.size != 2
- end
-
- private
- def create_record(attributes, &block)
- # Can't use Base.create because the foreign key may be a protected attribute.
- ensure_owner_is_not_new
- if attributes.is_a?(Array)
- attributes.collect { |attr| create(attr) }
- else
- build_record(attributes, &block)
- end
- end
-
- def record_timestamp_columns(record)
- if record.record_timestamps
- record.send(:all_timestamp_attributes).map(&:to_s)
- else
- []
- end
+ def invertible_for?(record)
+ false
end
end
end
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index c33bc6aa47..78c5c4b870 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -5,19 +5,14 @@ module ActiveRecord
#
# If the association has a <tt>:through</tt> option further specialization
# is provided by its child HasManyThroughAssociation.
- class HasManyAssociation < AssociationCollection #:nodoc:
- def initialize(owner, reflection)
- @finder_sql = nil
- super
+ class HasManyAssociation < CollectionAssociation #:nodoc:
+
+ def insert_record(record, validate = true)
+ set_owner_attributes(record)
+ record.save(:validate => validate)
end
- protected
- def owner_quoted_id
- if @reflection.options[:primary_key]
- quote_value(@owner.send(@reflection.options[:primary_key]))
- else
- @owner.quoted_id
- end
- end
+
+ private
# Returns the number of records in this collection.
#
@@ -34,94 +29,70 @@ module ActiveRecord
# the loaded flag is set to true as well.
def count_records
count = if has_cached_counter?
- @owner.send(:read_attribute, cached_counter_attribute_name)
- elsif @reflection.options[:counter_sql]
- @reflection.klass.count_by_sql(@counter_sql)
+ owner.send(:read_attribute, cached_counter_attribute_name)
+ elsif options[:counter_sql] || options[:finder_sql]
+ reflection.klass.count_by_sql(custom_counter_sql)
else
- @reflection.klass.count(:conditions => @counter_sql, :include => @reflection.options[:include])
+ scoped.count
end
# If there's nothing in the database and @target has no new records
# we are certain the current target is an empty array. This is a
# documented side-effect of the method that may avoid an extra SELECT.
- @target ||= [] and loaded if count == 0
-
- if @reflection.options[:limit]
- count = [ @reflection.options[:limit], count ].min
- end
-
- return count
- end
+ @target ||= [] and loaded! if count == 0
- def has_cached_counter?
- @owner.attribute_present?(cached_counter_attribute_name)
+ [options[:limit], count].compact.min
end
- def cached_counter_attribute_name
- "#{@reflection.name}_count"
+ def has_cached_counter?(reflection = reflection)
+ owner.attribute_present?(cached_counter_attribute_name(reflection))
end
- def insert_record(record, force = false, validate = true)
- set_belongs_to_association_for(record)
- force ? record.save! : record.save(:validate => validate)
+ def cached_counter_attribute_name(reflection = reflection)
+ "#{reflection.name}_count"
end
- # Deletes the records according to the <tt>:dependent</tt> option.
- def delete_records(records)
- case @reflection.options[:dependent]
- when :destroy
- records.each { |r| r.destroy }
- when :delete_all
- @reflection.klass.delete(records.map { |record| record.id })
- else
- relation = Arel::Table.new(@reflection.table_name)
- relation.where(relation[@reflection.primary_key_name].eq(@owner.id).
- and(Arel::Predicates::In.new(relation[@reflection.klass.primary_key], records.map(&:id)))
- ).update(relation[@reflection.primary_key_name] => nil)
-
- @owner.class.update_counters(@owner.id, cached_counter_attribute_name => -records.size) if has_cached_counter?
+ def update_counter(difference, reflection = reflection)
+ if has_cached_counter?(reflection)
+ counter = cached_counter_attribute_name(reflection)
+ owner.class.update_counters(owner.id, counter => difference)
+ owner[counter] += difference
+ owner.changed_attributes.delete(counter) # eww
end
end
- def target_obsolete?
- false
+ # This shit is nasty. We need to avoid the following situation:
+ #
+ # * An associated record is deleted via record.destroy
+ # * Hence the callbacks run, and they find a belongs_to on the record with a
+ # :counter_cache options which points back at our owner. So they update the
+ # counter cache.
+ # * In which case, we must make sure to *not* update the counter cache, or else
+ # it will be decremented twice.
+ #
+ # Hence this method.
+ def inverse_updates_counter_cache?(reflection = reflection)
+ counter_name = cached_counter_attribute_name(reflection)
+ reflection.klass.reflect_on_all_associations(:belongs_to).any? { |inverse_reflection|
+ inverse_reflection.counter_cache_column == counter_name
+ }
end
- def construct_sql
- case
- when @reflection.options[:finder_sql]
- @finder_sql = interpolate_sql(@reflection.options[:finder_sql])
-
- when @reflection.options[:as]
- @finder_sql =
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_id = #{owner_quoted_id} AND " +
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_type = #{@owner.class.quote_value(@owner.class.base_class.name.to_s)}"
- @finder_sql << " AND (#{conditions})" if conditions
+ # 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
+ keys = records.map { |r| r[reflection.association_primary_key] }
+ scope = scoped.where(reflection.association_primary_key => keys)
+ if method == :delete_all
+ update_counter(-scope.delete_all)
else
- @finder_sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{owner_quoted_id}"
- @finder_sql << " AND (#{conditions})" if conditions
+ update_counter(-scope.update_all(reflection.foreign_key => nil))
+ end
end
-
- construct_counter_sql
- end
-
- def construct_scope
- create_scoping = {}
- set_belongs_to_association_for(create_scoping)
- {
- :find => { :conditions => @finder_sql,
- :readonly => false,
- :order => @reflection.options[:order],
- :limit => @reflection.options[:limit],
- :include => @reflection.options[:include]},
- :create => create_scoping
- }
- end
-
- def we_can_set_the_inverse_on_this?(record)
- inverse = @reflection.inverse_of
- return !inverse.nil?
end
end
end
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index 608b1c741a..9d2b29685b 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -1,114 +1,144 @@
-require "active_record/associations/through_association_scope"
require 'active_support/core_ext/object/blank'
module ActiveRecord
# = Active Record Has Many Through Association
module Associations
class HasManyThroughAssociation < HasManyAssociation #:nodoc:
- include ThroughAssociationScope
+ include ThroughAssociation
alias_method :new, :build
- def create!(attrs = nil)
- create_record(attrs, true)
- end
-
- def create(attrs = nil)
- create_record(attrs, false)
+ # 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 destroy(*records)
- transaction do
- delete_records(flatten_deeper(records))
- super
+ 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
- # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been
- # loaded and calling collection.size if it has. If it's more likely than not that the collection does
- # have a size larger than zero, and you need to fetch that collection afterwards, it'll take one fewer
- # SELECT query if you use #length.
- def size
- return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
- return @target.size if loaded?
- return count
+ def insert_record(record, validate = true)
+ ensure_not_nested
+ return if record.new_record? && !record.save(:validate => validate)
+
+ through_record(record).save!
+ update_counter(1)
+ record
end
- protected
- def create_record(attrs, force = true)
- ensure_owner_is_not_new
+ private
- transaction do
- object = @reflection.klass.new(attrs)
- add_record_to_target_with_callbacks(object) {|r| insert_record(object, force) }
- object
+ def through_record(record)
+ through_association = owner.association(through_reflection.name)
+ attributes = construct_join_attributes(record)
+
+ through_record = Array.wrap(through_association.target).find { |candidate|
+ candidate.attributes.slice(*attributes.keys) == attributes
+ }
+
+ unless through_record
+ through_record = through_association.build(attributes)
+ through_record.send("#{source_reflection.name}=", record)
+ end
+
+ through_record
+ end
+
+ def build_record(attributes)
+ ensure_not_nested
+
+ record = super(attributes)
+
+ inverse = source_reflection.inverse_of
+ if inverse
+ if inverse.macro == :has_many
+ record.send(inverse.name) << through_record(record)
+ elsif inverse.macro == :has_one
+ record.send("#{inverse.name}=", through_record(record))
+ end
end
+
+ record
end
def target_reflection_has_associated_record?
- if @reflection.through_reflection.macro == :belongs_to && @owner[@reflection.through_reflection.primary_key_name].blank?
+ if through_reflection.macro == :belongs_to && owner[through_reflection.foreign_key].blank?
false
else
true
end
end
- def construct_find_options!(options)
- options[:joins] = construct_joins(options[:joins])
- options[:include] = @reflection.source_reflection.options[:include] if options[:include].nil? && @reflection.source_reflection.options[:include]
+ def update_through_counter?(method)
+ case method
+ when :destroy
+ !inverse_updates_counter_cache?(through_reflection)
+ when :nullify
+ false
+ else
+ true
+ end
end
- def insert_record(record, force = true, validate = true)
- if record.new_record?
- if force
- record.save!
- else
- return false unless record.save(:validate => validate)
- end
- end
+ def delete_records(records, method)
+ ensure_not_nested
- through_association = @owner.send(@reflection.through_reflection.name)
- through_record = through_association.create!(construct_join_attributes(record))
- through_association.proxy_target << through_record
- end
+ through = owner.association(through_reflection.name)
+ scope = through.scoped.where(construct_join_attributes(*records))
- # TODO - add dependent option support
- def delete_records(records)
- klass = @reflection.through_reflection.klass
- records.each do |associate|
- klass.delete_all(construct_join_attributes(associate))
+ 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
- end
- def find_target
- return [] unless target_reflection_has_associated_record?
- with_scope(construct_scope) { @reflection.klass.find(:all) }
- end
-
- def construct_sql
- case
- when @reflection.options[:finder_sql]
- @finder_sql = interpolate_sql(@reflection.options[:finder_sql])
+ delete_through_records(through, records)
- @finder_sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{owner_quoted_id}"
- @finder_sql << " AND (#{conditions})" if conditions
- else
- @finder_sql = construct_conditions
+ if through_reflection.macro == :has_many && update_through_counter?(method)
+ update_counter(-count, through_reflection)
end
- construct_counter_sql
+ update_counter(-count)
end
- def has_cached_counter?
- @owner.attribute_present?(cached_counter_attribute_name)
+ def delete_through_records(through, records)
+ if through_reflection.macro == :has_many
+ records.each do |record|
+ through.target.delete(through_record(record))
+ end
+ else
+ records.each do |record|
+ through.target = nil if through.target == through_record(record)
+ end
+ end
end
- def cached_counter_attribute_name
- "#{@reflection.name}_count"
+ def find_target
+ return [] unless target_reflection_has_associated_record?
+ scoped.all
end
# NOTE - not sure that we can actually cope with inverses here
- def we_can_set_the_inverse_on_this?(record)
+ def invertible_for?(record)
false
end
end
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index 68b8b792ad..1d2e8667e4 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -1,142 +1,70 @@
module ActiveRecord
# = Active Record Belongs To Has One Association
module Associations
- class HasOneAssociation < AssociationProxy #:nodoc:
- def initialize(owner, reflection)
- super
- construct_sql
- end
+ class HasOneAssociation < SingularAssociation #:nodoc:
+ def replace(record, save = true)
+ raise_on_type_mismatch(record) if record
+ load_target
- def create(attrs = {}, replace_existing = true)
- new_record(replace_existing) do |reflection|
- attrs = merge_with_conditions(attrs)
- reflection.create_association(attrs)
- end
- end
+ reflection.klass.transaction do
+ if target && target != record
+ remove_target!(options[:dependent])
+ end
- def create!(attrs = {}, replace_existing = true)
- new_record(replace_existing) do |reflection|
- attrs = merge_with_conditions(attrs)
- reflection.create_association!(attrs)
- end
- end
+ if record
+ set_inverse_instance(record)
+ set_owner_attributes(record)
- def build(attrs = {}, replace_existing = true)
- new_record(replace_existing) do |reflection|
- attrs = merge_with_conditions(attrs)
- reflection.build_association(attrs)
+ if owner.persisted? && save && !record.save
+ nullify_owner_attributes(record)
+ set_owner_attributes(target)
+ raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
+ end
+ end
end
- end
- def replace(obj, dont_save = false)
- load_target
+ self.target = record
+ end
- unless @target.nil? || @target == obj
- if dependent? && !dont_save
- case @reflection.options[:dependent]
+ def delete(method = options[:dependent])
+ if load_target
+ case method
when :delete
- @target.delete unless @target.new_record?
- @owner.clear_association_cache
+ target.delete
when :destroy
- @target.destroy unless @target.new_record?
- @owner.clear_association_cache
+ target.destroy
when :nullify
- @target[@reflection.primary_key_name] = nil
- @target.save unless @owner.new_record? || @target.new_record?
- end
- else
- @target[@reflection.primary_key_name] = nil
- @target.save unless @owner.new_record? || @target.new_record?
+ target.update_attribute(reflection.foreign_key, nil)
end
end
-
- if obj.nil?
- @target = nil
- else
- raise_on_type_mismatch(obj)
- set_belongs_to_association_for(obj)
- @target = (AssociationProxy === obj ? obj.target : obj)
- end
-
- set_inverse_instance(obj, @owner)
- @loaded = true
-
- unless @owner.new_record? or obj.nil? or dont_save
- return (obj.save ? self : false)
- else
- return (obj.nil? ? nil : self)
- end
end
- protected
- def owner_quoted_id
- if @reflection.options[:primary_key]
- @owner.class.quote_value(@owner.send(@reflection.options[:primary_key]))
- else
- @owner.quoted_id
- end
- end
-
private
- def find_target
- the_target = @reflection.klass.find(:first,
- :conditions => @finder_sql,
- :select => @reflection.options[:select],
- :order => @reflection.options[:order],
- :include => @reflection.options[:include],
- :readonly => @reflection.options[:readonly]
- )
- set_inverse_instance(the_target, @owner)
- the_target
- end
- def construct_sql
- case
- when @reflection.options[:as]
- @finder_sql =
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_id = #{owner_quoted_id} AND " +
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_type = #{@owner.class.quote_value(@owner.class.base_class.name.to_s)}"
- else
- @finder_sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{owner_quoted_id}"
- end
- @finder_sql << " AND (#{conditions})" if conditions
+ # 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 construct_scope
- create_scoping = {}
- set_belongs_to_association_for(create_scoping)
- { :create => create_scoping }
- end
-
- def new_record(replace_existing)
- # Make sure we load the target first, if we plan on replacing the existing
- # instance. Otherwise, if the target has not previously been loaded
- # elsewhere, the instance we create will get orphaned.
- load_target if replace_existing
- record = @reflection.klass.send(:with_scope, :create => construct_scope[:create]) do
- yield @reflection
- end
-
- if replace_existing
- replace(record, true)
+ def remove_target!(method)
+ if [:delete, :destroy].include?(method)
+ target.send(method)
else
- record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
- self.target = record
- set_inverse_instance(record, @owner)
- end
+ nullify_owner_attributes(target)
- record
- end
-
- def we_can_set_the_inverse_on_this?(record)
- inverse = @reflection.inverse_of
- return !inverse.nil?
+ if target.persisted? && owner.persisted? && !target.save
+ set_owner_attributes(target)
+ raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " +
+ "The record failed to save when after its foreign key was set to nil."
+ end
+ end
end
- def merge_with_conditions(attrs={})
- attrs ||= {}
- attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
- attrs
+ def nullify_owner_attributes(record)
+ record[reflection.foreign_key] = nil
end
end
end
diff --git a/activerecord/lib/active_record/associations/has_one_through_association.rb b/activerecord/lib/active_record/associations/has_one_through_association.rb
index fba0a2bfcc..fdf8ae1453 100644
--- a/activerecord/lib/active_record/associations/has_one_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_through_association.rb
@@ -1,40 +1,36 @@
-require "active_record/associations/through_association_scope"
-
module ActiveRecord
# = Active Record Has One Through Association
module Associations
- class HasOneThroughAssociation < HasOneAssociation
- include ThroughAssociationScope
+ class HasOneThroughAssociation < HasOneAssociation #:nodoc:
+ include ThroughAssociation
- def replace(new_value)
- create_through_record(new_value)
- @target = new_value
+ def replace(record)
+ create_through_record(record)
+ self.target = record
end
private
- def create_through_record(new_value) #nodoc:
- klass = @reflection.through_reflection.klass
+ def create_through_record(record)
+ ensure_not_nested
+
+ through_proxy = owner.association(through_reflection.name)
+ through_record = through_proxy.send(:load_target)
- current_object = @owner.send(@reflection.through_reflection.name)
+ if through_record && !record
+ through_record.destroy
+ elsif record
+ attributes = construct_join_attributes(record)
- if current_object
- new_value ? current_object.update_attributes(construct_join_attributes(new_value)) : current_object.destroy
- elsif new_value
- if @owner.new_record?
- self.target = new_value
- through_association = @owner.send(:association_instance_get, @reflection.through_reflection.name)
- through_association.build(construct_join_attributes(new_value))
- else
- @owner.send(@reflection.through_reflection.name, klass.create(construct_join_attributes(new_value)))
+ if through_record
+ through_record.update_attributes(attributes)
+ elsif owner.new_record?
+ through_proxy.build(attributes)
+ else
+ through_proxy.create(attributes)
+ end
end
end
- end
-
- private
- def find_target
- with_scope(construct_scope) { @reflection.klass.find(:first) }
- end
end
end
end
diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb
new file mode 100644
index 0000000000..504f25271c
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency.rb
@@ -0,0 +1,215 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ autoload :JoinPart, 'active_record/associations/join_dependency/join_part'
+ autoload :JoinBase, 'active_record/associations/join_dependency/join_base'
+ autoload :JoinAssociation, 'active_record/associations/join_dependency/join_association'
+
+ attr_reader :join_parts, :reflections, :alias_tracker, :active_record
+
+ def initialize(base, associations, joins)
+ @active_record = base
+ @table_joins = joins
+ @join_parts = [JoinBase.new(base)]
+ @associations = {}
+ @reflections = []
+ @alias_tracker = AliasTracker.new(joins)
+ @alias_tracker.aliased_name_for(base.table_name) # Updates the count for base.table_name to 1
+ build(associations)
+ end
+
+ def graft(*associations)
+ associations.each do |association|
+ join_associations.detect {|a| association == a} ||
+ build(association.reflection.name, association.find_parent_in(self) || join_base, association.join_type)
+ end
+ self
+ end
+
+ def join_associations
+ join_parts.last(join_parts.length - 1)
+ end
+
+ def join_base
+ join_parts.first
+ end
+
+ def columns
+ join_parts.collect { |join_part|
+ table = join_part.aliased_table
+ join_part.column_names_with_alias.collect{ |column_name, aliased_name|
+ table[column_name].as Arel.sql(aliased_name)
+ }
+ }.flatten
+ end
+
+ def instantiate(rows)
+ primary_key = join_base.aliased_primary_key
+ parents = {}
+
+ records = rows.map { |model|
+ primary_id = model[primary_key]
+ parent = parents[primary_id] ||= join_base.instantiate(model)
+ construct(parent, @associations, join_associations, model)
+ parent
+ }.uniq
+
+ remove_duplicate_results!(active_record, records, @associations)
+ records
+ end
+
+ def remove_duplicate_results!(base, records, associations)
+ case associations
+ when Symbol, String
+ reflection = base.reflections[associations]
+ remove_uniq_by_reflection(reflection, records)
+ when Array
+ associations.each do |association|
+ remove_duplicate_results!(base, records, association)
+ end
+ when Hash
+ associations.keys.each do |name|
+ reflection = base.reflections[name]
+ remove_uniq_by_reflection(reflection, records)
+
+ parent_records = []
+ records.each do |record|
+ if descendant = record.send(reflection.name)
+ if reflection.collection?
+ parent_records.concat descendant.target.uniq
+ else
+ parent_records << descendant
+ end
+ end
+ end
+
+ remove_duplicate_results!(reflection.klass, parent_records, associations[name]) unless parent_records.empty?
+ end
+ end
+ end
+
+ protected
+
+ def cache_joined_association(association)
+ associations = []
+ parent = association.parent
+ while parent != join_base
+ associations.unshift(parent.reflection.name)
+ parent = parent.parent
+ end
+ ref = @associations
+ associations.each do |key|
+ ref = ref[key]
+ end
+ ref[association.reflection.name] ||= {}
+ end
+
+ def build(associations, parent = nil, join_type = Arel::InnerJoin)
+ parent ||= join_parts.last
+ case associations
+ when Symbol, String
+ reflection = parent.reflections[associations.to_s.intern] or
+ raise ConfigurationError, "Association named '#{ associations }' was not found; perhaps you misspelled it?"
+ unless join_association = find_join_association(reflection, parent)
+ @reflections << reflection
+ join_association = build_join_association(reflection, parent)
+ join_association.join_type = join_type
+ @join_parts << join_association
+ cache_joined_association(join_association)
+ end
+ join_association
+ when Array
+ associations.each do |association|
+ build(association, parent, join_type)
+ end
+ when Hash
+ associations.keys.sort_by { |a| a.to_s }.each do |name|
+ join_association = build(name, parent, join_type)
+ build(associations[name], join_association, join_type)
+ end
+ else
+ raise ConfigurationError, associations.inspect
+ end
+ end
+
+ def find_join_association(name_or_reflection, parent)
+ if String === name_or_reflection
+ name_or_reflection = name_or_reflection.to_sym
+ end
+
+ join_associations.detect { |j|
+ j.reflection == name_or_reflection && j.parent == parent
+ }
+ end
+
+ def remove_uniq_by_reflection(reflection, records)
+ if reflection && reflection.collection?
+ records.each { |record| record.send(reflection.name).target.uniq! }
+ end
+ end
+
+ def build_join_association(reflection, parent)
+ JoinAssociation.new(reflection, self, parent)
+ end
+
+ def construct(parent, associations, join_parts, row)
+ case associations
+ when Symbol, String
+ name = associations.to_s
+
+ join_part = join_parts.detect { |j|
+ j.reflection.name.to_s == name &&
+ j.parent_table_name == parent.class.table_name }
+
+ raise(ConfigurationError, "No such association") unless join_part
+
+ join_parts.delete(join_part)
+ construct_association(parent, join_part, row)
+ when Array
+ associations.each do |association|
+ construct(parent, association, join_parts, row)
+ end
+ when Hash
+ associations.sort_by { |k,_| k.to_s }.each do |association_name, assoc|
+ association = construct(parent, association_name, join_parts, row)
+ construct(association, assoc, join_parts, row) if association
+ end
+ else
+ raise ConfigurationError, associations.inspect
+ end
+ end
+
+ def construct_association(record, join_part, row)
+ return if record.id.to_s != join_part.parent.record_id(row).to_s
+
+ macro = join_part.reflection.macro
+ if macro == :has_one
+ return if record.association_cache.key?(join_part.reflection.name)
+ association = join_part.instantiate(row) unless row[join_part.aliased_primary_key].nil?
+ set_target_and_inverse(join_part, association, record)
+ else
+ return if row[join_part.aliased_primary_key].nil?
+ association = join_part.instantiate(row)
+ case macro
+ when :has_many, :has_and_belongs_to_many
+ other = record.association(join_part.reflection.name)
+ other.loaded!
+ other.target.push(association)
+ other.set_inverse_instance(association)
+ when :belongs_to
+ set_target_and_inverse(join_part, association, record)
+ else
+ raise ConfigurationError, "unknown macro: #{join_part.reflection.macro}"
+ end
+ end
+ association
+ end
+
+ def set_target_and_inverse(join_part, association, record)
+ other = record.association(join_part.reflection.name)
+ other.target = association
+ other.set_inverse_instance(association)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
new file mode 100644
index 0000000000..4121a5b378
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
@@ -0,0 +1,144 @@
+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|
+ parent == join_part
+ end
+ end
+
+ def join_to(relation)
+ tables = @tables.dup
+ foreign_table = parent_table
+
+ # 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...
+ relation.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 = 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
+
+ relation.from(join(table, constraint))
+
+ unless conditions[i].empty?
+ relation.where(sanitize(conditions[i], table))
+ end
+
+ # The current table in this iteration becomes the foreign table in the next
+ foreign_table = table
+ end
+
+ relation
+ 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 conditions
+ @conditions ||= reflection.conditions.reverse
+ end
+
+ private
+
+ def interpolate(conditions)
+ if conditions.respond_to?(:to_proc)
+ instance_eval(&conditions)
+ else
+ conditions
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_base.rb b/activerecord/lib/active_record/associations/join_dependency/join_base.rb
new file mode 100644
index 0000000000..3920e84976
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_base.rb
@@ -0,0 +1,24 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ class JoinBase < JoinPart # :nodoc:
+ def ==(other)
+ other.class == self.class &&
+ other.active_record == active_record
+ end
+
+ def aliased_prefix
+ "t0"
+ end
+
+ def table
+ Arel::Table.new(table_name, arel_engine)
+ end
+
+ def aliased_table_name
+ active_record.table_name
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_part.rb b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
new file mode 100644
index 0000000000..3279e56e7d
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
@@ -0,0 +1,78 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ # A JoinPart represents a part of a JoinDependency. It is an abstract class, inherited
+ # by JoinBase and JoinAssociation. A JoinBase represents the Active Record which
+ # everything else is being joined onto. A JoinAssociation represents an association which
+ # is joining to the base. A JoinAssociation may result in more than one actual join
+ # operations (for example a has_and_belongs_to_many JoinAssociation would result in
+ # two; one for the join table and one for the target table).
+ class JoinPart # :nodoc:
+ # The Active Record class which this join part is associated 'about'; for a JoinBase
+ # this is the actual base model, for a JoinAssociation this is the target model of the
+ # association.
+ attr_reader :active_record
+
+ delegate :table_name, :column_names, :primary_key, :reflections, :arel_engine, :to => :active_record
+
+ def initialize(active_record)
+ @active_record = active_record
+ @cached_record = {}
+ @column_names_with_alias = nil
+ end
+
+ def aliased_table
+ Arel::Nodes::TableAlias.new aliased_table_name, table
+ end
+
+ def ==(other)
+ raise NotImplementedError
+ end
+
+ # An Arel::Table for the active_record
+ def table
+ raise NotImplementedError
+ end
+
+ # The prefix to be used when aliasing columns in the active_record's table
+ def aliased_prefix
+ raise NotImplementedError
+ end
+
+ # The alias for the active_record's table
+ def aliased_table_name
+ raise NotImplementedError
+ end
+
+ # The alias for the primary key of the active_record's table
+ def aliased_primary_key
+ "#{aliased_prefix}_r0"
+ end
+
+ # An array of [column_name, alias] pairs for the table
+ def column_names_with_alias
+ unless @column_names_with_alias
+ @column_names_with_alias = []
+
+ ([primary_key] + (column_names - [primary_key])).each_with_index do |column_name, i|
+ @column_names_with_alias << [column_name, "#{aliased_prefix}_r#{i}"]
+ end
+ end
+ @column_names_with_alias
+ end
+
+ def extract_record(row)
+ Hash[column_names_with_alias.map{|cn, an| [cn, row[an]]}]
+ end
+
+ def record_id(row)
+ row[aliased_primary_key]
+ end
+
+ def instantiate(row)
+ @cached_record[record_id(row)] ||= active_record.send(:instantiate, extract_record(row))
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_helper.rb b/activerecord/lib/active_record/associations/join_helper.rb
new file mode 100644
index 0000000000..eae546e76e
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_helper.rb
@@ -0,0 +1,56 @@
+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).options[: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 = alias_tracker.pluralize(reflection.name)
+ name << "_#{alias_suffix}"
+ name << "_join" if join
+ name
+ end
+
+ def join(table, constraint)
+ table.create_join(table, table.create_on(constraint), join_type)
+ end
+
+ def sanitize(conditions, table)
+ conditions = conditions.map do |condition|
+ condition = active_record.send(:sanitize_sql, interpolate(condition), table.table_alias || table.name)
+ condition = Arel.sql(condition) unless condition.is_a?(Arel::Node)
+ condition
+ end
+
+ conditions.length == 1 ? conditions.first : Arel::Nodes::And.new(conditions)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
new file mode 100644
index 0000000000..fafed94ff2
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -0,0 +1,177 @@
+module ActiveRecord
+ module Associations
+ # Implements the details of eager loading of Active Record associations.
+ #
+ # Note that 'eager loading' and 'preloading' are actually the same thing.
+ # However, there are two different eager loading strategies.
+ #
+ # The first one is by using table joins. This was only strategy available
+ # prior to Rails 2.1. Suppose that you have an Author model with columns
+ # 'name' and 'age', and a Book model with columns 'name' and 'sales'. Using
+ # this strategy, Active Record would try to retrieve all data for an author
+ # and all of its books via a single query:
+ #
+ # SELECT * FROM authors
+ # LEFT OUTER JOIN books ON authors.id = books.id
+ # WHERE authors.name = 'Ken Akamatsu'
+ #
+ # However, this could result in many rows that contain redundant data. After
+ # having received the first row, we already have enough data to instantiate
+ # the Author object. In all subsequent rows, only the data for the joined
+ # 'books' table is useful; the joined 'authors' data is just redundant, and
+ # processing this redundant data takes memory and CPU time. The problem
+ # quickly becomes worse and worse as the level of eager loading increases
+ # (i.e. if Active Record is to eager load the associations' associations as
+ # well).
+ #
+ # The second strategy is to use multiple database queries, one for each
+ # level of association. Since Rails 2.1, this is the default strategy. In
+ # situations where a table join is necessary (e.g. when the +:conditions+
+ # option references an association's column), it will fallback to the table
+ # join strategy.
+ class Preloader #:nodoc:
+ autoload :Association, 'active_record/associations/preloader/association'
+ autoload :SingularAssociation, 'active_record/associations/preloader/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/preloader/collection_association'
+ autoload :ThroughAssociation, 'active_record/associations/preloader/through_association'
+
+ autoload :HasMany, 'active_record/associations/preloader/has_many'
+ autoload :HasManyThrough, 'active_record/associations/preloader/has_many_through'
+ autoload :HasOne, 'active_record/associations/preloader/has_one'
+ autoload :HasOneThrough, 'active_record/associations/preloader/has_one_through'
+ autoload :HasAndBelongsToMany, 'active_record/associations/preloader/has_and_belongs_to_many'
+ autoload :BelongsTo, 'active_record/associations/preloader/belongs_to'
+
+ attr_reader :records, :associations, :options, :model
+
+ # Eager loads the named associations for the given Active Record record(s).
+ #
+ # In this description, 'association name' shall refer to the name passed
+ # to an association creation method. For example, a model that specifies
+ # <tt>belongs_to :author</tt>, <tt>has_many :buyers</tt> has association
+ # names +:author+ and +:buyers+.
+ #
+ # == Parameters
+ # +records+ is an array of ActiveRecord::Base. This array needs not be flat,
+ # i.e. +records+ itself may also contain arrays of records. In any case,
+ # +preload_associations+ will preload the all associations records by
+ # flattening +records+.
+ #
+ # +associations+ specifies one or more associations that you want to
+ # preload. It may be:
+ # - a Symbol or a String which specifies a single association name. For
+ # example, specifying +:books+ allows this method to preload all books
+ # for an Author.
+ # - an Array which specifies multiple association names. This array
+ # is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
+ # allows this method to preload an author's avatar as well as all of his
+ # books.
+ # - a Hash which specifies multiple association names, as well as
+ # association names for the to-be-preloaded association objects. For
+ # example, specifying <tt>{ :author => :avatar }</tt> will preload a
+ # book's author, as well as that author's avatar.
+ #
+ # +:associations+ has the same format as the +:include+ option for
+ # <tt>ActiveRecord::Base.find</tt>. So +associations+ could look like this:
+ #
+ # :books
+ # [ :books, :author ]
+ # { :author => :avatar }
+ # [ :books, { :author => :avatar } ]
+ #
+ # +options+ contains options that will be passed to ActiveRecord::Base#find
+ # (which is called under the hood for preloading records). But it is passed
+ # only one level deep in the +associations+ argument, i.e. it's not passed
+ # to the child associations when +associations+ is a Hash.
+ def initialize(records, associations, options = {})
+ @records = Array.wrap(records).compact.uniq
+ @associations = Array.wrap(associations)
+ @options = options
+ end
+
+ def run
+ unless records.empty?
+ associations.each { |association| preload(association) }
+ end
+ end
+
+ private
+
+ def preload(association)
+ case association
+ when Hash
+ preload_hash(association)
+ when String, Symbol
+ preload_one(association.to_sym)
+ else
+ raise ArgumentError, "#{association.inspect} was not recognised for preload"
+ end
+ end
+
+ def preload_hash(association)
+ association.each do |parent, child|
+ Preloader.new(records, parent, options).run
+ Preloader.new(records.map { |record| record.send(parent) }.flatten, child).run
+ end
+ end
+
+ # Not all records have the same class, so group then preload group on the reflection
+ # itself so that if various subclass share the same association then we do not split
+ # them unnecessarily
+ #
+ # Additionally, polymorphic belongs_to associations can have multiple associated
+ # classes, depending on the polymorphic_type field. So we group by the classes as
+ # well.
+ def preload_one(association)
+ grouped_records(association).each do |reflection, klasses|
+ klasses.each do |klass, records|
+ preloader_for(reflection).new(klass, records, reflection, options).run
+ end
+ end
+ end
+
+ def grouped_records(association)
+ Hash[
+ records_by_reflection(association).map do |reflection, records|
+ [reflection, records.group_by { |record| association_klass(reflection, record) }]
+ end
+ ]
+ end
+
+ def records_by_reflection(association)
+ records.group_by do |record|
+ reflection = record.class.reflections[association]
+
+ unless reflection
+ raise ActiveRecord::ConfigurationError, "Association named '#{association}' was not found; " \
+ "perhaps you misspelled it?"
+ end
+
+ reflection
+ end
+ end
+
+ def association_klass(reflection, record)
+ if reflection.macro == :belongs_to && reflection.options[:polymorphic]
+ klass = record.send(reflection.foreign_type)
+ klass && klass.constantize
+ else
+ reflection.klass
+ end
+ end
+
+ def preloader_for(reflection)
+ case reflection.macro
+ when :has_many
+ reflection.options[:through] ? HasManyThrough : HasMany
+ when :has_one
+ reflection.options[:through] ? HasOneThrough : HasOne
+ when :has_and_belongs_to_many
+ HasAndBelongsToMany
+ when :belongs_to
+ BelongsTo
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
new file mode 100644
index 0000000000..7256dd5288
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -0,0 +1,126 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class Association #:nodoc:
+ attr_reader :owners, :reflection, :preload_options, :model, :klass
+
+ def initialize(klass, owners, reflection, preload_options)
+ @klass = klass
+ @owners = owners
+ @reflection = reflection
+ @preload_options = preload_options || {}
+ @model = owners.first && owners.first.class
+ @scoped = nil
+ @owners_by_key = nil
+ end
+
+ def run
+ unless owners.first.association(reflection.name).loaded?
+ preload
+ end
+ end
+
+ def preload
+ raise NotImplementedError
+ end
+
+ def scoped
+ @scoped ||= build_scope
+ end
+
+ def records_for(ids)
+ scoped.where(association_key.in(ids))
+ end
+
+ def table
+ klass.arel_table
+ end
+
+ # The name of the key on the associated records
+ def association_key_name
+ raise NotImplementedError
+ end
+
+ # This is overridden by HABTM as the condition should be on the foreign_key column in
+ # the join table
+ def association_key
+ table[association_key_name]
+ end
+
+ # The name of the key on the model which declares the association
+ def owner_key_name
+ raise NotImplementedError
+ end
+
+ # We're converting to a string here because postgres will return the aliased association
+ # key in a habtm as a string (for whatever reason)
+ def owners_by_key
+ @owners_by_key ||= owners.group_by do |owner|
+ key = owner[owner_key_name]
+ key && key.to_s
+ end
+ end
+
+ def options
+ reflection.options
+ end
+
+ private
+
+ def associated_records_by_owner
+ owner_keys = owners.map { |owner| owner[owner_key_name] }.compact.uniq
+
+ if klass.nil? || owner_keys.empty?
+ records = []
+ else
+ # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
+ # Make several smaller queries if necessary or make one query if the adapter supports it
+ sliced = owner_keys.each_slice(model.connection.in_clause_length || owner_keys.size)
+ records = sliced.map { |slice| records_for(slice) }.flatten
+ end
+
+ # Each record may have multiple owners, and vice-versa
+ records_by_owner = Hash[owners.map { |owner| [owner, []] }]
+ records.each do |record|
+ owner_key = record[association_key_name].to_s
+
+ owners_by_key[owner_key].each do |owner|
+ records_by_owner[owner] << record
+ end
+ end
+ records_by_owner
+ end
+
+ def build_scope
+ scope = klass.scoped
+
+ scope = scope.where(process_conditions(options[:conditions]))
+ scope = scope.where(process_conditions(preload_options[:conditions]))
+
+ scope = scope.select(preload_options[:select] || options[:select] || table[Arel.star])
+ scope = scope.includes(preload_options[:include] || options[:include])
+
+ if options[:as]
+ scope = scope.where(
+ klass.table_name => {
+ reflection.type => model.base_class.sti_name
+ }
+ )
+ end
+
+ scope
+ end
+
+ def process_conditions(conditions)
+ if conditions.respond_to?(:to_proc)
+ conditions = klass.send(:instance_eval, &conditions)
+ end
+
+ if conditions
+ klass.send(:sanitize_sql, conditions)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/belongs_to.rb b/activerecord/lib/active_record/associations/preloader/belongs_to.rb
new file mode 100644
index 0000000000..5091d4717a
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/belongs_to.rb
@@ -0,0 +1,17 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class BelongsTo < SingularAssociation #:nodoc:
+
+ def association_key_name
+ reflection.options[:primary_key] || klass && klass.primary_key
+ end
+
+ def owner_key_name
+ reflection.foreign_key
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/collection_association.rb b/activerecord/lib/active_record/associations/preloader/collection_association.rb
new file mode 100644
index 0000000000..c248aeaaf6
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/collection_association.rb
@@ -0,0 +1,24 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class CollectionAssociation < Association #:nodoc:
+
+ private
+
+ def build_scope
+ super.order(preload_options[:order] || options[:order])
+ end
+
+ def preload
+ associated_records_by_owner.each do |owner, records|
+ association = owner.association(reflection.name)
+ association.loaded!
+ association.target.concat(records)
+ records.each { |record| association.set_inverse_instance(record) }
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
new file mode 100644
index 0000000000..24be279449
--- /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(options[:join_table]).alias('t0')
+ end
+
+ # Unlike the other associations, we want to get a raw array of rows so that we can
+ # access the aliased column on the join table
+ def records_for(ids)
+ scope = super
+ klass.connection.select_all(scope.arel.to_sql, 'SQL', scope.bind_values)
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ def association_key_name
+ 'ar_association_key_name'
+ end
+
+ def association_key
+ join_table[reflection.foreign_key]
+ end
+
+ private
+
+ # Once we have used the join table column (in super), we manually instantiate the
+ # actual records, ensuring that we don't create more than one instances of the same
+ # record
+ def associated_records_by_owner
+ records = {}
+ super.each do |owner_key, 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 0000000000..3ea91a8c11
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_many.rb
@@ -0,0 +1,17 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasMany < CollectionAssociation #:nodoc:
+
+ def association_key_name
+ reflection.foreign_key
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_many_through.rb b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
new file mode 100644
index 0000000000..c6e9ede356
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
@@ -0,0 +1,15 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasManyThrough < CollectionAssociation #:nodoc:
+ include ThroughAssociation
+
+ def associated_records_by_owner
+ super.each do |owner, records|
+ records.uniq! if options[:uniq]
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_one.rb b/activerecord/lib/active_record/associations/preloader/has_one.rb
new file mode 100644
index 0000000000..848448bb48
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_one.rb
@@ -0,0 +1,23 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasOne < SingularAssociation #:nodoc:
+
+ def association_key_name
+ reflection.foreign_key
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ private
+
+ def build_scope
+ super.order(preload_options[:order] || options[:order])
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_one_through.rb b/activerecord/lib/active_record/associations/preloader/has_one_through.rb
new file mode 100644
index 0000000000..f063f85574
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_one_through.rb
@@ -0,0 +1,9 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasOneThrough < SingularAssociation #:nodoc:
+ include ThroughAssociation
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/singular_association.rb b/activerecord/lib/active_record/associations/preloader/singular_association.rb
new file mode 100644
index 0000000000..44e804d785
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/singular_association.rb
@@ -0,0 +1,21 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class SingularAssociation < Association #:nodoc:
+
+ private
+
+ def preload
+ associated_records_by_owner.each do |owner, associated_records|
+ record = associated_records.first
+
+ association = owner.association(reflection.name)
+ association.target = record
+ association.set_inverse_instance(record)
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb
new file mode 100644
index 0000000000..ad6374d09a
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -0,0 +1,67 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ module ThroughAssociation #:nodoc:
+
+ def through_reflection
+ reflection.through_reflection
+ end
+
+ def source_reflection
+ reflection.source_reflection
+ end
+
+ def associated_records_by_owner
+ through_records = through_records_by_owner
+
+ ActiveRecord::Associations::Preloader.new(
+ through_records.values.flatten,
+ source_reflection.name, options
+ ).run
+
+ through_records.each do |owner, records|
+ records.map! { |r| r.send(source_reflection.name) }.flatten!
+ records.compact!
+ end
+ end
+
+ private
+
+ def through_records_by_owner
+ ActiveRecord::Associations::Preloader.new(
+ owners, through_reflection.name,
+ through_options
+ ).run
+
+ Hash[owners.map do |owner|
+ through_records = Array.wrap(owner.send(through_reflection.name))
+
+ # Dont cache the association - we would only be caching a subset
+ if reflection.options[:source_type] && through_reflection.collection?
+ owner.association(through_reflection.name).reset
+ end
+
+ [owner, through_records]
+ end]
+ end
+
+ def through_options
+ through_options = {}
+
+ if options[:source_type]
+ through_options[:conditions] = { reflection.foreign_type => options[:source_type] }
+ else
+ if options[:conditions]
+ through_options[:include] = options[:include] || options[:source]
+ through_options[:conditions] = options[:conditions]
+ end
+
+ through_options[:order] = options[:order]
+ end
+
+ through_options
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
new file mode 100644
index 0000000000..4edbe216be
--- /dev/null
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -0,0 +1,55 @@
+module ActiveRecord
+ module Associations
+ class SingularAssociation < Association #:nodoc:
+ # Implements the reader method, e.g. foo.bar for Foo.has_one :bar
+ def reader(force_reload = false)
+ if force_reload
+ klass.uncached { reload }
+ elsif !loaded? || stale_target?
+ reload
+ end
+
+ target
+ end
+
+ # Implements the writer method, e.g. foo.items= for Foo.has_many :items
+ def writer(record)
+ replace(record)
+ end
+
+ def create(attributes = {})
+ new_record(:create, attributes)
+ end
+
+ def create!(attributes = {})
+ build(attributes).tap { |record| record.save! }
+ end
+
+ def build(attributes = {})
+ new_record(:build, attributes)
+ end
+
+ private
+
+ def find_target
+ scoped.first.tap { |record| set_inverse_instance(record) }
+ end
+
+ # Implemented by subclasses
+ def replace(record)
+ raise NotImplementedError, "Subclasses must implement a replace(record) method"
+ end
+
+ def set_new_record(record)
+ replace(record)
+ end
+
+ def new_record(method, attributes)
+ attributes = scoped.scope_for_create.merge(attributes || {})
+ record = reflection.send("#{method}_association", attributes)
+ set_new_record(record)
+ record
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb
new file mode 100644
index 0000000000..e6ab628719
--- /dev/null
+++ b/activerecord/lib/active_record/associations/through_association.rb
@@ -0,0 +1,80 @@
+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 = scope.merge(reflection.klass.scoped)
+ 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)
+ if source_reflection.macro != :belongs_to
+ raise HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection)
+ end
+
+ join_attributes = {
+ source_reflection.foreign_key =>
+ records.map { |record|
+ record.send(source_reflection.association_primary_key)
+ }
+ }
+
+ if options[:source_type]
+ join_attributes[source_reflection.foreign_type] =
+ records.map { |record| record.class.base_class.name }
+ end
+
+ if records.count == 1
+ Hash[join_attributes.map { |k, v| [k, v.first] }]
+ else
+ join_attributes
+ end
+ end
+
+ # 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].to_s
+ end
+ end
+
+ def foreign_key_present?
+ through_reflection.macro == :belongs_to &&
+ !owner[through_reflection.foreign_key].nil?
+ end
+
+ def ensure_not_nested
+ if reflection.nested?
+ raise HasManyThroughNestedAssociationsAreReadonly.new(owner, reflection)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/through_association_scope.rb b/activerecord/lib/active_record/associations/through_association_scope.rb
deleted file mode 100644
index cabb33c4a8..0000000000
--- a/activerecord/lib/active_record/associations/through_association_scope.rb
+++ /dev/null
@@ -1,154 +0,0 @@
-module ActiveRecord
- # = Active Record Through Association Scope
- module Associations
- module ThroughAssociationScope
-
- protected
-
- def construct_scope
- { :create => construct_owner_attributes(@reflection),
- :find => { :conditions => construct_conditions,
- :joins => construct_joins,
- :include => @reflection.options[:include] || @reflection.source_reflection.options[:include],
- :select => construct_select,
- :order => @reflection.options[:order],
- :limit => @reflection.options[:limit],
- :readonly => @reflection.options[:readonly],
- } }
- end
-
- # Build SQL conditions from attributes, qualified by table name.
- def construct_conditions
- table_name = @reflection.through_reflection.quoted_table_name
- conditions = construct_quoted_owner_attributes(@reflection.through_reflection).map do |attr, value|
- "#{table_name}.#{attr} = #{value}"
- end
- conditions << sql_conditions if sql_conditions
- "(" + conditions.join(') AND (') + ")"
- end
-
- # Associate attributes pointing to owner, quoted.
- def construct_quoted_owner_attributes(reflection)
- if as = reflection.options[:as]
- { "#{as}_id" => owner_quoted_id,
- "#{as}_type" => reflection.klass.quote_value(
- @owner.class.base_class.name.to_s,
- reflection.klass.columns_hash["#{as}_type"]) }
- elsif reflection.macro == :belongs_to
- { reflection.klass.primary_key => @owner.class.quote_value(@owner[reflection.primary_key_name]) }
- else
- { reflection.primary_key_name => owner_quoted_id }
- end
- end
-
- def construct_from
- @reflection.table_name
- end
-
- def construct_select(custom_select = nil)
- distinct = "DISTINCT " if @reflection.options[:uniq]
- selected = custom_select || @reflection.options[:select] || "#{distinct}#{@reflection.quoted_table_name}.*"
- end
-
- def construct_joins(custom_joins = nil)
- polymorphic_join = nil
- if @reflection.source_reflection.macro == :belongs_to
- reflection_primary_key = @reflection.klass.primary_key
- source_primary_key = @reflection.source_reflection.primary_key_name
- if @reflection.options[:source_type]
- polymorphic_join = "AND %s.%s = %s" % [
- @reflection.through_reflection.quoted_table_name, "#{@reflection.source_reflection.options[:foreign_type]}",
- @owner.class.quote_value(@reflection.options[:source_type])
- ]
- end
- else
- reflection_primary_key = @reflection.source_reflection.primary_key_name
- source_primary_key = @reflection.through_reflection.klass.primary_key
- if @reflection.source_reflection.options[:as]
- polymorphic_join = "AND %s.%s = %s" % [
- @reflection.quoted_table_name, "#{@reflection.source_reflection.options[:as]}_type",
- @owner.class.quote_value(@reflection.through_reflection.klass.name)
- ]
- end
- end
-
- "INNER JOIN %s ON %s.%s = %s.%s %s #{@reflection.options[:joins]} #{custom_joins}" % [
- @reflection.through_reflection.quoted_table_name,
- @reflection.quoted_table_name, reflection_primary_key,
- @reflection.through_reflection.quoted_table_name, source_primary_key,
- polymorphic_join
- ]
- end
-
- # Construct attributes for associate pointing to owner.
- def construct_owner_attributes(reflection)
- if as = reflection.options[:as]
- { "#{as}_id" => @owner.id,
- "#{as}_type" => @owner.class.base_class.name.to_s }
- else
- { reflection.primary_key_name => @owner.id }
- end
- end
-
- # Construct attributes for :through pointing to owner and associate.
- def construct_join_attributes(associate)
- # TODO: revisit this to allow it for deletion, supposing dependent option is supported
- raise ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(@owner, @reflection) if [:has_one, :has_many].include?(@reflection.source_reflection.macro)
-
- join_attributes = construct_owner_attributes(@reflection.through_reflection).merge(@reflection.source_reflection.primary_key_name => associate.id)
-
- if @reflection.options[:source_type]
- join_attributes.merge!(@reflection.source_reflection.options[:foreign_type] => associate.class.base_class.name.to_s)
- end
-
- if @reflection.through_reflection.options[:conditions].is_a?(Hash)
- join_attributes.merge!(@reflection.through_reflection.options[:conditions])
- end
-
- join_attributes
- end
-
- def conditions
- @conditions = build_conditions unless defined?(@conditions)
- @conditions
- end
-
- def build_conditions
- association_conditions = @reflection.options[:conditions]
- through_conditions = build_through_conditions
- source_conditions = @reflection.source_reflection.options[:conditions]
- uses_sti = !@reflection.through_reflection.klass.descends_from_active_record?
-
- if association_conditions || through_conditions || source_conditions || uses_sti
- all = []
-
- [association_conditions, source_conditions].each do |conditions|
- all << interpolate_sql(sanitize_sql(conditions)) if conditions
- end
-
- all << through_conditions if through_conditions
- all << build_sti_condition if uses_sti
-
- all.map { |sql| "(#{sql})" } * ' AND '
- end
- end
-
- def build_through_conditions
- conditions = @reflection.through_reflection.options[:conditions]
- if conditions.is_a?(Hash)
- interpolate_sql(@reflection.through_reflection.klass.send(:sanitize_sql, conditions)).gsub(
- @reflection.quoted_table_name,
- @reflection.through_reflection.quoted_table_name)
- elsif conditions
- interpolate_sql(sanitize_sql(conditions))
- end
- end
-
- def build_sti_condition
- @reflection.through_reflection.klass.send(:type_condition).to_sql
- end
-
- alias_method :sql_conditions, :conditions
- end
- end
-end
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 56e18eced0..5833c65893 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -10,7 +10,18 @@ module ActiveRecord
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods
- super(columns_hash.keys)
+ return if attribute_methods_generated?
+ super(column_names)
+ @attribute_methods_generated = true
+ end
+
+ def attribute_methods_generated?
+ @attribute_methods_generated ||= false
+ end
+
+ def undefine_attribute_methods(*args)
+ super
+ @attribute_methods_generated = false
end
# Checks whether the method is defined in the model or any of its subclasses
@@ -18,7 +29,11 @@ module ActiveRecord
# method is defined by Active Record though.
def instance_method_already_implemented?(method_name)
method_name = method_name.to_s
- @_defined_class_methods ||= ancestors.first(ancestors.index(ActiveRecord::Base)).sum([]) { |m| m.public_instance_methods(false) | m.private_instance_methods(false) | m.protected_instance_methods(false) }.map {|m| m.to_s }.to_set
+ index = ancestors.index(ActiveRecord::Base) || ancestors.length
+ @_defined_class_methods ||= ancestors.first(index).map { |m|
+ m.instance_methods(false) | m.private_instance_methods(false)
+ }.flatten.map {|m| m.to_s }.to_set
+
@@_defined_activerecord_methods ||= defined_activerecord_methods
raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord" if @@_defined_activerecord_methods.include?(method_name)
@_defined_class_methods.include?(method_name)
@@ -27,9 +42,8 @@ module ActiveRecord
def defined_activerecord_methods
active_record = ActiveRecord::Base
super_klass = ActiveRecord::Base.superclass
- methods = active_record.public_instance_methods - super_klass.public_instance_methods
- methods += active_record.private_instance_methods - super_klass.private_instance_methods
- methods += active_record.protected_instance_methods - super_klass.protected_instance_methods
+ methods = (active_record.instance_methods - super_klass.instance_methods) +
+ (active_record.private_instance_methods - super_klass.private_instance_methods)
methods.map {|m| m.to_s }.to_set
end
end
@@ -48,13 +62,13 @@ module ActiveRecord
end
def respond_to?(*args)
- self.class.define_attribute_methods
+ self.class.define_attribute_methods unless self.class.attribute_methods_generated?
super
end
protected
def attribute_method?(attr_name)
- attr_name == 'id' || attributes.include?(attr_name)
+ attr_name == 'id' || (defined?(@attributes) && @attributes.include?(attr_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
index a4e144f233..bde11d0494 100644
--- a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb
+++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb
@@ -13,21 +13,19 @@ module ActiveRecord
# Returns a hash of attributes before typecasting and deserialization.
def attributes_before_type_cast
- self.attribute_names.inject({}) do |attrs, name|
- attrs[name] = read_attribute_before_type_cast(name)
- attrs
- end
+ @attributes
end
private
- # Handle *_before_type_cast for method_missing.
- def attribute_before_type_cast(attribute_name)
- if attribute_name == 'id'
- read_attribute_before_type_cast(self.class.primary_key)
- else
- read_attribute_before_type_cast(attribute_name)
- end
+
+ # Handle *_before_type_cast for method_missing.
+ def attribute_before_type_cast(attribute_name)
+ if attribute_name == 'id'
+ read_attribute_before_type_cast(self.class.primary_key)
+ else
+ read_attribute_before_type_cast(attribute_name)
end
+ end
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb
index cf4594ad7f..3eff3d54e3 100644
--- a/activerecord/lib/active_record/attribute_methods/dirty.rb
+++ b/activerecord/lib/active_record/attribute_methods/dirty.rb
@@ -1,3 +1,4 @@
+require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/object/blank'
module ActiveRecord
@@ -12,7 +13,7 @@ module ActiveRecord
raise "You cannot include Dirty after Timestamp"
end
- superclass_delegating_accessor :partial_updates
+ class_attribute :partial_updates
self.partial_updates = true
end
@@ -21,6 +22,8 @@ module ActiveRecord
if status = super
@previously_changed = changes
@changed_attributes.clear
+ elsif IdentityMap.enabled?
+ IdentityMap.remove(self)
end
status
end
@@ -31,6 +34,9 @@ module ActiveRecord
@previously_changed = changes
@changed_attributes.clear
end
+ rescue
+ IdentityMap.remove(self) if IdentityMap.enabled?
+ raise
end
# <tt>reload</tt> the record and clears changed attributes.
@@ -88,7 +94,7 @@ module ActiveRecord
end
def clone_with_time_zone_conversion_attribute?(attr, old)
- old.class.name == "Time" && time_zone_aware_attributes && !skip_time_zone_conversion_for_attributes.include?(attr.to_sym)
+ old.class.name == "Time" && time_zone_aware_attributes && !self.skip_time_zone_conversion_for_attributes.include?(attr.to_sym)
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
index 82d94b848a..fcdd31ddea 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -3,36 +3,48 @@ module ActiveRecord
module PrimaryKey
extend ActiveSupport::Concern
- # Returns this record's primary key value wrapped in an Array
- # or nil if the record is a new_record?
+ # Returns this record's primary key value wrapped in an Array or nil if
+ # the record is not persisted? or has just been destroyed.
def to_key
- new_record? ? nil : [ id ]
+ key = send(self.class.primary_key)
+ [key] if key
end
module ClassMethods
# Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
# primary_key_prefix_type setting, though.
def primary_key
- reset_primary_key
+ @primary_key ||= reset_primary_key
end
def reset_primary_key #:nodoc:
- key = get_primary_key(base_class.name)
+ key = self == base_class ? get_primary_key(base_class.name) :
+ base_class.primary_key
+
set_primary_key(key)
key
end
def get_primary_key(base_name) #:nodoc:
- key = 'id'
+ return 'id' unless base_name && !base_name.blank?
+
case primary_key_prefix_type
- when :table_name
- key = base_name.to_s.foreign_key(false)
- when :table_name_with_underscore
- key = base_name.to_s.foreign_key
+ when :table_name
+ base_name.foreign_key(false)
+ when :table_name_with_underscore
+ base_name.foreign_key
+ else
+ if ActiveRecord::Base != self && connection.table_exists?(table_name)
+ connection.primary_key(table_name)
+ else
+ 'id'
+ end
end
- key
end
+ attr_accessor :original_primary_key
+ attr_writer :primary_key
+
# Sets the name of the primary key column to use to the given value,
# or (if the value is nil or false) to the value returned by the given
# block.
@@ -41,9 +53,12 @@ module ActiveRecord
# set_primary_key "sysid"
# end
def set_primary_key(value = nil, &block)
- define_attr_method :primary_key, value, &block
+ @primary_key ||= ''
+ self.original_primary_key = @primary_key
+ value &&= value.to_s
+ connection_pool.primary_keys[table_name] = value
+ self.primary_key = block_given? ? instance_eval(&block) : value
end
- alias :primary_key= :set_primary_key
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
index 3da3d9d8cc..69d5cd83f1 100644
--- a/activerecord/lib/active_record/attribute_methods/read.rb
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -20,14 +20,13 @@ module ActiveRecord
# be cached. Usually caching only pays off for attributes with expensive conversion
# methods, like time related columns (e.g. +created_at+, +updated_at+).
def cache_attributes(*attribute_names)
- attribute_names.each {|attr| cached_attributes << attr.to_s}
+ cached_attributes.merge attribute_names.map { |attr| attr.to_s }
end
# Returns the attributes which are cached. By default time related columns
# with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
def cached_attributes
- @cached_attributes ||=
- columns.select{|c| attribute_types_cached_by_default.include?(c.type)}.map{|col| col.name}.to_set
+ @cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
end
# Returns +true+ if the provided attribute is being cached.
@@ -37,10 +36,10 @@ module ActiveRecord
protected
def define_method_attribute(attr_name)
- if self.serialized_attributes[attr_name]
+ if serialized_attributes.include?(attr_name)
define_read_method_for_serialized_attribute(attr_name)
else
- define_read_method(attr_name.to_sym, attr_name, columns_hash[attr_name])
+ define_read_method(attr_name, attr_name, columns_hash[attr_name])
end
if attr_name == primary_key && attr_name != "id"
@@ -49,33 +48,52 @@ module ActiveRecord
end
private
+ def cacheable_column?(column)
+ serialized_attributes.include?(column.name) || attribute_types_cached_by_default.include?(column.type)
+ end
+
# Define read method for serialized attribute.
def define_read_method_for_serialized_attribute(attr_name)
- generated_attribute_methods.module_eval("def #{attr_name}; unserialize_attribute('#{attr_name}'); end", __FILE__, __LINE__)
+ access_code = "@attributes_cache['#{attr_name}'] ||= @attributes['#{attr_name}']"
+ generated_attribute_methods.module_eval("def _#{attr_name}; #{access_code}; end; alias #{attr_name} _#{attr_name}", __FILE__, __LINE__)
end
# Define an attribute reader method. Cope with nil column.
def define_read_method(symbol, attr_name, column)
- cast_code = column.type_cast_code('v') if column
- access_code = cast_code ? "(v=@attributes['#{attr_name}']) && #{cast_code}" : "@attributes['#{attr_name}']"
+ cast_code = column.type_cast_code('v')
+ access_code = "(v=@attributes['#{attr_name}']) && #{cast_code}"
unless attr_name.to_s == self.primary_key.to_s
- access_code = access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
+ access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
end
if cache_attribute?(attr_name)
access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})"
end
- generated_attribute_methods.module_eval("def #{symbol}; #{access_code}; end", __FILE__, __LINE__)
+ if symbol =~ /^[a-zA-Z_]\w*[!?=]?$/
+ generated_attribute_methods.module_eval("def _#{symbol}; #{access_code}; end; alias #{symbol} _#{symbol}", __FILE__, __LINE__)
+ else
+ generated_attribute_methods.module_eval do
+ define_method("_#{symbol}") { eval(access_code) }
+ alias_method(symbol, "_#{symbol}")
+ end
+ 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)
+ send "_#{attr_name}"
+ rescue NoMethodError
+ _read_attribute attr_name
+ end
+
+ def _read_attribute(attr_name)
attr_name = attr_name.to_s
attr_name = self.class.primary_key if attr_name == 'id'
- if !(value = @attributes[attr_name]).nil?
+ value = @attributes[attr_name]
+ unless value.nil?
if column = column_for_attribute(attr_name)
if unserializable_attribute?(attr_name, column)
unserialize_attribute(attr_name)
@@ -85,26 +103,20 @@ module ActiveRecord
else
value
end
- else
- nil
end
end
# Returns true if the attribute is of a text column and marked for serialization.
def unserializable_attribute?(attr_name, column)
- column.text? && self.class.serialized_attributes[attr_name]
+ column.text? && self.class.serialized_attributes.include?(attr_name)
end
# Returns the unserialized object of the attribute.
def unserialize_attribute(attr_name)
- unserialized_object = object_from_yaml(@attributes[attr_name])
+ coder = self.class.serialized_attributes[attr_name]
+ unserialized_object = coder.load(@attributes[attr_name])
- if unserialized_object.is_a?(self.class.serialized_attributes[attr_name]) || unserialized_object.nil?
- @attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object
- else
- raise SerializationTypeMismatch,
- "#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, but was a #{unserialized_object.class.to_s}"
- end
+ @attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object
end
private
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
index 8f0aacba42..6aac96df6f 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/class/attribute'
+
module ActiveRecord
module AttributeMethods
module TimeZoneConversion
@@ -7,24 +9,25 @@ module ActiveRecord
cattr_accessor :time_zone_aware_attributes, :instance_writer => false
self.time_zone_aware_attributes = false
- class_inheritable_accessor :skip_time_zone_conversion_for_attributes, :instance_writer => 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 read method automatically converts the UTC time stored in the database to the time
+ # This enhanced read method automatically converts the UTC time stored in the database to the time
# 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}(reload = false)
+ def _#{attr_name}
cached = @attributes_cache['#{attr_name}']
- return cached if cached && !reload
- time = read_attribute('#{attr_name}')
+ return cached if cached
+ time = _read_attribute('#{attr_name}')
@attributes_cache['#{attr_name}'] = time.acts_like?(:time) ? time.in_time_zone : time
end
+ alias #{attr_name} _#{attr_name}
EOV
generated_attribute_methods.module_eval(method_body, __FILE__, line)
else
@@ -37,12 +40,14 @@ module ActiveRecord
def define_method_attribute=(attr_name)
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
method_body, line = <<-EOV, __LINE__ + 1
- def #{attr_name}=(time)
+ def #{attr_name}=(original_time)
+ time = original_time
unless time.acts_like?(:time)
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
end
time = time.in_time_zone rescue nil if time
- write_attribute(:#{attr_name}, time)
+ write_attribute(:#{attr_name}, original_time)
+ @attributes_cache["#{attr_name}"] = time
end
EOV
generated_attribute_methods.module_eval(method_body, __FILE__, line)
@@ -53,7 +58,7 @@ module ActiveRecord
private
def create_time_zone_conversion_attribute?(name, column)
- time_zone_aware_attributes && !skip_time_zone_conversion_for_attributes.include?(name.to_sym) && [:datetime, :timestamp].include?(column.type)
+ time_zone_aware_attributes && !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) && [:datetime, :timestamp].include?(column.type)
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb
index 7a2de3bf80..3c4dab304e 100644
--- a/activerecord/lib/active_record/attribute_methods/write.rb
+++ b/activerecord/lib/active_record/attribute_methods/write.rb
@@ -10,11 +10,17 @@ module ActiveRecord
module ClassMethods
protected
def define_method_attribute=(attr_name)
- generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
+ if attr_name =~ /^[a-zA-Z_]\w*[!?=]?$/
+ generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
+ else
+ generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value|
+ write_attribute(attr_name, new_value)
+ end
+ end
end
end
- # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings
+ # 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
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 2c7afe3c9f..48dbe0838a 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -2,14 +2,14 @@ require 'active_support/core_ext/array/wrap'
module ActiveRecord
# = Active Record Autosave Association
- #
- # AutosaveAssociation is a module that takes care of automatically saving
- # associacted records when parent is saved. In addition to saving, it
+ #
+ # +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 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 1 transaction. This should never leave the
+ # 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
@@ -18,6 +18,9 @@ module ActiveRecord
# 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.
+ #
# === One-to-one Example
#
# class Post
@@ -28,7 +31,7 @@ module ActiveRecord
# automatically _and_ atomically:
#
# post = Post.find(1)
- # post.title # => "The current global position of migrating ducks"
+ # post.title # => "The current global position of migrating ducks"
# post.author.name # => "alloy"
#
# post.title = "On the migration of ducks"
@@ -36,7 +39,7 @@ module ActiveRecord
#
# post.save
# post.reload
- # post.title # => "On the migration of ducks"
+ # 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
@@ -46,6 +49,7 @@ module ActiveRecord
# 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
#
@@ -53,40 +57,49 @@ module ActiveRecord
# post.reload.author # => nil
#
# Now it _is_ removed from the database:
+ #
# Author.find_by_id(id).nil? # => true
#
# === One-to-many Example
#
- # Consider a Post model with many Comments:
+ # When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
#
# class Post
- # has_many :comments, :autosave => true
+ # has_many :comments # :autosave option is no declared
# end
#
- # Saving changes to the parent and its associated model can now be performed
- # automatically _and_ atomically:
+ # post = Post.new(:title => 'ruby rocks')
+ # post.comments.build(:body => 'hello world')
+ # post.save # => saves both post and comment
#
- # post = Post.find(1)
- # post.title # => "The current global position of migrating ducks"
- # post.comments.first.body # => "Wow, awesome info thanks!"
- # post.comments.last.body # => "Actually, your article should be named differently."
+ # post = Post.create(:title => 'ruby rocks')
+ # post.comments.build(:body => 'hello world')
+ # post.save # => saves both post and comment
#
- # post.title = "On the migration of ducks"
- # post.comments.last.body = "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
+ # post = Post.create(:title => 'ruby rocks')
+ # post.comments.create(:body => 'hello world')
+ # post.save # => saves both post and comment
#
- # post.save
- # post.reload
- # post.title # => "On the migration of ducks"
- # post.comments.last.body # => "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
+ # When <tt>:autosave</tt> is true all children is saved, no matter whether they are new records:
#
- # Destroying one of the associated models members, as part of the parent's
- # save action, is as simple as marking it for destruction:
+ # 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
#
@@ -94,62 +107,53 @@ module ActiveRecord
# post.reload.comments.length # => 1
#
# Now it _is_ removed from the database:
+ #
# Comment.find_by_id(id).nil? # => true
#
# === Validation
#
- # Validation is performed on the parent as usual, but also on all autosave
- # enabled associations. If any of the associations fail validation, its
- # error messages will be applied on the parents errors object and validation
- # of the parent will fail.
- #
- # Consider a Post model with Author which validates the presence of its name
- # attribute:
- #
- # class Post
- # has_one :author, :autosave => true
- # end
- #
- # class Author
- # validates_presence_of :name
- # end
- #
- # post = Post.find(1)
- # post.author.name = ''
- # post.save # => false
- # post.errors # => #<ActiveRecord::Errors:0x174498c @errors={"author.name"=>["can't be blank"]}, @base=#<Post ...>>
- #
- # No validations will be performed on the associated models when validations
- # are skipped for the parent:
- #
- # post = Post.find(1)
- # post.author.name = ''
- # post.save(:validate => false) # => true
+ # Children records are validated unless <tt>:validate</tt> is +false+.
module AutosaveAssociation
extend ActiveSupport::Concern
- ASSOCIATION_TYPES = %w{ has_one belongs_to has_many has_and_belongs_to_many }
+ ASSOCIATION_TYPES = %w{ HasOne HasMany BelongsTo HasAndBelongsToMany }
+
+ module AssociationBuilderExtension #:nodoc:
+ def self.included(base)
+ base.valid_options << :autosave
+ end
+
+ def build
+ reflection = super
+ model.send(:add_autosave_association_callbacks, reflection)
+ reflection
+ end
+ end
included do
ASSOCIATION_TYPES.each do |type|
- send("valid_keys_for_#{type}_association") << :autosave
+ Associations::Builder.const_get(type).send(:include, AssociationBuilderExtension)
end
end
module ClassMethods
private
- # def belongs_to(name, options = {})
- # super
- # add_autosave_association_callbacks(reflect_on_association(name))
- # end
- ASSOCIATION_TYPES.each do |type|
- module_eval <<-CODE, __FILE__, __LINE__ + 1
- def #{type}(name, options = {})
- super
- add_autosave_association_callbacks(reflect_on_association(name))
+ def define_non_cyclic_method(name, reflection, &block)
+ define_method(name) do |*args|
+ result = true; @_already_called ||= {}
+ # Loop prevention for validation of associations
+ unless @_already_called[[name, reflection.name]]
+ begin
+ @_already_called[[name, reflection.name]]=true
+ result = instance_eval(&block)
+ ensure
+ @_already_called[[name, reflection.name]]=false
+ end
end
- CODE
+
+ result
+ end
end
# Adds validation and save callbacks for the association as specified by
@@ -172,16 +176,25 @@ module ActiveRecord
if collection
before_save :before_save_collection_association
- define_method(save_method) { save_collection_association(reflection) }
+ define_non_cyclic_method(save_method, reflection) { save_collection_association(reflection) }
# Doesn't use after_save as that would save associations added in after_create/after_update twice
after_create save_method
after_update save_method
else
if reflection.macro == :has_one
define_method(save_method) { save_has_one_association(reflection) }
- after_save save_method
+ # 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_method(save_method) { save_belongs_to_association(reflection) }
+ define_non_cyclic_method(save_method, reflection) { save_belongs_to_association(reflection) }
before_save save_method
end
end
@@ -189,7 +202,7 @@ module ActiveRecord
if reflection.validate? && !method_defined?(validation_method)
method = (collection ? :validate_collection_association : :validate_single_association)
- define_method(validation_method) { send(method, reflection) }
+ define_non_cyclic_method(validation_method, reflection) { send(method, reflection) }
validate validation_method
end
end
@@ -202,7 +215,7 @@ module ActiveRecord
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
+ # 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.
@@ -222,7 +235,7 @@ module ActiveRecord
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
@@ -230,7 +243,7 @@ module ActiveRecord
# unless the parent is/was a new record itself.
def associated_records_to_validate_or_save(association, new_record, autosave)
if new_record
- association
+ association && association.target
elsif autosave
association.target.find_all { |record| record.changed_for_autosave? }
else
@@ -243,16 +256,16 @@ module ActiveRecord
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?(&:changed_for_autosave?)
+ 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)
- if (association = association_instance_get(reflection.name)) && !association.target.nil?
- association_valid?(reflection, association)
- end
+ association = association_instance_get(reflection.name)
+ record = association && association.target
+ association_valid?(reflection, record) if record
end
# Validate the associated records if <tt>:validate</tt> or
@@ -269,12 +282,12 @@ module ActiveRecord
# Returns whether or not the association is valid and applies any errors to
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
# enabled records if they're marked_for_destruction? or destroyed.
- def association_valid?(reflection, association)
- return true if association.destroyed? || association.marked_for_destruction?
+ def association_valid?(reflection, record)
+ return true if record.destroyed? || record.marked_for_destruction?
- unless valid = association.valid?
+ unless valid = record.valid?
if reflection.options[:autosave]
- association.errors.each do |attribute, message|
+ record.errors.each do |attribute, message|
attribute = "#{reflection.name}.#{attribute}"
errors[attribute] << message
errors[attribute].uniq!
@@ -306,27 +319,35 @@ module ActiveRecord
autosave = reflection.options[:autosave]
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
+ begin
records.each do |record|
next if record.destroyed?
+ saved = true
+
if autosave && record.marked_for_destruction?
- association.destroy(record)
+ association.proxy.destroy(record)
elsif autosave != false && (@new_record_before_save || record.new_record?)
if autosave
- saved = association.send(:insert_record, record, false, false)
+ saved = association.insert_record(record, false)
else
- association.send(:insert_record, record)
+ association.insert_record(record)
end
elsif autosave
saved = record.save(:validate => false)
end
- raise ActiveRecord::Rollback if saved == false
+ raise ActiveRecord::Rollback unless saved
end
+ rescue
+ records.each {|x| IdentityMap.remove(x) } if IdentityMap.enabled?
+ raise
+ end
+
end
- # reconstruct the SQL queries now that we know the owner's id
- association.send(:construct_sql) if association.respond_to?(:construct_sql)
+ # reconstruct the scope now that we know the owner's id
+ association.send(:construct_scope) if association.respond_to?(:construct_scope)
end
end
@@ -339,16 +360,18 @@ module ActiveRecord
# This all happens inside a transaction, _if_ the Transactions module is included into
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
def save_has_one_association(reflection)
- if (association = association_instance_get(reflection.name)) && !association.target.nil? && !association.destroyed?
+ association = association_instance_get(reflection.name)
+ record = association && association.load_target
+ if record && !record.destroyed?
autosave = reflection.options[:autosave]
- if autosave && association.marked_for_destruction?
- association.destroy
+ if autosave && record.marked_for_destruction?
+ record.destroy
else
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
- if autosave != false && (new_record? || association.new_record? || association[reflection.primary_key_name] != key || autosave)
- association[reflection.primary_key_name] = key
- saved = association.save(:validate => !autosave)
+ if autosave != false && (new_record? || record.new_record? || record[reflection.foreign_key] != key || autosave)
+ record[reflection.foreign_key] = key
+ saved = record.save(:validate => !autosave)
raise ActiveRecord::Rollback if !saved && autosave
saved
end
@@ -360,17 +383,20 @@ module ActiveRecord
#
# In addition, it will destroy the association if it was marked for destruction.
def save_belongs_to_association(reflection)
- if (association = association_instance_get(reflection.name)) && !association.destroyed?
+ association = association_instance_get(reflection.name)
+ record = association && association.load_target
+ if record && !record.destroyed?
autosave = reflection.options[:autosave]
- if autosave && association.marked_for_destruction?
- association.destroy
+ if autosave && record.marked_for_destruction?
+ record.destroy
elsif autosave != false
- saved = association.save(:validate => !autosave) if association.new_record? || autosave
+ saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
if association.updated?
- association_id = association.send(reflection.options[:primary_key] || :id)
- self[reflection.primary_key_name] = association_id
+ association_id = record.send(reflection.options[:primary_key] || :id)
+ self[reflection.foreign_key] = association_id
+ association.loaded!
end
saved if autosave
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 8da4fbcba7..b778b0c0f0 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -1,3 +1,8 @@
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
require 'set'
require 'active_support/benchmarkable'
@@ -7,7 +12,7 @@ require 'active_support/time'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/class/delegating_attributes'
-require 'active_support/core_ext/class/inheritable_attributes'
+require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/hash/deep_merge'
require 'active_support/core_ext/hash/indifferent_access'
@@ -15,7 +20,6 @@ require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/string/behavior'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/module/deprecation'
require 'active_support/core_ext/module/introspection'
require 'active_support/core_ext/object/duplicable'
require 'active_support/core_ext/object/blank'
@@ -26,18 +30,18 @@ require 'active_record/log_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 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/README.html for more insight.
+ # 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
+ # 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")
@@ -77,16 +81,16 @@ module ActiveRecord #:nodoc:
# 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+
+ # 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
+ # <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
+ # 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(
@@ -108,7 +112,7 @@ module ActiveRecord #:nodoc:
#
# Student.where(:grade => [9,11,12])
#
- # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
+ # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
# can be used to qualify the table name of a particular condition. For instance:
#
# Student.joins(:schools).where(:schools => { :type => 'public' })
@@ -116,10 +120,10 @@ module ActiveRecord #:nodoc:
#
# == 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
+ # 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
@@ -134,7 +138,7 @@ module ActiveRecord #:nodoc:
# end
# end
#
- # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
+ # 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
@@ -153,43 +157,40 @@ module ActiveRecord #:nodoc:
#
# == 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,
+ # 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
+ # 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 cleaner 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>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
- # like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
- # <tt>Payment.find_by_transaction_id</tt>. Instead of writing
+ # Dynamic attribute-based finders are a cleaner 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>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
+ # like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
+ # <tt>Payment.find_by_transaction_id</tt>. Instead of writing
# <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
- # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
+ # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
# <tt>Person.find_all_by_last_name(last_name)</tt>.
#
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
- #
+ #
# Person.where(:user_name => user_name, :password => password).first
- # Person.find_by_user_name_and_password #with dynamic finder
- #
- # Person.where(:user_name => user_name, :password => password, :gender => 'male').first
- # Payment.find_by_user_name_and_password_and_gender
+ # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
#
# It's even possible to call these dynamic finder methods on relations and named scopes.
#
# Payment.order("created_on").find_all_by_amount(50)
# Payment.pending.find_last_by_amount(100)
#
- # The same dynamic finder style can be used to create the object if it doesn't already exist.
- # This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
- # it already exists and otherwise creates it, then returns it. Protected attributes won't be set
- # unless they are given in a block.
+ # The same dynamic finder style can be used to create the object if it doesn't already exist.
+ # This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
+ # it already exists and otherwise creates it, then returns it. Protected attributes won't be set
+ # unless they are given in a block.
#
# # No 'Summer' tag exists
# Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
@@ -200,33 +201,33 @@ module ActiveRecord #:nodoc:
# # Now 'Bob' exist and is an 'admin'
# User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
#
- # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
+ # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
# saving it first. Protected attributes won't be set unless they are given in a block.
#
# # No 'Winter' tag exists
# winter = Tag.find_or_initialize_by_name("Winter")
- # winter.new_record? # true
+ # winter.persisted? # false
#
# To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
# a list of parameters.
#
# Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
#
- # That will either find an existing tag named "rails", or create a new one while setting the
+ # That will either find an existing tag named "rails", or create a new one while setting the
# user that created it.
#
# Just like <tt>find_by_*</tt>, you can also use <tt>scoped_by_*</tt> to retrieve data. The good thing about
# using this feature is that the very first time result is returned using <tt>method_missing</tt> technique
# but after that the method is declared on the class. Henceforth <tt>method_missing</tt> will not be hit.
#
- # User.scoped_by_user_name('David')
+ # User.scoped_by_user_name('David')
#
# == 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
+ # 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.
+ # This makes it possible to store arrays, hashes, and other non-mappable objects without doing
+ # any additional work.
#
# class User < ActiveRecord::Base
# serialize :preferences
@@ -235,7 +236,7 @@ module ActiveRecord #:nodoc:
# 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
+ # 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
@@ -245,10 +246,21 @@ module ActiveRecord #:nodoc:
# user = User.create(:preferences => %w( one two three ))
# User.find(user.id).preferences # raises SerializationTypeMismatch
#
+ # When you specify a class option, the default value for that attribute will be a new
+ # instance of that class.
+ #
+ # class User < ActiveRecord::Base
+ # serialize :preferences, OpenStruct
+ # end
+ #
+ # user = User.new
+ # user.preferences.theme_color = "red"
+ #
+ #
# == Single table inheritance
#
- # Active Record allows inheritance by storing the name of the class in a column that by
- # default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
+ # 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
@@ -256,12 +268,12 @@ module ActiveRecord #:nodoc:
# 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
+ # 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
+ # 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:
@@ -269,14 +281,14 @@ module ActiveRecord #:nodoc:
#
# == 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
+ # 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
+ # 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
@@ -284,25 +296,25 @@ module ActiveRecord #:nodoc:
# * 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
+ # * 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
+ # * AssociationTypeMismatch - The object assigned to the association wasn't of the type
# specified in the association definition.
# * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
- # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt>
+ # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt>
# before querying.
# * 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.
# * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
# * 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
+ # <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.
- # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
+ # * 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
+ # You can inspect the +attribute+ property of the exception object to determine which attribute
# triggered the error.
#
# *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
@@ -311,23 +323,11 @@ module ActiveRecord #:nodoc:
class Base
##
# :singleton-method:
- # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
- # which is then passed on to any new database connections made and which can be retrieved on both
+ # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
+ # 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+.
cattr_accessor :logger, :instance_writer => false
- class << self
- def reset_subclasses #:nodoc:
- ActiveSupport::Deprecation.warn 'ActiveRecord::Base.reset_subclasses no longer does anything in Rails 3. It will be removed in the final release; please update your apps and plugins.', caller
- end
-
- def subclasses
- descendants
- end
-
- deprecate :subclasses => :descendants
- end
-
##
# :singleton-method:
# Contains the database configuration - as is typically stored in config/database.yml -
@@ -360,9 +360,9 @@ module ActiveRecord #:nodoc:
##
# :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
+ # 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.
cattr_accessor :primary_key_prefix_type, :instance_writer => false
@@ -370,13 +370,13 @@ module ActiveRecord #:nodoc:
##
# :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.
+ # 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
+ # 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 = ""
@@ -398,7 +398,7 @@ module ActiveRecord #:nodoc:
##
# :singleton-method:
- # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling
+ # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling
# dates and times from the database. This is set to :local by default.
cattr_accessor :default_timezone, :instance_writer => false
@@default_timezone = :local
@@ -421,24 +421,25 @@ module ActiveRecord #:nodoc:
@@timestamped_migrations = true
# Determine whether to store the full constant name including namespace when using STI
- superclass_delegating_accessor :store_full_sti_class
+ class_attribute :store_full_sti_class
self.store_full_sti_class = true
# Stores the default scope for the class
- class_inheritable_accessor :default_scoping, :instance_writer => false
+ class_attribute :default_scoping, :instance_writer => false
self.default_scoping = []
- class << self # Class methods
- def colorize_logging(*args)
- ActiveSupport::Deprecation.warn "ActiveRecord::Base.colorize_logging and " <<
- "config.active_record.colorize_logging are deprecated. Please use " <<
- "Rails::LogSubscriber.colorize_logging or config.colorize_logging instead", caller
- end
- alias :colorize_logging= :colorize_logging
+ # Returns a hash of all the attributes that have been specified for serialization as
+ # keys and their class restriction as values.
+ class_attribute :serialized_attributes
+ self.serialized_attributes = {}
+
+ class_attribute :_attr_readonly, :instance_writer => false
+ self._attr_readonly = []
+ class << self # Class methods
delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped
delegate :find_each, :find_in_batches, :to => :scoped
- delegate :select, :group, :order, :reorder, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
+ delegate :select, :group, :order, :except, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
# Executes a custom SQL query against your database and returns all the results. The results will
@@ -462,9 +463,9 @@ module ActiveRecord #:nodoc:
#
# # 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={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
- def find_by_sql(sql)
- connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
+ # > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...]
+ def find_by_sql(sql, binds = [])
+ connection.select_all(sanitize_sql(sql), "#{name} Load", binds).collect! { |record| instantiate(record) }
end
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
@@ -519,12 +520,12 @@ module ActiveRecord #:nodoc:
# Attributes listed as readonly will be used to create a new record but update operations will
# ignore these fields.
def attr_readonly(*attributes)
- write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (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
- read_inheritable_attribute(:attr_readonly) || []
+ self._attr_readonly
end
# If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
@@ -539,24 +540,26 @@ module ActiveRecord #:nodoc:
#
# ==== Example
# # Serialize a preferences attribute
- # class User
+ # class User < ActiveRecord::Base
# serialize :preferences
# end
def serialize(attr_name, class_name = Object)
- serialized_attributes[attr_name.to_s] = class_name
- end
+ coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
+ class_name
+ else
+ Coders::YAMLColumn.new(class_name)
+ end
- # Returns a hash of all the attributes that have been specified for serialization as
- # keys and their class restriction as values.
- def serialized_attributes
- read_inheritable_attribute(:attr_serialized) or write_inheritable_attribute(:attr_serialized, {})
+ # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
+ # has its own hash of own serialized attributes
+ self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
end
- # Guesses the table name (in forced lower-case) based on the name of the class in the
- # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
+ # 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
+ # 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
@@ -605,10 +608,10 @@ module ActiveRecord #:nodoc:
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
end
- # Defines the column name for use with single table inheritance. Use
+ # Defines the column name for use with single table inheritance. Use
# <tt>set_inheritance_column</tt> to set a different value.
def inheritance_column
- @inheritance_column ||= "type".freeze
+ @inheritance_column ||= "type"
end
# Lazy-set the sequence name to the connection's default. This method
@@ -623,7 +626,7 @@ module ActiveRecord #:nodoc:
default
end
- # Sets the table name. If the value is nil or false then the value returned by the given
+ # Sets the table name. If the value is nil or false then the value returned by the given
# block is used.
#
# class Project < ActiveRecord::Base
@@ -632,6 +635,9 @@ module ActiveRecord #:nodoc:
def set_table_name(value = nil, &block)
@quoted_table_name = nil
define_attr_method :table_name, value, &block
+
+ @arel_table = Arel::Table.new(table_name, arel_engine)
+ @relation = Relation.new(self, arel_table)
end
alias :table_name= :set_table_name
@@ -675,16 +681,12 @@ module ActiveRecord #:nodoc:
# Returns an array of column objects for the table associated with this class.
def columns
- unless defined?(@columns) && @columns
- @columns = connection.columns(table_name, "#{name} Columns")
- @columns.each { |column| column.primary = column.name == primary_key }
- end
- @columns
+ connection_pool.columns[table_name]
end
# Returns a hash of column objects for the table associated with this class.
def columns_hash
- @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
+ connection_pool.columns_hash[table_name]
end
# Returns an array of column names as strings.
@@ -739,13 +741,16 @@ module ActiveRecord #:nodoc:
# end
# end
def reset_column_information
+ connection.clear_cache!
undefine_attribute_methods
- @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
- @arel_engine = @relation = @arel_table = nil
+ connection_pool.clear_table_cache!(table_name) if table_exists?
+
+ @column_names = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
+ @arel_engine = @relation = nil
end
- def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
- descendants.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
+ def clear_cache! # :nodoc:
+ connection_pool.clear_cache!
end
def attribute_method?(attribute)
@@ -756,15 +761,12 @@ module ActiveRecord #:nodoc:
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
- rescue
- # OPTIMIZE this rescue is to fix this test: ./test/cases/reflection_test.rb:56:in `test_human_name_for_column'
- # Apparently the method base_class causes some trouble.
- # It now works for sure.
- [self]
end
# Set the i18n scope to overwrite ActiveModel.
@@ -786,7 +788,7 @@ module ActiveRecord #:nodoc:
:true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
end
- # Returns a string like 'Post id:integer, title:string, body:text'
+ # Returns a string like 'Post(id:integer, title:string, body:text)'
def inspect
if self == Base
super
@@ -814,6 +816,10 @@ module ActiveRecord #:nodoc:
object.is_a?(self)
end
+ def symbolized_base_class
+ @symbolized_base_class ||= base_class.to_s.to_sym
+ end
+
# Returns the base AR subclass that this class descends from. If A
# extends AR::Base, A.base_class will return A. If B descends from A
# through some arbitrarily deep hierarchy, B.base_class will return A.
@@ -847,15 +853,15 @@ module ActiveRecord #:nodoc:
end
def arel_table
- @arel_table ||= Arel::Table.new(table_name, arel_engine)
+ Arel::Table.new(table_name, arel_engine)
end
def arel_engine
@arel_engine ||= begin
if self == ActiveRecord::Base
- Arel::Table.engine
+ ActiveRecord::Base
else
- connection_handler.connection_pools[name] ? Arel::Sql::Engine.new(self) : superclass.arel_engine
+ connection_handler.connection_pools[name] ? self : superclass.arel_engine
end
end
end
@@ -876,7 +882,12 @@ module ActiveRecord #:nodoc:
# limit(10) # Fires "SELECT * FROM posts LIMIT 10"
# }
#
- def unscoped
+ # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt>
+ # does not work. Assuming that <tt>published</tt> is a <tt>scope</tt> following two statements are same.
+ #
+ # Post.unscoped.published
+ # Post.published
+ def unscoped #:nodoc:
block_given? ? relation.scoping { yield } : relation
end
@@ -885,32 +896,55 @@ module ActiveRecord #:nodoc:
Thread.current[key] = Thread.current[key].presence || self.default_scoping.dup
end
- private
+ def before_remove_const #:nodoc:
+ reset_scoped_methods
+ end
- def relation #:nodoc:
- @relation ||= Relation.new(self, arel_table)
- finder_needs_type_condition? ? @relation.where(type_condition) : @relation
+ # Specifies how the record is loaded by +Marshal+.
+ #
+ # +_load+ sets an instance variable for each key in the hash it takes as input.
+ # Override this method if you require more complex marshalling.
+ def _load(data)
+ record = allocate
+ record.init_with(Marshal.load(data))
+ record
+ end
+
+
+ # Finder methods must instantiate through this method to work with the
+ # single-table inheritance model that makes it possible to create
+ # objects of different types from the same table.
+ def instantiate(record)
+ sti_class = find_sti_class(record[inheritance_column])
+ record_id = sti_class.primary_key && record[sti_class.primary_key]
+
+ if ActiveRecord::IdentityMap.enabled? && record_id
+ if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number?
+ record_id = record_id.to_i
+ end
+ if instance = IdentityMap.get(sti_class, record_id)
+ instance.reinit_with('attributes' => record)
+ else
+ instance = sti_class.allocate.init_with('attributes' => record)
+ IdentityMap.add(instance)
+ end
+ else
+ instance = sti_class.allocate.init_with('attributes' => record)
end
- # Finder methods must instantiate through this method to work with the
- # single-table inheritance model that makes it possible to create
- # objects of different types from the same table.
- def instantiate(record)
- object = find_sti_class(record[inheritance_column]).allocate
+ instance
+ end
- object.instance_variable_set(:@attributes, record)
- object.instance_variable_set(:@attributes_cache, {})
- object.instance_variable_set(:@new_record, false)
- object.instance_variable_set(:@readonly, false)
- object.instance_variable_set(:@destroyed, false)
- object.instance_variable_set(:@marked_for_destruction, false)
- object.instance_variable_set(:@previously_changed, {})
- object.instance_variable_set(:@changed_attributes, {})
+ private
- object.send(:_run_find_callbacks)
- object.send(:_run_initialize_callbacks)
+ def relation #:nodoc:
+ @relation ||= Relation.new(self, arel_table)
- object
+ if finder_needs_type_condition?
+ @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
+ else
+ @relation
+ end
end
def find_sti_class(type_name)
@@ -918,7 +952,11 @@ module ActiveRecord #:nodoc:
self
else
begin
- compute_type(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}'. " +
@@ -930,17 +968,16 @@ module ActiveRecord #:nodoc:
end
def construct_finder_arel(options = {}, scope = nil)
- relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : unscoped.merge(options)
+ relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options
relation = scope.merge(relation) if scope
relation
end
- def type_condition
- sti_column = arel_table[inheritance_column]
- condition = sti_column.eq(sti_name)
- descendants.each { |subclass| condition = condition.or(sti_column.eq(subclass.sti_name)) }
+ def type_condition(table = arel_table)
+ sti_column = table[inheritance_column.to_sym]
+ sti_names = ([self] + descendants).map { |model| model.sti_name }
- condition
+ sti_column.in(sti_names)
end
# Guesses the table name, but does not decorate it with prefix and suffix information.
@@ -958,7 +995,7 @@ module ActiveRecord #:nodoc:
if parent < ActiveRecord::Base && !parent.abstract_class?
contained = parent.table_name
contained = contained.singularize if parent.pluralize_table_names
- contained << '_'
+ contained += '_'
end
"#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
else
@@ -967,14 +1004,14 @@ module ActiveRecord #:nodoc:
end
end
- # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and
+ # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and
# <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders
# section at the top of this file for more detailed information.
#
- # It's even possible to use all the additional parameters to +find+. For example, the
+ # It's even possible to use all the additional parameters to +find+. For example, the
# full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>.
#
- # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it
+ # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it
# is first invoked, so that future attempts to use it do not run through method_missing.
def method_missing(method_id, *arguments, &block)
if match = DynamicFinderMatch.match(method_id)
@@ -992,14 +1029,11 @@ module ActiveRecord #:nodoc:
super unless all_attributes_exists?(attribute_names)
if match.scope?
self.class_eval <<-METHOD, __FILE__, __LINE__ + 1
- def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args)
- options = args.extract_options! # options = args.extract_options!
- attributes = construct_attributes_from_arguments( # attributes = construct_attributes_from_arguments(
- [:#{attribute_names.join(',:')}], args # [:user_name, :password], args
- ) # )
- #
- scoped(:conditions => attributes) # scoped(:conditions => attributes)
- end # end
+ def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args)
+ attributes = Hash[[:#{attribute_names.join(',:')}].zip(args)] # attributes = Hash[[:user_name, :password].zip(args)]
+ #
+ scoped(:conditions => attributes) # scoped(:conditions => attributes)
+ end # end
METHOD
send(method_id, *arguments)
end
@@ -1008,30 +1042,22 @@ module ActiveRecord #:nodoc:
end
end
- def construct_attributes_from_arguments(attribute_names, arguments)
- attributes = {}
- attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] }
- attributes
- end
-
# Similar in purpose to +expand_hash_conditions_for_aggregates+.
def expand_attribute_names_for_aggregates(attribute_names)
- expanded_attribute_names = []
- attribute_names.each do |attribute_name|
+ attribute_names.map { |attribute_name|
unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil?
- aggregate_mapping(aggregation).each do |field_attr, aggregate_attr|
- expanded_attribute_names << field_attr
+ aggregate_mapping(aggregation).map do |field_attr, _|
+ field_attr.to_sym
end
else
- expanded_attribute_names << attribute_name
+ attribute_name.to_sym
end
- end
- expanded_attribute_names
+ }.flatten
end
def all_attributes_exists?(attribute_names)
- attribute_names = expand_attribute_names_for_aggregates(attribute_names)
- attribute_names.all? { |name| column_methods_hash.include?(name.to_sym) }
+ (expand_attribute_names_for_aggregates(attribute_names) -
+ column_methods_hash.keys).empty?
end
protected
@@ -1087,9 +1113,9 @@ module ActiveRecord #:nodoc:
if method_scoping.is_a?(Hash)
# Dup first and second level of hash (method and params).
- method_scoping = method_scoping.inject({}) do |hash, (method, params)|
- hash[method] = (params == true) ? params : params.dup
- hash
+ method_scoping = method_scoping.dup
+ method_scoping.each do |method, params|
+ method_scoping[method] = params.dup unless params == true
end
method_scoping.assert_valid_keys([ :find, :create ])
@@ -1147,12 +1173,33 @@ MSG
# class Person < ActiveRecord::Base
# default_scope order('last_name, first_name')
# end
+ #
+ # <tt>default_scope</tt> is also applied while creating/building a record. It is not
+ # applied while updating a record.
+ #
+ # class Article < ActiveRecord::Base
+ # default_scope where(:published => true)
+ # end
+ #
+ # Article.new.published # => true
+ # Article.create.published # => true
def default_scope(options = {})
- self.default_scoping << construct_finder_arel(options, default_scoping.pop)
+ reset_scoped_methods
+ default_scoping = self.default_scoping.dup
+ self.default_scoping = default_scoping << construct_finder_arel(options, default_scoping.pop)
end
def current_scoped_methods #:nodoc:
- scoped_methods.last
+ method = scoped_methods.last
+ if method.respond_to?(:call)
+ relation.scoping { method.call }
+ else
+ method
+ end
+ end
+
+ def reset_scoped_methods #:nodoc:
+ Thread.current[:"#{self}_scoped_methods"] = nil
end
# Returns the class type of the record using the current module as a prefix. So descendants of
@@ -1161,7 +1208,7 @@ MSG
if type_name.match(/^::/)
# If the type is prefixed with a scope operator then we assume that
# the type_name is an absolute reference.
- type_name.constantize
+ ActiveSupport::Dependencies.constantize(type_name)
else
# Build a list of candidates to search for
candidates = []
@@ -1170,7 +1217,7 @@ MSG
candidates.each do |candidate|
begin
- constant = candidate.constantize
+ constant = ActiveSupport::Dependencies.constantize(candidate)
return constant if candidate == constant.to_s
rescue NameError => e
# We don't want to swallow NoMethodError < NameError errors
@@ -1274,9 +1321,11 @@ MSG
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
attrs = expand_hash_conditions_for_aggregates(attrs)
- table = Arel::Table.new(self.table_name, :engine => arel_engine, :as => default_table_name)
- builder = PredicateBuilder.new(arel_engine)
- builder.build_from_hash(attrs, table).map(&:to_sql).join(' AND ')
+ table = Arel::Table.new(table_name).alias(default_table_name)
+ viz = Arel::Visitors.for(arel_engine)
+ PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b|
+ viz.accept b
+ }.join(' AND ')
end
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
@@ -1294,7 +1343,7 @@ MSG
# ["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) and statement =~ /:\w+/
+ if values.first.is_a?(Hash) && statement =~ /:\w+/
replace_named_bind_variables(statement, values.first)
elsif statement.include?('?')
replace_bind_variables(statement, values)
@@ -1375,6 +1424,8 @@ MSG
# hence you can't have attributes that aren't part of the table columns.
def initialize(attributes = nil)
@attributes = attributes_from_column_definition
+ @association_cache = {}
+ @aggregation_cache = {}
@attributes_cache = {}
@new_record = true
@readonly = false
@@ -1384,43 +1435,66 @@ MSG
@changed_attributes = {}
ensure_proper_type
+ set_serialized_attributes
- if scope = self.class.send(:current_scoped_methods)
- create_with = scope.scope_for_create
- create_with.each { |att,value| self.send("#{att}=", value) } if create_with
- end
+ populate_with_current_scope_attributes
self.attributes = attributes unless attributes.nil?
result = yield self if block_given?
- _run_initialize_callbacks
+ run_callbacks :initialize
result
end
- # Cloned objects have no id assigned and are treated as new records. Note that this is a "shallow" clone
- # as it copies the object's attributes only, not its associations. The extent of a "deep" clone is
- # application specific and is therefore left to the application to implement according to its need.
- def initialize_copy(other)
- _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks)
- cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
- cloned_attributes.delete(self.class.primary_key)
+ # Populate +coder+ with attributes about this record that should be
+ # serialized. The structure of +coder+ defined in this method is
+ # guaranteed to match the structure of +coder+ passed to the +init_with+
+ # method.
+ #
+ # Example:
+ #
+ # class Post < ActiveRecord::Base
+ # end
+ # coder = {}
+ # Post.new.encode_with(coder)
+ # coder # => { 'id' => nil, ... }
+ def encode_with(coder)
+ coder['attributes'] = attributes
+ end
- @attributes = cloned_attributes
+ # 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 = coder['attributes']
- @changed_attributes = {}
- attributes_from_column_definition.each do |attr, orig_value|
- @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr])
- end
+ set_serialized_attributes
- clear_aggregation_cache
- clear_association_cache
- @attributes_cache = {}
- @new_record = true
- ensure_proper_type
+ @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
+ @association_cache = {}
+ @aggregation_cache = {}
+ @readonly = @destroyed = @marked_for_destruction = false
+ @new_record = false
+ run_callbacks :find
+ run_callbacks :initialize
- if scope = self.class.send(:current_scoped_methods)
- create_with = scope.scope_for_create
- create_with.each { |att,value| self.send("#{att}=", value) } if create_with
- end
+ self
+ end
+
+ # Specifies how the record is dumped by +Marshal+.
+ #
+ # +_dump+ emits a marshalled hash which has been passed to +encode_with+. Override this
+ # method if you require more complex marshalling.
+ def _dump(level)
+ dump = {}
+ encode_with(dump)
+ Marshal.dump(dump)
end
# Returns a String, which Action Pack uses for constructing an URL to this
@@ -1477,22 +1551,9 @@ MSG
@attributes.has_key?(attr_name.to_s)
end
- # Returns an array of names for the attributes available on this object sorted alphabetically.
+ # Returns an array of names for the attributes available on this object.
def attribute_names
- @attributes.keys.sort
- 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)).
- # (Alias for the protected read_attribute method).
- def [](attr_name)
- read_attribute(attr_name)
- end
-
- # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
- # (Alias for the protected write_attribute method).
- def []=(attr_name, value)
- write_attribute(attr_name, value)
+ @attributes.keys
end
# Allows you to set all the attributes at once by passing in a hash with keys
@@ -1525,8 +1586,10 @@ MSG
attributes.each do |k, v|
if k.include?("(")
multi_parameter_attributes << [ k, v ]
+ elsif respond_to?("#{k}=")
+ send("#{k}=", v)
else
- respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
+ raise(UnknownAttributeError, "unknown attribute: #{k}")
end
end
@@ -1535,9 +1598,7 @@ MSG
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
def attributes
- attrs = {}
- attribute_names.each { |name| attrs[name] = read_attribute(name) }
- attrs
+ Hash[@attributes.map { |name, _| [name, read_attribute(name)] }]
end
# Returns an <tt>#inspect</tt>-like string for the value of the
@@ -1568,8 +1629,7 @@ MSG
# Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
# nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).
def attribute_present?(attribute)
- value = read_attribute(attribute)
- !value.blank?
+ !_read_attribute(attribute).blank?
end
# Returns the column object for the named attribute.
@@ -1577,16 +1637,25 @@ MSG
self.class.columns_hash[name.to_s]
end
- # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
+ # 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)
comparison_object.equal?(self) ||
- (comparison_object.instance_of?(self.class) &&
- comparison_object.id == id && !comparison_object.new_record?)
+ comparison_object.instance_of?(self.class) &&
+ id.present? &&
+ comparison_object.id == id
end
# Delegates to ==
def eql?(comparison_object)
- self == (comparison_object)
+ self == comparison_object
end
# Delegates to id in order to allow two records of the same type and id to work with something like:
@@ -1605,11 +1674,42 @@ MSG
@attributes.frozen?
end
- # Returns duplicated record with unfreezed attributes.
- def dup
- obj = super
- obj.instance_variable_set('@attributes', @attributes.dup)
- obj
+ # Backport dup from 1.9 so that initialize_dup() gets called
+ unless Object.respond_to?(:initialize_dup)
+ def dup # :nodoc:
+ copy = super
+ copy.initialize_dup(self)
+ copy
+ end
+ end
+
+ # 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)
+ cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
+ cloned_attributes.delete(self.class.primary_key)
+
+ @attributes = cloned_attributes
+
+ _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks)
+
+ @changed_attributes = {}
+ attributes_from_column_definition.each do |attr, orig_value|
+ @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr])
+ end
+
+ @aggregation_cache = {}
+ @association_cache = {}
+ @attributes_cache = {}
+ @new_record = true
+
+ ensure_proper_type
+ populate_with_current_scope_attributes
+ clear_timestamp_attributes
end
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
@@ -1626,7 +1726,7 @@ MSG
# Returns the contents of the record as a nicely formatted string.
def inspect
attributes_as_nice_string = self.class.column_names.collect { |name|
- if has_attribute?(name) || new_record?
+ if has_attribute?(name)
"#{name}: #{attribute_for_inspect(name)}"
end
}.compact.join(", ")
@@ -1650,10 +1750,17 @@ MSG
private
- # Sets the attribute used for single table inheritance to this class name if this is not the
+ def set_serialized_attributes
+ (@attributes.keys & self.class.serialized_attributes.keys).each do |key|
+ coder = self.class.serialized_attributes[key]
+ @attributes[key] = coder.load @attributes[key]
+ end
+ end
+
+ # Sets the attribute used for single table inheritance to this class name if this is not the
# ActiveRecord::Base descendant.
- # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
- # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
+ # 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
unless self.class.descends_from_active_record?
@@ -1671,17 +1778,25 @@ MSG
# Returns a copy of the attributes hash where all the values have been safely quoted for use in
# an Arel insert/update method.
def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
- attrs = {}
+ attrs = {}
+ klass = self.class
+ arel_table = klass.arel_table
+
attribute_names.each do |name|
if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))
- value = read_attribute(name)
- if value && ((self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time))) || value.is_a?(Hash) || value.is_a?(Array))
- value = value.to_yaml
- end
- attrs[self.class.arel_table[name]] = value
+ value = if coder = klass.serialized_attributes[name]
+ coder.dump @attributes[name]
+ else
+ # FIXME: we need @attributes to be used consistently.
+ # If the values stored in @attributes were already type
+ # casted, this code could be simplified
+ read_attribute(name)
+ end
+
+ attrs[arel_table[name]] = value
end
end
end
@@ -1693,18 +1808,12 @@ MSG
self.class.connection.quote(value, column)
end
- # Interpolate custom SQL string in instance context.
- # Optional record argument is meant for custom insert_sql.
- def interpolate_sql(sql, record = nil)
- instance_eval("%@#{sql.gsub('@', '\@')}@", __FILE__, __LINE__)
- end
-
# Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
# by calling new on the column type or aggregation type (through composed_of) object with these parameters.
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
# 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,
- # f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the
+ # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum,
+ # f for Float, s for String, and a for Array. 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(
@@ -1727,7 +1836,7 @@ MSG
klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass
# in order to allow a date to be set without a year, we must keep the empty values.
# Otherwise, we wouldn't be able to distinguish it from a date with an empty day.
- values = values_with_empty_parameters.reject(&:nil?)
+ values = values_with_empty_parameters.reject { |v| v.nil? }
if values.empty?
send(name + "=", nil)
@@ -1786,10 +1895,7 @@ MSG
end
def quote_columns(quoter, hash)
- hash.inject({}) do |quoted, (name, value)|
- quoted[quoter.quote_column_name(name)] = value
- quoted
- end
+ Hash[hash.map { |name, value| [quoter.quote_column_name(name), value] }]
end
def quoted_comma_pair_list(quoter, hash)
@@ -1808,9 +1914,21 @@ MSG
end
end
- def object_from_yaml(string)
- return string unless string.is_a?(String) && string =~ /^---/
- YAML::load(string) rescue string
+ def populate_with_current_scope_attributes
+ if scope = self.class.send(:current_scoped_methods)
+ create_with = scope.scope_for_create
+ create_with.each { |att,value|
+ respond_to?("#{att}=") && send("#{att}=", value)
+ }
+ end
+ end
+
+ # Clear attributes and changed_attributes
+ def clear_timestamp_attributes
+ all_timestamp_attributes_in_model.each do |attribute_name|
+ self[attribute_name] = nil
+ changed_attributes.delete(attribute_name)
+ end
end
end
@@ -1832,7 +1950,9 @@ MSG
include AttributeMethods::Dirty
include ActiveModel::MassAssignmentSecurity
include Callbacks, ActiveModel::Observing, Timestamp
- include Associations, AssociationPreload, NamedScope
+ include Associations, NamedScope
+ include IdentityMap
+ include ActiveModel::SecurePassword
# AutosaveAssociation needs to be included before Transactions, because we want
# #save_with_autosave_associations to be wrapped inside a transaction.
@@ -1840,6 +1960,17 @@ MSG
include Aggregations, Transactions, Reflection, Serialization
NilClass.add_whiner(self) if NilClass.respond_to?(:add_whiner)
+
+ # 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)).
+ # (Alias for the protected read_attribute method).
+ alias [] read_attribute
+
+ # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
+ # (Alias for the protected write_attribute method).
+ alias []= write_attribute
+
+ public :[], :[]=
end
end
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index aa92bf999f..86d58df99b 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -2,8 +2,8 @@ require 'active_support/core_ext/array/wrap'
module ActiveRecord
# = Active Record Callbacks
- #
- # Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic
+ #
+ # 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
@@ -25,9 +25,13 @@ module ActiveRecord
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
# <tt>after_rollback</tt>.
#
- # That's a total of ten callbacks, which gives you immense power to react and prepare for each state in the
- # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
- # except that each <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
+ # 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
@@ -55,8 +59,8 @@ module ActiveRecord
#
# == 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
+ # 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
@@ -67,9 +71,9 @@ module ActiveRecord
# 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+ methis is overriden:
+ # 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
@@ -79,20 +83,20 @@ module ActiveRecord
# 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 overwriteable methods when you want to leave it up to each descendant
+ # 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 overwriteable 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
+ # *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
+ # 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:
@@ -170,14 +174,14 @@ module ActiveRecord
# end
# end
#
- # The callback macros usually accept a symbol for the method they're supposed to run, but you can also
+ # 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
+ # 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
@@ -185,25 +189,17 @@ module ActiveRecord
# 'puts "Evaluated after parents are destroyed"'
# end
#
- # == The +after_find+ and +after_initialize+ exceptions
- #
- # Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder,
- # such as <tt>Base.find(:all)</tt>, we've had to implement a simple performance constraint (50% more speed
- # on a simple test case). Unlike all the other callbacks, +after_find+ and +after_initialize+ will only be
- # run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the
- # callback types will be called.
- #
# == <tt>before_validation*</tt> returning statements
#
- # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
- # aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
+ # 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
+ # 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.
#
# == Transactions
@@ -218,16 +214,6 @@ module ActiveRecord
# needs to be aware of it because an ordinary +save+ will raise such exception
# instead of quietly returning +false+.
#
- # == Debugging callbacks
- #
- # To list the methods and procs registered with a particular callback, append <tt>_callback_chain</tt> to
- # the callback name that you wish to list and send that to your class from the Rails console:
- #
- # >> Topic.after_save_callback_chain
- # => [#<ActiveSupport::Callbacks::Callback:0x3f6a448
- # @method=#<Proc:0x03f9a42c@/Users/foo/bar/app/models/topic.rb:43>, kind:after_save, identifiernil,
- # options{}]
- #
module Callbacks
extend ActiveSupport::Concern
@@ -235,7 +221,7 @@ module ActiveRecord
: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
+ :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
]
included do
@@ -246,43 +232,26 @@ module ActiveRecord
define_model_callbacks :save, :create, :update, :destroy
end
- module ClassMethods
- def method_added(meth)
- super
- if CALLBACKS.include?(meth.to_sym)
- ActiveSupport::Deprecation.warn("Base##{meth} has been deprecated, please use Base.#{meth} :method instead", caller[0,1])
- send(meth.to_sym, meth.to_sym)
- end
- end
- end
-
def destroy #:nodoc:
- _run_destroy_callbacks { super }
+ run_callbacks(:destroy) { super }
end
def touch(*) #:nodoc:
- _run_touch_callbacks { super }
- end
-
- def deprecated_callback_method(symbol) #:nodoc:
- if respond_to?(symbol, true)
- ActiveSupport::Deprecation.warn("Overwriting #{symbol} in your models has been deprecated, please use Base##{symbol} :method_name instead")
- send(symbol)
- end
+ run_callbacks(:touch) { super }
end
private
def create_or_update #:nodoc:
- _run_save_callbacks { super }
+ run_callbacks(:save) { super }
end
def create #:nodoc:
- _run_create_callbacks { super }
+ run_callbacks(:create) { super }
end
def update(*) #:nodoc:
- _run_update_callbacks { super }
+ run_callbacks(:update) { super }
end
end
end
diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb
new file mode 100644
index 0000000000..fb59d9fb07
--- /dev/null
+++ b/activerecord/lib/active_record/coders/yaml_column.rb
@@ -0,0 +1,41 @@
+module ActiveRecord
+ # :stopdoc:
+ module Coders
+ class YAMLColumn
+ RESCUE_ERRORS = [ ArgumentError ]
+
+ if defined?(Psych) && defined?(Psych::SyntaxError)
+ RESCUE_ERRORS << Psych::SyntaxError
+ end
+
+ attr_accessor :object_class
+
+ def initialize(object_class = Object)
+ @object_class = object_class
+ end
+
+ def dump(obj)
+ YAML.dump obj
+ end
+
+ def load(yaml)
+ return object_class.new if object_class != Object && yaml.nil?
+ return yaml unless yaml.is_a?(String) && yaml =~ /^---/
+ begin
+ obj = YAML.load(yaml)
+
+ unless obj.is_a?(object_class) || obj.nil?
+ raise SerializationTypeMismatch,
+ "Attribute was supposed to be a #{object_class}, but was a #{obj.class}"
+ end
+ obj ||= object_class.new if object_class != Object
+
+ obj
+ rescue *RESCUE_ERRORS
+ yaml
+ end
+ end
+ end
+ end
+ # :startdoc
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index 02a8f4e214..4297c26413 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -1,3 +1,4 @@
+require 'thread'
require 'monitor'
require 'set'
require 'active_support/core_ext/module/synchronization'
@@ -56,7 +57,9 @@ module ActiveRecord
# * +wait_timeout+: number of seconds to block and wait for a connection
# before giving up and raising a timeout error (default 5 seconds).
class ConnectionPool
+ attr_accessor :automatic_reconnect
attr_reader :spec, :connections
+ attr_reader :columns, :columns_hash, :primary_keys, :tables
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
# object which describes database connection information (e.g. adapter,
@@ -73,18 +76,70 @@ module ActiveRecord
# The mutex used to synchronize pool access
@connection_mutex = Monitor.new
@queue = @connection_mutex.new_cond
-
- # default 5 second timeout unless on ruby 1.9
- @timeout =
- if RUBY_VERSION < '1.9'
- spec.config[:wait_timeout] || 5
- end
+ @timeout = spec.config[:wait_timeout] || 5
# default max pool size to 5
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
@connections = []
@checked_out = []
+ @automatic_reconnect = true
+ @tables = {}
+
+ @columns = Hash.new do |h, table_name|
+ h[table_name] = with_connection do |conn|
+
+ # Fetch a list of columns
+ conn.columns(table_name, "#{table_name} Columns").tap do |columns|
+
+ # set primary key information
+ columns.each do |column|
+ column.primary = column.name == primary_keys[table_name]
+ end
+ end
+ end
+ end
+
+ @columns_hash = Hash.new do |h, table_name|
+ h[table_name] = Hash[columns[table_name].map { |col|
+ [col.name, col]
+ }]
+ end
+
+ @primary_keys = Hash.new do |h, table_name|
+ h[table_name] = with_connection do |conn|
+ table_exists?(table_name) ? conn.primary_key(table_name) : 'id'
+ end
+ end
+ end
+
+ # A cached lookup for table existence
+ def table_exists?(name)
+ return true if @tables.key? name
+
+ with_connection do |conn|
+ conn.tables.each { |table| @tables[table] = true }
+ end
+
+ @tables.key? name
+ end
+
+ # Clears out internal caches:
+ #
+ # * columns
+ # * columns_hash
+ # * tables
+ def clear_cache!
+ @columns.clear
+ @columns_hash.clear
+ @tables.clear
+ end
+
+ # Clear out internal caches for table with +table_name+
+ def clear_table_cache!(table_name)
+ @columns.delete table_name
+ @columns_hash.delete table_name
+ @primary_keys.delete table_name
end
# Retrieve the connection associated with the current thread, or call
@@ -93,11 +148,7 @@ module ActiveRecord
# #connection can be called any number of times; the connection is
# held in a hash keyed by the thread id.
def connection
- if conn = @reserved_connections[current_connection_id]
- conn
- else
- @reserved_connections[current_connection_id] = checkout
- end
+ @reserved_connections[current_connection_id] ||= checkout
end
# Signal that the thread is finished with the current connection.
@@ -109,7 +160,7 @@ module ActiveRecord
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
+ # exists checkout a connection, yield it to the block, and checkin the
# connection when finished.
def with_connection
connection_id = current_connection_id
@@ -165,7 +216,6 @@ module ActiveRecord
keys = @reserved_connections.keys - Thread.list.find_all { |t|
t.alive?
}.map { |thread| thread.object_id }
-
keys.each do |key|
checkin @reserved_connections[key]
@reserved_connections.delete(key)
@@ -198,16 +248,18 @@ module ActiveRecord
checkout_new_connection
end
return conn if conn
- # No connections available; wait for one
- if @queue.wait(@timeout)
+
+ @queue.wait(@timeout)
+
+ if(@checked_out.size < @connections.size)
next
else
- # try looting dead threads
clear_stale_cached_connections!
if @size == @checked_out.size
raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it."
end
end
+
end
end
end
@@ -219,7 +271,7 @@ module ActiveRecord
# calling +checkout+ on this pool.
def checkin(conn)
@connection_mutex.synchronize do
- conn.send(:_run_checkin_callbacks) do
+ conn.run_callbacks :checkin do
@checked_out.delete conn
@queue.signal
end
@@ -239,6 +291,8 @@ module ActiveRecord
end
def checkout_new_connection
+ raise ConnectionNotEstablished unless @automatic_reconnect
+
c = new_connection
@connections << c
checkout_and_verify(c)
@@ -326,7 +380,7 @@ module ActiveRecord
# already been opened.
def connected?(klass)
conn = retrieve_connection_pool(klass)
- conn ? conn.connected? : false
+ conn && conn.connected?
end
# Remove the connection for this class. This will close the active
@@ -337,7 +391,7 @@ module ActiveRecord
pool = @connection_pools[klass.name]
return nil unless pool
- @connection_pools.delete_if { |key, value| value == pool }
+ pool.automatic_reconnect = false
pool.disconnect!
pool.spec.config
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
index 8e74eff0ab..d88720c8bf 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
@@ -67,12 +67,12 @@ module ActiveRecord
begin
require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
- rescue LoadError
- raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{$!})"
+ rescue LoadError => e
+ raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e})"
end
adapter_method = "#{spec[:adapter]}_connection"
- if !respond_to?(adapter_method)
+ unless respond_to?(adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
end
@@ -89,6 +89,16 @@ module ActiveRecord
retrieve_connection
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)
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
index a130c330dd..29ac9341ec 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb
@@ -37,9 +37,9 @@ module ActiveRecord
16
end
- # the maximum number of elements in an IN (x,y,z) clause
+ # the maximum number of elements in an IN (x,y,z) clause. nil means no limit
def in_clause_length
- 65535
+ nil
end
# the maximum length of an SQL query
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index 25432e9985..a3082b8f01 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -1,10 +1,20 @@
+require 'active_support/core_ext/module/deprecation'
+
module ActiveRecord
module ConnectionAdapters # :nodoc:
module DatabaseStatements
# Returns an array of record hashes with the column names as keys and
# column values as values.
- def select_all(sql, name = nil)
- select(sql, name)
+ def select_all(sql, name = nil, binds = [])
+ if supports_statement_cache?
+ select(sql, name, binds)
+ else
+ return select(sql, name) if binds.empty?
+ binds = binds.dup
+ select sql.gsub('?') {
+ quote(*binds.shift.reverse)
+ }, name
+ end
end
# Returns a record hash with the column names as keys and column values
@@ -35,10 +45,16 @@ module ActiveRecord
undef_method :select_rows
# Executes the SQL statement in the context of this connection.
- def execute(sql, name = nil, skip_logging = false)
+ 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
+
# Returns the last auto-generated ID from the affected table.
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
insert_sql(sql, name, pk, id_value, sequence_name)
@@ -68,6 +84,12 @@ module ActiveRecord
nil
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.
#
@@ -209,11 +231,12 @@ module ActiveRecord
#
# This method *modifies* the +sql+ parameter.
#
+ # This method is deprecated!! Stop using it!
+ #
# ===== Examples
# add_limit_offset!('SELECT * FROM suppliers', {:limit => 10, :offset => 50})
# generates
# SELECT * FROM suppliers LIMIT 10 OFFSET 50
-
def add_limit_offset!(sql, options)
if limit = options[:limit]
sql << " LIMIT #{sanitize_limit(limit)}"
@@ -223,6 +246,7 @@ module ActiveRecord
end
sql
end
+ deprecate :add_limit_offset!
def default_sequence_name(table, column)
nil
@@ -236,7 +260,19 @@ module ActiveRecord
# Inserts the given fixture into the table. Overridden in adapters that require
# something beyond a simple insert (eg. Oracle).
def insert_fixture(fixture, table_name)
- execute "INSERT INTO #{quote_table_name(table_name)} (#{fixture.key_list}) VALUES (#{fixture.value_list})", 'Fixture Insert'
+ columns = Hash[columns(table_name).map { |c| [c.name, c] }]
+
+ key_list = []
+ value_list = fixture.map do |name, value|
+ key_list << quote_column_name(name)
+ quote(value, columns[name])
+ end
+
+ execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
+ end
+
+ def null_insert_value
+ Arel.sql 'DEFAULT'
end
def empty_insert_statement_value
@@ -251,10 +287,29 @@ module ActiveRecord
"WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
end
+ # Sanitizes the given LIMIT parameter in order to prevent SQL injection.
+ #
+ # The +limit+ may be anything that can evaluate to a string via #to_s. It
+ # should look like an integer, or a comma-delimited list of integers, or
+ # an Arel SQL literal.
+ #
+ # Returns Integer and Arel::Nodes::SqlLiteral limits as is.
+ # Returns the sanitized limit parameter, either as an integer, or as a
+ # string which contains a comma-delimited list of integers.
+ def sanitize_limit(limit)
+ if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
+ limit
+ elsif limit.to_s =~ /,/
+ Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
+ else
+ Integer(limit)
+ end
+ end
+
protected
# Returns an array of record hashes with the column names as keys and
# column values as values.
- def select(sql, name = nil)
+ def select(sql, name = nil, binds = [])
end
undef_method :select
@@ -274,21 +329,6 @@ module ActiveRecord
update_sql(sql, name)
end
- # Sanitizes the given LIMIT parameter in order to prevent SQL injection.
- #
- # +limit+ may be anything that can evaluate to a string via #to_s. It
- # should look like an integer, or a comma-delimited list of integers.
- #
- # Returns the sanitized limit parameter, either as an integer, or as a
- # string which contains a comma-delimited list of integers.
- def sanitize_limit(limit)
- if limit.to_s =~ /,/
- limit.to_s.split(',').map{ |i| i.to_i }.join(',')
- else
- limit.to_i
- end
- end
-
# Send a rollback message to all records after they have been rolled back. If rollback
# is false, only rollback records since the last save point.
def rollback_transaction_records(rollback) #:nodoc
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
index 78fffaff6e..1db397f584 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/object/duplicable'
-
module ActiveRecord
module ConnectionAdapters # :nodoc:
module QueryCache
@@ -49,40 +47,26 @@ module ActiveRecord
@query_cache.clear
end
- def select_all(*args)
- if @query_cache_enabled
- cache_sql(args.first) { super }
- else
- super
- end
- end
-
- def columns(*)
+ def select_all(sql, name = nil, binds = [])
if @query_cache_enabled
- @query_cache["SHOW FIELDS FROM #{args.first}"] ||= super
+ cache_sql(sql, binds) { super }
else
super
end
end
private
- def cache_sql(sql)
+ def cache_sql(sql, binds)
result =
- if @query_cache.has_key?(sql)
+ if @query_cache[sql].key?(binds)
ActiveSupport::Notifications.instrument("sql.active_record",
- :sql => sql, :name => "CACHE", :connection_id => self.object_id)
- @query_cache[sql]
+ :sql => sql, :name => "CACHE", :connection_id => object_id)
+ @query_cache[sql][binds]
else
- @query_cache[sql] = yield
+ @query_cache[sql][binds] = yield
end
- if Array === result
- result.collect { |row| row.dup }
- else
- result.duplicable? ? result.dup : result
- end
- rescue TypeError
- result
+ result.collect { |row| row.dup }
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
index e2b3773a99..7489e88eef 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -10,28 +10,32 @@ module ActiveRecord
return value.quoted_id if value.respond_to?(:quoted_id)
case value
- when String, ActiveSupport::Multibyte::Chars
- value = value.to_s
- if column && column.type == :binary && column.class.respond_to?(:string_to_binary)
- "'#{quote_string(column.class.string_to_binary(value))}'" # ' (for ruby-mode)
- elsif column && [:integer, :float].include?(column.type)
- value = column.type == :integer ? value.to_i : value.to_f
- value.to_s
- else
- "'#{quote_string(value)}'" # ' (for ruby-mode)
- end
- when NilClass then "NULL"
- when TrueClass then (column && column.type == :integer ? '1' : quoted_true)
- when FalseClass then (column && column.type == :integer ? '0' : quoted_false)
- when Float, Fixnum, Bignum then value.to_s
- # BigDecimals need to be output in a non-normalized form and quoted.
- when BigDecimal then value.to_s('F')
+ 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
- if value.acts_like?(:date) || value.acts_like?(:time)
- "'#{quoted_date(value)}'"
- else
- "'#{quote_string(value.to_s)}'"
- end
+ 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 then value.to_s
+ when Date, Time then "'#{quoted_date(value)}'"
+ when Symbol then "'#{quote_string(value.to_s)}'"
+ else
+ "'#{quote_string(value.to_yaml)}'"
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index 9118ceb33c..7ac48c6646 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -6,259 +6,6 @@ require 'bigdecimal/util'
module ActiveRecord
module ConnectionAdapters #:nodoc:
- # An abstract definition of a column in a table.
- class Column
- TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
- FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
-
- module Format
- ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
- ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
- end
-
- attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
- attr_accessor :primary
-
- # Instantiates a new column in the table.
- #
- # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
- # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
- # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
- # <tt>company_name varchar(60)</tt>.
- # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
- # +null+ determines if this column allows +NULL+ values.
- def initialize(name, default, sql_type = nil, null = true)
- @name, @sql_type, @null = name, sql_type, null
- @limit, @precision, @scale = extract_limit(sql_type), extract_precision(sql_type), extract_scale(sql_type)
- @type = simplified_type(sql_type)
- @default = extract_default(default)
-
- @primary = nil
- end
-
- # Returns +true+ if the column is either of type string or text.
- def text?
- type == :string || type == :text
- end
-
- # Returns +true+ if the column is either of type integer, float or decimal.
- def number?
- type == :integer || type == :float || type == :decimal
- end
-
- def has_default?
- !default.nil?
- end
-
- # Returns the Ruby class that corresponds to the abstract data type.
- def klass
- case type
- when :integer then Fixnum
- when :float then Float
- when :decimal then BigDecimal
- when :datetime then Time
- when :date then Date
- when :timestamp then Time
- when :time then Time
- when :text, :string then String
- when :binary then String
- when :boolean then Object
- end
- end
-
- # Casts value (which is a String) to an appropriate instance.
- def type_cast(value)
- return nil if value.nil?
- case type
- when :string then value
- when :text then value
- when :integer then value.to_i rescue value ? 1 : 0
- when :float then value.to_f
- when :decimal then self.class.value_to_decimal(value)
- when :datetime then self.class.string_to_time(value)
- when :timestamp then self.class.string_to_time(value)
- when :time then self.class.string_to_dummy_time(value)
- when :date then self.class.string_to_date(value)
- when :binary then self.class.binary_to_string(value)
- when :boolean then self.class.value_to_boolean(value)
- else value
- end
- end
-
- def type_cast_code(var_name)
- case type
- when :string then nil
- when :text then nil
- when :integer then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
- when :float then "#{var_name}.to_f"
- when :decimal then "#{self.class.name}.value_to_decimal(#{var_name})"
- when :datetime then "#{self.class.name}.string_to_time(#{var_name})"
- when :timestamp then "#{self.class.name}.string_to_time(#{var_name})"
- when :time then "#{self.class.name}.string_to_dummy_time(#{var_name})"
- when :date then "#{self.class.name}.string_to_date(#{var_name})"
- when :binary then "#{self.class.name}.binary_to_string(#{var_name})"
- when :boolean then "#{self.class.name}.value_to_boolean(#{var_name})"
- else nil
- end
- end
-
- # Returns the human name of the column name.
- #
- # ===== Examples
- # Column.new('sales_stage', ...).human_name # => 'Sales stage'
- def human_name
- Base.human_attribute_name(@name)
- end
-
- def extract_default(default)
- type_cast(default)
- end
-
- class << self
- # Used to convert from Strings to BLOBs
- def string_to_binary(value)
- value
- end
-
- # Used to convert from BLOBs to Strings
- def binary_to_string(value)
- value
- end
-
- def string_to_date(string)
- return string unless string.is_a?(String)
- return nil if string.empty?
-
- fast_string_to_date(string) || fallback_string_to_date(string)
- end
-
- def string_to_time(string)
- return string unless string.is_a?(String)
- return nil if string.empty?
-
- fast_string_to_time(string) || fallback_string_to_time(string)
- end
-
- def string_to_dummy_time(string)
- return string unless string.is_a?(String)
- return nil if string.empty?
-
- string_to_time "2000-01-01 #{string}"
- end
-
- # convert something to a boolean
- def value_to_boolean(value)
- if value.is_a?(String) && value.blank?
- nil
- else
- TRUE_VALUES.include?(value)
- end
- end
-
- # convert something to a BigDecimal
- def value_to_decimal(value)
- # Using .class is faster than .is_a? and
- # subclasses of BigDecimal will be handled
- # in the else clause
- if value.class == BigDecimal
- value
- elsif value.respond_to?(:to_d)
- value.to_d
- else
- value.to_s.to_d
- end
- end
-
- protected
- # '0.123456' -> 123456
- # '1.123456' -> 123456
- def microseconds(time)
- ((time[:sec_fraction].to_f % 1) * 1_000_000).to_i
- end
-
- def new_date(year, mon, mday)
- if year && year != 0
- Date.new(year, mon, mday) rescue nil
- end
- end
-
- def new_time(year, mon, mday, hour, min, sec, microsec)
- # Treat 0000-00-00 00:00:00 as nil.
- return nil if year.nil? || year == 0
-
- Time.time_with_datetime_fallback(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
- end
-
- def fast_string_to_date(string)
- if string =~ Format::ISO_DATE
- new_date $1.to_i, $2.to_i, $3.to_i
- end
- end
-
- # Doesn't handle time zones.
- def fast_string_to_time(string)
- if string =~ Format::ISO_DATETIME
- microsec = ($7.to_f * 1_000_000).to_i
- new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
- end
- end
-
- def fallback_string_to_date(string)
- new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
- end
-
- def fallback_string_to_time(string)
- time_hash = Date._parse(string)
- time_hash[:sec_fraction] = microseconds(time_hash)
-
- new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
- end
- end
-
- private
- def extract_limit(sql_type)
- $1.to_i if sql_type =~ /\((.*)\)/
- end
-
- def extract_precision(sql_type)
- $2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
- end
-
- def extract_scale(sql_type)
- case sql_type
- when /^(numeric|decimal|number)\((\d+)\)/i then 0
- when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
- end
- end
-
- def simplified_type(field_type)
- case field_type
- when /int/i
- :integer
- when /float|double/i
- :float
- when /decimal|numeric|number/i
- extract_scale(field_type) == 0 ? :integer : :decimal
- when /datetime/i
- :datetime
- when /timestamp/i
- :timestamp
- when /time/i
- :time
- when /date/i
- :date
- when /clob/i, /text/i
- :text
- when /blob/i, /binary/i
- :binary
- when /char/i, /string/i
- :string
- when /boolean/i
- :boolean
- end
- end
- end
-
class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc:
end
@@ -268,6 +15,10 @@ module ActiveRecord
# for generating a number of table creation or table changing SQL statements.
class ColumnDefinition < Struct.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
+ def string_to_binary(value)
+ value
+ end
+
def sql_type
base.type_to_sql(type.to_sym, limit, precision, scale) rescue type
end
@@ -318,21 +69,13 @@ module ActiveRecord
@base = base
end
- #Handles non supported datatypes - e.g. XML
- def method_missing(symbol, *args)
- if symbol.to_s == 'xml'
- xml_column_fallback(args)
- else
- super
- end
- end
+ def xml(*args)
+ raise NotImplementedError unless %w{
+ sqlite mysql mysql2
+ }.include? @base.adapter_name.downcase
- def xml_column_fallback(*args)
- case @base.adapter_name.downcase
- when 'sqlite', 'mysql'
- options = args.extract_options!
- column(args[0], :text, options)
- end
+ options = args.extract_options!
+ column(args[0], :text, options)
end
# Appends a primary key definition to the table definition.
@@ -360,7 +103,7 @@ module ActiveRecord
#
# 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
+ # Requests a maximum column length. This is number of characters for <tt>:string</tt> and
# <tt>:text</tt> columns and number of bytes for :binary and :integer columns.
# * <tt>:default</tt> -
# The column's default value. Use nil for NULL.
@@ -464,7 +207,7 @@ module ActiveRecord
# 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
+ # 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. So what can be written like this:
#
# create_table :taggings do |t|
@@ -528,7 +271,7 @@ module ActiveRecord
# concatenated together. This string can then be prepended and appended to
# to generate the final SQL to create the table.
def to_sql
- @columns.map(&:to_sql) * ', '
+ @columns.map { |c| c.to_sql } * ', '
end
private
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index 7dee68502f..8bae50885f 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -12,7 +12,7 @@ module ActiveRecord
# Truncates a table alias according to the limits of the current adapter.
def table_alias_for(table_name)
- table_name[0..table_alias_length-1].gsub(/\./, '_')
+ table_name[0...table_alias_length].gsub(/\./, '_')
end
# def tables(name = nil) end
@@ -110,8 +110,8 @@ module ActiveRecord
#
# Also note that this just sets the primary key in the table. You additionally
# need to configure the primary key in the model via the +set_primary_key+ macro.
- # Models do NOT auto-detect the primary key from their table definition.
- #
+ # 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>]
@@ -151,10 +151,10 @@ module ActiveRecord
#
# See also TableDefinition#column for details on how to create columns.
def create_table(table_name, options = {})
- table_definition = TableDefinition.new(self)
- table_definition.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false
+ td = table_definition
+ td.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false
- yield table_definition if block_given?
+ yield td if block_given?
if options[:force] && table_exists?(table_name)
drop_table(table_name, options)
@@ -162,7 +162,7 @@ module ActiveRecord
create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE "
create_sql << "#{quote_table_name(table_name)} ("
- create_sql << table_definition.to_sql
+ create_sql << td.to_sql
create_sql << ") #{options[:options]}"
execute create_sql
end
@@ -176,6 +176,13 @@ module ActiveRecord
# # Other column alterations here
# end
#
+ # The +options+ hash can include the following keys:
+ # [<tt>:bulk</tt>]
+ # Set this to true to make this a bulk alter query, such as
+ # ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
+ #
+ # Defaults to false.
+ #
# ===== Examples
# ====== Add a column
# change_table(:suppliers) do |t|
@@ -224,8 +231,14 @@ module ActiveRecord
#
# See also Table for details on
# all of the various column transformation
- def change_table(table_name)
- yield Table.new(table_name, self)
+ def change_table(table_name, options = {})
+ if supports_bulk_alter? && options[:bulk]
+ recorder = ActiveRecord::Migration::CommandRecorder.new(self)
+ yield Table.new(table_name, recorder)
+ bulk_change_table(table_name, recorder.commands)
+ else
+ yield Table.new(table_name, self)
+ end
end
# Renames a table.
@@ -253,10 +266,7 @@ module ActiveRecord
# remove_column(:suppliers, :qualification)
# remove_columns(:suppliers, :qualification, :experience)
def remove_column(table_name, *column_names)
- raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.empty?
- column_names.flatten.each do |column_name|
- execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{quote_column_name(column_name)}"
- end
+ columns_for_remove(table_name, *column_names).each {|column_name| execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{column_name}" }
end
alias :remove_columns :remove_column
@@ -269,12 +279,11 @@ module ActiveRecord
raise NotImplementedError, "change_column is not implemented"
end
- # Sets a new default value for a column. If you want to set the default
- # value to +NULL+, you are out of luck. You need to
- # DatabaseStatements#execute the appropriate SQL statement yourself.
+ # Sets a new default value for a column.
# ===== Examples
# change_column_default(:suppliers, :qualification, 'new')
# change_column_default(:accounts, :authorized, 1)
+ # change_column_default(:users, :email, nil)
def change_column_default(table_name, column_name, default)
raise NotImplementedError, "change_column_default is not implemented"
end
@@ -327,29 +336,8 @@ module ActiveRecord
#
# Note: SQLite doesn't support index length
def add_index(table_name, column_name, options = {})
- options[:name] = options[:name].to_s if options.key?(:name)
-
- column_names = Array.wrap(column_name)
- index_name = index_name(table_name, :column => column_names)
-
- if Hash === options # legacy support, since this param was a string
- index_type = options[:unique] ? "UNIQUE" : ""
- index_name = options[:name] || index_name
- else
- index_type = options
- end
-
- if index_name.length > index_name_length
- @logger.warn("Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters. Skipping.")
- return
- end
- if index_name_exists?(table_name, index_name, false)
- @logger.warn("Index name '#{index_name}' on table '#{table_name}' already exists. Skipping.")
- return
- end
- quoted_column_names = quoted_columns_for_index(column_names, options).join(", ")
-
- execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{quoted_column_names})"
+ index_name, index_type, index_columns = add_index_options(table_name, column_name, options)
+ execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})"
end
# Remove the given index from the table.
@@ -363,12 +351,7 @@ module ActiveRecord
# Remove the index named by_branch_party in the accounts table.
# remove_index :accounts, :name => :by_branch_party
def remove_index(table_name, options = {})
- index_name = index_name(table_name, options)
- unless index_name_exists?(table_name, index_name, true)
- @logger.warn("Index name '#{index_name}' on table '#{table_name}' does not exist. Skipping.")
- return
- end
- remove_index!(table_name, index_name)
+ remove_index!(table_name, index_name_for_remove(table_name, options))
end
def remove_index!(table_name, index_name) #:nodoc:
@@ -407,6 +390,7 @@ module ActiveRecord
# 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
@@ -446,12 +430,14 @@ module ActiveRecord
end
end
- def assume_migrated_upto_version(version, migrations_path = ActiveRecord::Migrator.migrations_path)
+ def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
+ migrations_paths = Array.wrap(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(&:to_i)
- versions = Dir["#{migrations_path}/[0-9]*_*.rb"].map do |filename|
+ 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
@@ -471,7 +457,7 @@ module ActiveRecord
end
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
- if native = native_database_types[type]
+ if native = native_database_types[type.to_sym]
column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
if type == :decimal # ignore limit, use precision and scale
@@ -538,6 +524,50 @@ module ActiveRecord
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.wrap(column_name)
+ index_name = index_name(table_name, :column => column_names)
+
+ if Hash === options # legacy support, since this param was a string
+ index_type = options[:unique] ? "UNIQUE" : ""
+ index_name = options[:name].to_s if options.key?(:name)
+ else
+ index_type = options
+ end
+
+ if index_name.length > index_name_length
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters"
+ end
+ if index_name_exists?(table_name, index_name, false)
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
+ end
+ index_columns = quoted_columns_for_index(column_names, options).join(", ")
+
+ [index_name, index_type, index_columns]
+ end
+
+ def index_name_for_remove(table_name, options = {})
+ index_name = index_name(table_name, options)
+
+ unless index_name_exists?(table_name, index_name, true)
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
+ end
+
+ index_name
+ end
+
+ def columns_for_remove(table_name, *column_names)
+ column_names = column_names.flatten
+
+ raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.blank?
+ column_names.map {|column_name| quote_column_name(column_name) }
+ end
+
+ private
+ def table_definition
+ TableDefinition.new(self)
+ 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
index d8c92d0ad3..0f44baa2fe 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -4,6 +4,7 @@ require 'bigdecimal/util'
require 'active_support/core_ext/benchmark'
# TODO: Autoload these files
+require 'active_record/connection_adapters/column'
require 'active_record/connection_adapters/abstract/schema_definitions'
require 'active_record/connection_adapters/abstract/schema_statements'
require 'active_record/connection_adapters/abstract/database_statements'
@@ -12,6 +13,7 @@ require 'active_record/connection_adapters/abstract/connection_pool'
require 'active_record/connection_adapters/abstract/connection_specification'
require 'active_record/connection_adapters/abstract/query_cache'
require 'active_record/connection_adapters/abstract/database_limits'
+require 'active_record/result'
module ActiveRecord
module ConnectionAdapters # :nodoc:
@@ -40,7 +42,7 @@ module ActiveRecord
@active = nil
@connection, @logger = connection, logger
@query_cache_enabled = false
- @query_cache = {}
+ @query_cache = Hash.new { |h,sql| h[sql] = {} }
@instrumenter = ActiveSupport::Notifications.instrumenter
end
@@ -76,8 +78,12 @@ module ActiveRecord
false
end
- # Does this adapter support savepoints? PostgreSQL and MySQL do, SQLite
- # does not.
+ def supports_bulk_alter?
+ false
+ end
+
+ # Does this adapter support savepoints? PostgreSQL and MySQL do,
+ # SQLite < 3.6.8 does not.
def supports_savepoints?
false
end
@@ -97,6 +103,12 @@ module ActiveRecord
quote_column_name(name)
end
+ # Returns a bind substitution value given a +column+ and list of current
+ # +binds+
+ def substitute_for(column, binds)
+ Arel.sql '?'
+ end
+
# REFERENTIAL INTEGRITY ====================================
# Override to turn off referential integrity while executing <tt>&block</tt>.
@@ -135,6 +147,13 @@ module ActiveRecord
# 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?
@@ -190,12 +209,13 @@ module ActiveRecord
protected
- def log(sql, name)
- name ||= "SQL"
- @instrumenter.instrument("sql.active_record",
- :sql => sql, :name => name, :connection_id => object_id) do
- yield
- end
+ def log(sql, name = "SQL", binds = [])
+ @instrumenter.instrument(
+ "sql.active_record",
+ :sql => sql,
+ :name => name,
+ :connection_id => object_id,
+ :binds => binds) { yield }
rescue Exception => e
message = "#{e.class.name}: #{e.message}: #{sql}"
@logger.debug message if @logger
diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb
new file mode 100644
index 0000000000..4e3d8a096f
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/column.rb
@@ -0,0 +1,268 @@
+module ActiveRecord
+ # :stopdoc:
+ module ConnectionAdapters
+ # An abstract definition of a column in a table.
+ class Column
+ TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
+ FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
+
+ module Format
+ ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
+ ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
+ end
+
+ attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
+ attr_accessor :primary, :coder
+
+ alias :encoded? :coder
+
+ # Instantiates a new column in the table.
+ #
+ # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
+ # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
+ # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
+ # <tt>company_name varchar(60)</tt>.
+ # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
+ # +null+ determines if this column allows +NULL+ values.
+ def initialize(name, default, sql_type = nil, null = true)
+ @name = name
+ @sql_type = sql_type
+ @null = null
+ @limit = extract_limit(sql_type)
+ @precision = extract_precision(sql_type)
+ @scale = extract_scale(sql_type)
+ @type = simplified_type(sql_type)
+ @default = extract_default(default)
+ @primary = nil
+ @coder = nil
+ end
+
+ # Returns +true+ if the column is either of type string or text.
+ def text?
+ type == :string || type == :text
+ end
+
+ # Returns +true+ if the column is either of type integer, float or decimal.
+ def number?
+ type == :integer || type == :float || type == :decimal
+ end
+
+ def has_default?
+ !default.nil?
+ end
+
+ # Returns the Ruby class that corresponds to the abstract data type.
+ def klass
+ case type
+ when :integer then Fixnum
+ when :float then Float
+ when :decimal then BigDecimal
+ when :datetime, :timestamp, :time then Time
+ when :date then Date
+ when :text, :string, :binary then String
+ when :boolean then Object
+ end
+ end
+
+ # Casts value (which is a String) to an appropriate instance.
+ def type_cast(value)
+ return nil if value.nil?
+ return coder.load(value) if encoded?
+
+ klass = self.class
+
+ case type
+ when :string, :text then value
+ when :integer then value.to_i rescue value ? 1 : 0
+ when :float then value.to_f
+ when :decimal then klass.value_to_decimal(value)
+ when :datetime, :timestamp then klass.string_to_time(value)
+ when :time then klass.string_to_dummy_time(value)
+ when :date then klass.string_to_date(value)
+ when :binary then klass.binary_to_string(value)
+ when :boolean then klass.value_to_boolean(value)
+ else value
+ end
+ end
+
+ def type_cast_code(var_name)
+ klass = self.class.name
+
+ case type
+ when :string, :text then var_name
+ when :integer then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
+ when :float then "#{var_name}.to_f"
+ when :decimal then "#{klass}.value_to_decimal(#{var_name})"
+ when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})"
+ when :time then "#{klass}.string_to_dummy_time(#{var_name})"
+ when :date then "#{klass}.string_to_date(#{var_name})"
+ when :binary then "#{klass}.binary_to_string(#{var_name})"
+ when :boolean then "#{klass}.value_to_boolean(#{var_name})"
+ else var_name
+ end
+ end
+
+ # Returns the human name of the column name.
+ #
+ # ===== Examples
+ # Column.new('sales_stage', ...).human_name # => 'Sales stage'
+ def human_name
+ Base.human_attribute_name(@name)
+ end
+
+ def extract_default(default)
+ type_cast(default)
+ end
+
+ # Used to convert from Strings to BLOBs
+ def string_to_binary(value)
+ self.class.string_to_binary(value)
+ end
+
+ class << self
+ # Used to convert from Strings to BLOBs
+ def string_to_binary(value)
+ value
+ end
+
+ # Used to convert from BLOBs to Strings
+ def binary_to_string(value)
+ value
+ end
+
+ def string_to_date(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ fast_string_to_date(string) || fallback_string_to_date(string)
+ end
+
+ def string_to_time(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ fast_string_to_time(string) || fallback_string_to_time(string)
+ end
+
+ def string_to_dummy_time(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ string_to_time "2000-01-01 #{string}"
+ end
+
+ # convert something to a boolean
+ def value_to_boolean(value)
+ if value.is_a?(String) && value.blank?
+ nil
+ else
+ TRUE_VALUES.include?(value)
+ end
+ end
+
+ # convert something to a BigDecimal
+ def value_to_decimal(value)
+ # Using .class is faster than .is_a? and
+ # subclasses of BigDecimal will be handled
+ # in the else clause
+ if value.class == BigDecimal
+ value
+ elsif value.respond_to?(:to_d)
+ value.to_d
+ else
+ value.to_s.to_d
+ end
+ end
+
+ protected
+ # '0.123456' -> 123456
+ # '1.123456' -> 123456
+ def microseconds(time)
+ ((time[:sec_fraction].to_f % 1) * 1_000_000).to_i
+ end
+
+ def new_date(year, mon, mday)
+ if year && year != 0
+ Date.new(year, mon, mday) rescue nil
+ end
+ end
+
+ def new_time(year, mon, mday, hour, min, sec, microsec)
+ # Treat 0000-00-00 00:00:00 as nil.
+ return nil if year.nil? || year == 0
+
+ Time.time_with_datetime_fallback(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
+ end
+
+ def fast_string_to_date(string)
+ if string =~ Format::ISO_DATE
+ new_date $1.to_i, $2.to_i, $3.to_i
+ end
+ end
+
+ # Doesn't handle time zones.
+ def fast_string_to_time(string)
+ if string =~ Format::ISO_DATETIME
+ microsec = ($7.to_f * 1_000_000).to_i
+ new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
+ end
+ end
+
+ def fallback_string_to_date(string)
+ new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
+ end
+
+ def fallback_string_to_time(string)
+ time_hash = Date._parse(string)
+ time_hash[:sec_fraction] = microseconds(time_hash)
+
+ new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
+ end
+ end
+
+ private
+ def extract_limit(sql_type)
+ $1.to_i if sql_type =~ /\((.*)\)/
+ end
+
+ def extract_precision(sql_type)
+ $2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
+ end
+
+ def extract_scale(sql_type)
+ case sql_type
+ when /^(numeric|decimal|number)\((\d+)\)/i then 0
+ when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
+ end
+ end
+
+ def simplified_type(field_type)
+ case field_type
+ when /int/i
+ :integer
+ when /float|double/i
+ :float
+ when /decimal|numeric|number/i
+ extract_scale(field_type) == 0 ? :integer : :decimal
+ when /datetime/i
+ :datetime
+ when /timestamp/i
+ :timestamp
+ when /time/i
+ :time
+ when /date/i
+ :date
+ when /clob/i, /text/i
+ :text
+ when /blob/i, /binary/i
+ :binary
+ when /char/i, /string/i
+ :string
+ when /boolean/i
+ :boolean
+ end
+ end
+ end
+ end
+ # :startdoc:
+end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index 568759775b..7bad511c64 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -1,11 +1,16 @@
# encoding: utf-8
-require 'mysql2' unless defined? Mysql2
+require 'mysql2'
module ActiveRecord
class Base
def self.mysql2_connection(config)
config[:username] = 'root' if config[:username].nil?
+
+ if Mysql2::Client.const_defined? :FOUND_ROWS
+ config[:flags] = Mysql2::Client::FOUND_ROWS
+ end
+
client = Mysql2::Client.new(config.symbolize_keys)
options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
@@ -13,6 +18,9 @@ module ActiveRecord
end
module ConnectionAdapters
+ class Mysql2IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc:
+ end
+
class Mysql2Column < Column
BOOL = "tinyint(1)"
def extract_default(default)
@@ -34,62 +42,17 @@ module ActiveRecord
super
end
- # Returns the Ruby class that corresponds to the abstract data type.
- def klass
- case type
- when :integer then Fixnum
- when :float then Float
- when :decimal then BigDecimal
- when :datetime then Time
- when :date then Date
- when :timestamp then Time
- when :time then Time
- when :text, :string then String
- when :binary then String
- when :boolean then Object
- end
- end
-
- def type_cast(value)
- return nil if value.nil?
- case type
- when :string then value
- when :text then value
- when :integer then value.to_i rescue value ? 1 : 0
- when :float then value.to_f # returns self if it's already a Float
- when :decimal then self.class.value_to_decimal(value)
- when :datetime, :timestamp then value.class == Time ? value : self.class.string_to_time(value)
- when :time then value.class == Time ? value : self.class.string_to_dummy_time(value)
- when :date then value.class == Date ? value : self.class.string_to_date(value)
- when :binary then value
- when :boolean then self.class.value_to_boolean(value)
- else value
- end
- end
-
- def type_cast_code(var_name)
- case type
- when :string then nil
- when :text then nil
- when :integer then "#{var_name}.to_i rescue #{var_name} ? 1 : 0"
- when :float then "#{var_name}.to_f"
- when :decimal then "#{self.class.name}.value_to_decimal(#{var_name})"
- when :datetime, :timestamp then "#{var_name}.class == Time ? #{var_name} : #{self.class.name}.string_to_time(#{var_name})"
- when :time then "#{var_name}.class == Time ? #{var_name} : #{self.class.name}.string_to_dummy_time(#{var_name})"
- when :date then "#{var_name}.class == Date ? #{var_name} : #{self.class.name}.string_to_date(#{var_name})"
- when :binary then nil
- when :boolean then "#{self.class.name}.value_to_boolean(#{var_name})"
- else nil
- end
- end
-
private
def simplified_type(field_type)
return :boolean if Mysql2Adapter.emulate_booleans && field_type.downcase.index(BOOL)
- return :string if field_type =~ /enum/i or field_type =~ /set/i
- return :integer if field_type =~ /year/i
- return :binary if field_type =~ /bit/i
- super
+
+ 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)
@@ -234,10 +197,7 @@ module ActiveRecord
def active?
return false unless @connection
- @connection.query 'select 1'
- true
- rescue Mysql2::Error
- false
+ @connection.ping
end
def reconnect!
@@ -277,7 +237,7 @@ module ActiveRecord
# return r
# end
# end
- #
+ #
# # Returns a single value from a record
# def select_value(sql, name = nil)
# result = execute(sql, name)
@@ -285,7 +245,7 @@ module ActiveRecord
# 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)
@@ -368,6 +328,7 @@ module ActiveRecord
end
sql
end
+ deprecate :add_limit_offset!
# SCHEMA STATEMENTS ========================================
@@ -442,10 +403,11 @@ module ActiveRecord
if current_index != row[:Key_name]
next if row[:Key_name] == PRIMARY # skip the primary key
current_index = row[:Key_name]
- indexes << IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique] == 0, [])
+ indexes << Mysql2IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique] == 0, [], [])
end
indexes.last.columns << row[:Column_name]
+ indexes.last.lengths << row[:Sub_part]
end
indexes
end
@@ -453,7 +415,7 @@ module ActiveRecord
def columns(table_name, name = nil)
sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}"
columns = []
- result = execute(sql, :skip_logging)
+ result = execute(sql)
result.each(:symbolize_keys => true, :as => :hash) { |field|
columns << Mysql2Column.new(field[:Field], field[:Default], field[:Type], field[:Null] == "YES")
}
@@ -606,12 +568,21 @@ module ActiveRecord
def configure_connection
@connection.query_options.merge!(:as => :array)
- encoding = @config[:encoding]
- execute("SET NAMES '#{encoding}'", :skip_logging) if encoding
# By default, MySQL 'where id is null' selects the last inserted id.
# Turn this off. http://dev.rubyonrails.org/ticket/6778
- execute("SET SQL_AUTO_IS_NULL=0", :skip_logging)
+ variable_assignments = ['SQL_AUTO_IS_NULL=0']
+ encoding = @config[:encoding]
+
+ # make sure we set the encoding
+ variable_assignments << "NAMES '#{encoding}'" if encoding
+
+ # increase timeout so mysql server doesn't disconnect us
+ wait_timeout = @config[:wait_timeout]
+ wait_timeout = 2592000 unless wait_timeout.is_a?(Fixnum)
+ variable_assignments << "@@wait_timeout = #{wait_timeout}"
+
+ execute("SET #{variable_assignments.join(', ')}", :skip_logging)
end
# Returns an array of record hashes with the column names as keys and
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index ba0051de05..e1186209d3 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -3,6 +3,28 @@ require 'active_support/core_ext/kernel/requires'
require 'active_support/core_ext/object/blank'
require 'set'
+begin
+ require 'mysql'
+rescue LoadError
+ raise "!!! Missing the mysql gem. Add it to your Gemfile: gem 'mysql'"
+end
+
+unless defined?(Mysql::Result) && Mysql::Result.method_defined?(:each_hash)
+ raise "!!! Outdated mysql gem. Upgrade to 2.8.1 or later. In your Gemfile: gem 'mysql', '2.8.1'. Or use gem 'mysql2'"
+end
+
+class Mysql
+ class Time
+ ###
+ # This monkey patch is for test_additional_columns_from_join_table
+ def to_date
+ Date.new(year, month, day)
+ end
+ end
+ class Stmt; include Enumerable end
+ class Result; include Enumerable end
+end
+
module ActiveRecord
class Base
# Establishes a connection to the database that's used by all Active Record objects.
@@ -15,22 +37,11 @@ module ActiveRecord
password = config[:password].to_s
database = config[:database]
- unless defined? Mysql
- begin
- require 'mysql'
- rescue LoadError
- raise "!!! Missing the mysql gem. Add it to your Gemfile: gem 'mysql', '2.8.1'"
- end
-
- unless defined?(Mysql::Result) && Mysql::Result.method_defined?(:each_hash)
- raise "!!! Outdated mysql gem. Upgrade to 2.8.1 or later. In your Gemfile: gem 'mysql', '2.8.1'"
- end
- end
-
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
@@ -38,6 +49,30 @@ module ActiveRecord
module ConnectionAdapters
class MysqlColumn < Column #:nodoc:
+ class << self
+ def 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 string_to_dummy_time(v)
+ return super unless Mysql::Time === v
+ new_time(2000, 01, 01, v.hour, v.minute, v.second, v.second_part)
+ end
+
+ def string_to_date(v)
+ return super unless Mysql::Time === v
+ new_date(v.year, v.month, v.day)
+ end
+ end
+
def extract_default(default)
if sql_type =~ /blob/i || type == :text
if default.blank?
@@ -131,7 +166,7 @@ module ActiveRecord
cattr_accessor :emulate_booleans
self.emulate_booleans = true
- ADAPTER_NAME = 'MySQL'.freeze
+ ADAPTER_NAME = 'MySQL'
LOST_CONNECTION_ERROR_MESSAGES = [
"Server shutdown in progress",
@@ -139,10 +174,10 @@ module ActiveRecord
"Lost connection to MySQL server during query",
"MySQL server has gone away" ]
- QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze
+ QUOTED_TRUE, QUOTED_FALSE = '1', '0'
NATIVE_DATABASE_TYPES = {
- :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze,
+ :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY",
:string => { :name => "varchar", :limit => 255 },
:text => { :name => "text" },
:integer => { :name => "int", :limit => 4 },
@@ -160,6 +195,7 @@ module ActiveRecord
super(connection, logger)
@connection_options, @config = connection_options, config
@quoted_column_names, @quoted_table_names = {}, {}
+ @statements = {}
connect
end
@@ -167,6 +203,16 @@ module ActiveRecord
ADAPTER_NAME
end
+ def supports_bulk_alter? #:nodoc:
+ true
+ end
+
+ # Returns +true+ when the connection adapter supports prepared statement
+ # caching, otherwise returns +false+
+ def supports_statement_cache?
+ true
+ end
+
def supports_migrations? #:nodoc:
true
end
@@ -251,6 +297,7 @@ module ActiveRecord
def reconnect!
disconnect!
+ clear_cache!
connect
end
@@ -271,14 +318,69 @@ module ActiveRecord
def select_rows(sql, name = nil)
@connection.query_with_result = true
- result = execute(sql, name)
- rows = []
- result.each { |row| rows << row }
- result.free
+ rows = exec_without_stmt(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
- # Executes an SQL query and returns a MySQL::Result object. Note that you have to free
+ def clear_cache!
+ @statements.values.each do |cache|
+ cache[:stmt].close
+ end
+ @statements.clear
+ end
+
+ def exec_query(sql, name = 'SQL', binds = [])
+ log(sql, name, binds) do
+ result = nil
+
+ cache = {}
+ if binds.empty?
+ stmt = @connection.prepare(sql)
+ else
+ cache = @statements[sql] ||= {
+ :stmt => @connection.prepare(sql)
+ }
+ stmt = cache[:stmt]
+ end
+
+ stmt.execute(*binds.map { |col, val|
+ col ? col.type_cast(val) : val
+ })
+ if metadata = stmt.result_metadata
+ cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
+ field.name
+ }
+
+ metadata.free
+ result = ActiveRecord::Result.new(cols, stmt.to_a)
+ end
+
+ stmt.free_result
+ stmt.close if binds.empty?
+
+ result
+ end
+ end
+
+ def exec_without_stmt(sql, name = 'SQL') # :nodoc:
+ # Some queries, like SHOW CREATE TABLE don't work through the prepared
+ # statement API. For those queries, we need to use this method. :'(
+ log(sql, name) do
+ result = @connection.query(sql)
+ cols = []
+ rows = []
+
+ if result
+ cols = result.fetch_fields.map { |field| field.name }
+ rows = result.to_a
+ result.free
+ end
+ ActiveRecord::Result.new(cols, rows)
+ end
+ end
+
+ # Executes an SQL query and returns a MySQL::Result object. Note that you have to free
# the Result object after you're done using it.
def execute(sql, name = nil) #:nodoc:
if name == :skip_logging
@@ -306,8 +408,8 @@ module ActiveRecord
end
def begin_db_transaction #:nodoc:
- execute "BEGIN"
- rescue Exception
+ exec_without_stmt "BEGIN"
+ rescue Mysql::Error
# Transactions aren't supported
end
@@ -346,6 +448,7 @@ module ActiveRecord
end
sql
end
+ deprecate :add_limit_offset!
# SCHEMA STATEMENTS ========================================
@@ -356,10 +459,11 @@ module ActiveRecord
sql = "SHOW TABLES"
end
- select_all(sql).inject("") do |structure, table|
+ select_all(sql).map do |table|
table.delete('Table_type')
- structure += select_one("SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}")["Create Table"] + ";\n\n"
- end
+ sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}"
+ exec_without_stmt(sql).first['Create Table'] + ";\n\n"
+ end.join("")
end
def recreate_database(name, options = {}) #:nodoc:
@@ -400,14 +504,28 @@ module ActiveRecord
show_variable 'collation_database'
end
- def tables(name = nil) #:nodoc:
+ def tables(name = nil, database = nil) #:nodoc:
tables = []
- result = execute("SHOW TABLES", name)
+ result = execute(["SHOW TABLES", database].compact.join(' IN '), name)
result.each { |field| tables << field[0] }
result.free
tables
end
+ def table_exists?(name)
+ return true if super
+
+ name = name.to_s
+ schema, table = name.split('.', 2)
+
+ unless table # A table was provided without a schema
+ table = schema
+ schema = nil
+ end
+
+ tables(nil, schema).include? table
+ end
+
def drop_table(table_name, options = {})
super(table_name, options)
end
@@ -433,7 +551,7 @@ module ActiveRecord
def columns(table_name, name = nil)#:nodoc:
sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}"
columns = []
- result = execute(sql, :skip_logging)
+ result = execute(sql)
result.each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") }
result.free
columns
@@ -447,11 +565,23 @@ module ActiveRecord
execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
end
+ def bulk_change_table(table_name, operations) #:nodoc:
+ sqls = operations.map do |command, args|
+ table, arguments = args.shift, args
+ method = :"#{command}_sql"
+
+ if respond_to?(method)
+ send(method, table, *arguments)
+ else
+ raise "Unknown method called : #{method}(#{arguments.inspect})"
+ end
+ end.flatten.join(", ")
+
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{sqls}")
+ end
+
def add_column(table_name, column_name, type, options = {})
- add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
- add_column_options!(add_column_sql, options)
- add_column_position!(add_column_sql, options)
- execute(add_column_sql)
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{add_column_sql(table_name, column_name, type, options)}")
end
def change_column_default(table_name, column_name, default) #:nodoc:
@@ -470,34 +600,11 @@ module ActiveRecord
end
def change_column(table_name, column_name, type, options = {}) #:nodoc:
- column = column_for(table_name, column_name)
-
- unless options_include_default?(options)
- options[:default] = column.default
- end
-
- unless options.has_key?(:null)
- options[:null] = column.null
- end
-
- change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
- add_column_options!(change_column_sql, options)
- add_column_position!(change_column_sql, options)
- execute(change_column_sql)
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_sql(table_name, column_name, type, options)}")
end
def rename_column(table_name, column_name, new_column_name) #:nodoc:
- options = {}
- if column = columns(table_name).find { |c| c.name == column_name.to_s }
- options[:default] = column.default
- options[:null] = column.null
- else
- raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
- end
- current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
- rename_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
- add_column_options!(rename_column_sql, options)
- execute(rename_column_sql)
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_sql(table_name, column_name, new_column_name)}")
end
# Maps logical Rails types to MySQL-specific data types.
@@ -580,6 +687,69 @@ module ActiveRecord
end
end
+ def add_column_sql(table_name, column_name, type, options = {})
+ add_column_sql = "ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(add_column_sql, options)
+ add_column_position!(add_column_sql, options)
+ add_column_sql
+ end
+
+ def remove_column_sql(table_name, *column_names)
+ columns_for_remove(table_name, *column_names).map {|column_name| "DROP #{column_name}" }
+ end
+ alias :remove_columns_sql :remove_column
+
+ def change_column_sql(table_name, column_name, type, options = {})
+ column = column_for(table_name, column_name)
+
+ unless options_include_default?(options)
+ options[:default] = column.default
+ end
+
+ unless options.has_key?(:null)
+ options[:null] = column.null
+ end
+
+ change_column_sql = "CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(change_column_sql, options)
+ add_column_position!(change_column_sql, options)
+ change_column_sql
+ end
+
+ def rename_column_sql(table_name, column_name, new_column_name)
+ options = {}
+
+ if column = columns(table_name).find { |c| c.name == column_name.to_s }
+ options[:default] = column.default
+ options[:null] = column.null
+ else
+ raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
+ end
+
+ current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
+ rename_column_sql = "CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
+ add_column_options!(rename_column_sql, options)
+ rename_column_sql
+ end
+
+ def add_index_sql(table_name, column_name, options = {})
+ index_name, index_type, index_columns = add_index_options(table_name, column_name, options)
+ "ADD #{index_type} INDEX #{index_name} (#{index_columns})"
+ end
+
+ def remove_index_sql(table_name, options = {})
+ index_name = index_name_for_remove(table_name, options)
+ "DROP INDEX #{index_name}"
+ end
+
+ def add_timestamps_sql(table_name)
+ [add_column_sql(table_name, :created_at, :datetime), add_column_sql(table_name, :updated_at, :datetime)]
+ end
+
+ def remove_timestamps_sql(table_name)
+ [remove_column_sql(table_name, :updated_at), remove_column_sql(table_name, :created_at)]
+ end
+
private
def connect
encoding = @config[:encoding]
@@ -612,12 +782,10 @@ module ActiveRecord
execute("SET SQL_AUTO_IS_NULL=0", :skip_logging)
end
- def select(sql, name = nil)
+ def select(sql, name = nil, binds = [])
@connection.query_with_result = true
- result = execute(sql, name)
- rows = []
- result.each_hash { |row| rows << row }
- result.free
+ rows = exec_query(sql, name, binds).to_a
+ @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
rows
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index 6fae899e87..5a830a50fb 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -1,20 +1,19 @@
require 'active_record/connection_adapters/abstract_adapter'
require 'active_support/core_ext/kernel/requires'
require 'active_support/core_ext/object/blank'
+require 'pg'
module ActiveRecord
class Base
# Establishes a connection to the database that's used by all Active Record objects
def self.postgresql_connection(config) # :nodoc:
- require 'pg'
-
config = config.symbolize_keys
host = config[:host]
port = config[:port] || 5432
username = config[:username].to_s if config[:username]
password = config[:password].to_s if config[:password]
- if config.has_key?(:database)
+ if config.key?(:database)
database = config[:database]
else
raise ArgumentError, "No database specified. Missing argument: database."
@@ -27,12 +26,6 @@ module ActiveRecord
end
module ConnectionAdapters
- class TableDefinition
- def xml(*args)
- options = args.extract_options!
- column(args[0], 'xml', options)
- end
- end
# PostgreSQL-specific extensions to column definitions in a table.
class PostgreSQLColumn < Column #:nodoc:
# Instantiates a new PostgreSQL column definition in a table.
@@ -170,9 +163,7 @@ module ActiveRecord
end
end
end
- end
- module ConnectionAdapters
# The PostgreSQL adapter works both with the native C (http://ruby.scripting.ca/postgres/) and the pure
# Ruby (available both as gem and from http://rubyforge.org/frs/?group_id=234&release_id=1944) drivers.
#
@@ -183,19 +174,24 @@ module ActiveRecord
# * <tt>:username</tt> - Defaults to nothing.
# * <tt>:password</tt> - Defaults to nothing.
# * <tt>:database</tt> - The name of the database. No default, must be provided.
- # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
+ # * <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
+ # * <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>: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>:allow_concurrency</tt> - If true, use async query methods so Ruby threads don't deadlock;
- # otherwise, use blocking query methods.
class PostgreSQLAdapter < AbstractAdapter
- ADAPTER_NAME = 'PostgreSQL'.freeze
+ class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
+ def xml(*args)
+ options = args.extract_options!
+ column(args[0], 'xml', options)
+ end
+ end
+
+ ADAPTER_NAME = 'PostgreSQL'
NATIVE_DATABASE_TYPES = {
- :primary_key => "serial primary key".freeze,
+ :primary_key => "serial primary key",
:string => { :name => "character varying", :limit => 255 },
:text => { :name => "text" },
:integer => { :name => "integer" },
@@ -215,6 +211,12 @@ module ActiveRecord
ADAPTER_NAME
end
+ # Returns +true+ when the connection adapter supports prepared statement
+ # caching, otherwise returns +false+
+ def supports_statement_cache?
+ true
+ end
+
# Initializes and connects a PostgreSQL adapter.
def initialize(connection, logger, connection_parameters, config)
super(connection, logger)
@@ -224,11 +226,19 @@ module ActiveRecord
@local_tz = nil
@table_alias_length = nil
@postgresql_version = nil
+ @statements = {}
connect
@local_tz = execute('SHOW TIME ZONE').first["TimeZone"]
end
+ def clear_cache!
+ @statements.each_value do |value|
+ @connection.query "DEALLOCATE #{value}"
+ end
+ @statements.clear
+ end
+
# Is this connection alive and ready for queries?
def active?
if @connection.respond_to?(:status)
@@ -246,6 +256,7 @@ module ActiveRecord
# Close then reopen the connection.
def reconnect!
if @connection.respond_to?(:reset)
+ clear_cache!
@connection.reset
configure_connection
else
@@ -254,8 +265,14 @@ module ActiveRecord
end
end
+ def reset!
+ clear_cache!
+ super
+ end
+
# Close the connection.
def disconnect!
+ clear_cache!
@connection.close rescue nil
end
@@ -317,19 +334,22 @@ module ActiveRecord
def quote(value, column = nil) #:nodoc:
return super unless column
- if value.kind_of?(String) && column.type == :binary
- "'#{escape_bytea(value)}'"
- elsif value.kind_of?(String) && column.sql_type == 'xml'
- "xml '#{quote_string(value)}'"
- elsif value.kind_of?(Numeric) && column.sql_type == 'money'
+ case value
+ when Numeric
+ return super unless column.sql_type == 'money'
# Not truly string input, so doesn't require (or allow) escape string syntax.
"'#{value}'"
- elsif value.kind_of?(String) && column.sql_type =~ /^bit/
- case value
- when /^[01]*$/
- "B'#{value}'" # Bit-string notation
- when /^[0-9A-F]*$/i
- "X'#{value}'" # Hexadecimal notation
+ when String
+ case column.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
@@ -375,13 +395,16 @@ module ActiveRecord
end
end
+ # Set the authorized user for this session
+ def session_auth=(user)
+ clear_cache!
+ exec_query "SET SESSION AUTHORIZATION #{user}"
+ end
+
# REFERENTIAL INTEGRITY ====================================
def supports_disable_referential_integrity?() #:nodoc:
- version = query("SHOW server_version")[0][0].split('.')
- version[0].to_i >= 8 && version[1].to_i >= 1
- rescue
- return false
+ postgresql_version >= 80100
end
def disable_referential_integrity #:nodoc:
@@ -430,7 +453,7 @@ module ActiveRecord
# If a pk is given, fallback to default sequence name.
# Don't fetch last insert id for a table without a pk.
if pk && sequence_name ||= default_sequence_name(table, pk)
- last_insert_id(table, sequence_name)
+ last_insert_id(sequence_name)
end
end
end
@@ -466,8 +489,8 @@ module ActiveRecord
# (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.]/, '')
+ when /^-?\D+[\d.]+,\d{2}$/ # (2)
data.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
end
end
@@ -502,6 +525,35 @@ module ActiveRecord
end
end
+ def substitute_for(column, current_values)
+ Arel.sql("$#{current_values.length + 1}")
+ end
+
+ def exec_query(sql, name = 'SQL', binds = [])
+ return exec_no_cache(sql, name) if binds.empty?
+
+ log(sql, name, binds) do
+ unless @statements.key? sql
+ nextkey = "a#{@statements.length + 1}"
+ @connection.prepare nextkey, sql
+ @statements[sql] = nextkey
+ end
+
+ key = @statements[sql]
+
+ # Clear the queue
+ @connection.get_last_result
+ @connection.send_query_prepared(key, binds.map { |col, val|
+ col ? col.type_cast(val) : val
+ })
+ @connection.block
+ result = @connection.get_last_result
+ ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
+ result.clear
+ return ret
+ end
+ end
+
# Executes an UPDATE query and returns the number of affected tuples.
def update_sql(sql, name = nil)
super.cmd_tuples
@@ -659,8 +711,8 @@ module ActiveRecord
# Returns the list of all column definitions for a table.
def columns(table_name, name = nil)
# Limit, precision, and scale are all handled by the superclass.
- column_definitions(table_name).collect do |name, type, default, notnull|
- PostgreSQLColumn.new(name, default, type, notnull == 'f')
+ column_definitions(table_name).collect do |column_name, type, default, notnull|
+ PostgreSQLColumn.new(column_name, default, type, notnull == 'f')
end
end
@@ -734,7 +786,7 @@ module ActiveRecord
def pk_and_sequence_for(table) #:nodoc:
# First try looking for a sequence with a dependency on the
# given table's primary key.
- result = query(<<-end_sql, 'PK and serial sequence')[0]
+ result = exec_query(<<-end_sql, 'PK and serial sequence').rows.first
SELECT attr.attname, seq.relname
FROM pg_class seq,
pg_attribute attr,
@@ -793,14 +845,18 @@ module ActiveRecord
# Adds a new column to the named table.
# See TableDefinition#column for details of the options you can use.
def add_column(table_name, column_name, type, options = {})
- default = options[:default]
- notnull = options[:null] == false
+ add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(add_column_sql, options)
- # Add the column.
- execute("ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}")
+ begin
+ execute add_column_sql
+ rescue ActiveRecord::StatementInvalid => e
+ raise e if postgresql_version > 80000
- change_column_default(table_name, column_name, default) if options_include_default?(options)
- change_column_null(table_name, column_name, false, default) if notnull
+ execute("ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}")
+ change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
+ change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
+ end
end
# Changes the column of a table.
@@ -850,6 +906,10 @@ module ActiveRecord
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
@@ -873,13 +933,13 @@ module ActiveRecord
# requires that the ORDER BY include the distinct column.
#
# distinct("posts.id", "posts.created_at desc")
- def distinct(columns, order_by) #:nodoc:
- return "DISTINCT #{columns}" if order_by.blank?
+ def distinct(columns, orders) #:nodoc:
+ return "DISTINCT #{columns}" if orders.empty?
# Construct a clean list of column names from the ORDER BY clause, removing
# any ASC/DESC modifiers
- order_columns = order_by.split(',').collect { |s| s.split.first }
- order_columns.delete_if(&:blank?)
+ order_columns = orders.collect { |s| s =~ /^(.+)\s+(ASC|DESC)\s*$/i ? $1 : s }
+ order_columns.delete_if { |c| c.blank? }
order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }
# Return a DISTINCT ON() clause that's distinct on the columns we want but includes
@@ -897,8 +957,12 @@ module ActiveRecord
else
# Mimic PGconn.server_version behavior
begin
- query('SELECT version()')[0][0] =~ /PostgreSQL (\d+)\.(\d+)\.(\d+)/
- ($1.to_i * 10000) + ($2.to_i * 100) + $3.to_i
+ if query('SELECT version()')[0][0] =~ /PostgreSQL ([0-9.]+)/
+ major, minor, tiny = $1.split(".")
+ (major.to_i * 10000) + (minor.to_i * 100) + tiny.to_i
+ else
+ 0
+ end
rescue
0
end
@@ -917,6 +981,15 @@ module ActiveRecord
end
private
+ def exec_no_cache(sql, name)
+ log(sql, name) do
+ result = @connection.async_exec(sql)
+ ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
+ result.clear
+ ret
+ end
+ 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.
@@ -929,7 +1002,7 @@ module ActiveRecord
PGconn.translate_results = false if PGconn.respond_to?(:translate_results=)
# Ignore async_exec and async_query when using postgres-pr.
- @async = @config[:allow_concurrency] && @connection.respond_to?(:async_exec)
+ @async = @connection.respond_to?(:async_exec)
# 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
@@ -965,17 +1038,15 @@ module ActiveRecord
end
# Returns the current ID of a table's sequence.
- def last_insert_id(table, sequence_name) #:nodoc:
- Integer(select_value("SELECT currval('#{sequence_name}')"))
+ def last_insert_id(sequence_name) #:nodoc:
+ r = exec_query("SELECT currval($1)", 'SQL', [[nil, sequence_name]])
+ Integer(r.rows.first.first)
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)
- fields, rows = select_raw(sql, name)
- rows.map do |row|
- Hash[*fields.zip(row).flatten]
- end
+ def select(sql, name = nil, binds = [])
+ exec_query(sql, name, binds).to_a
end
def select_raw(sql, name = nil)
@@ -1005,7 +1076,7 @@ module ActiveRecord
# - format_type includes the column size constraint, e.g. varchar(50)
# - ::regclass is a function that gives the id for a table name
def column_definitions(table_name) #:nodoc:
- query <<-end_sql
+ exec_query(<<-end_sql).rows
SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
@@ -1016,14 +1087,18 @@ module ActiveRecord
end
def extract_pg_identifier_from_name(name)
- match_data = name[0,1] == '"' ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
+ match_data = name.start_with?('"') ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
if match_data
- rest = name[match_data[0].length..-1]
- rest = rest[1..-1] if rest[0,1] == "."
+ 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 table_definition
+ TableDefinition.new(self)
+ end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index e5e92f2b1c..c3a7b039ff 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -1,4 +1,5 @@
require 'active_record/connection_adapters/sqlite_adapter'
+require 'sqlite3'
module ActiveRecord
class Base
@@ -20,16 +21,12 @@ module ActiveRecord
raise ArgumentError, 'adapter name should be "sqlite3"'
end
- unless self.class.const_defined?(:SQLite3)
- require_library_or_gem(config[:adapter])
- end
-
db = SQLite3::Database.new(
config[:database],
:results_as_hash => true
)
- db.busy_timeout(config[:timeout]) unless config[:timeout].nil?
+ db.busy_timeout(config[:timeout]) if config[:timeout]
ConnectionAdapters::SQLite3Adapter.new(db, logger, config)
end
@@ -37,14 +34,21 @@ module ActiveRecord
module ConnectionAdapters #:nodoc:
class SQLite3Adapter < SQLiteAdapter # :nodoc:
+ 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
# Returns the current database encoding format as a string, eg: 'UTF-8'
def encoding
if @connection.respond_to?(:encoding)
@connection.encoding.to_s
else
- encoding = @connection.execute('PRAGMA encoding')
- encoding[0]['encoding']
+ @connection.execute('PRAGMA encoding')[0]['encoding']
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
index 82ad0a3b8e..ae61d6ce94 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -29,7 +29,7 @@ module ActiveRecord
end
end
- # The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby
+ # The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby
# drivers (available both as gems and from http://rubyforge.org/projects/sqlite-ruby/).
#
# Options:
@@ -40,16 +40,17 @@ module ActiveRecord
include Comparable
def initialize(version_string)
- @version = version_string.split('.').map(&:to_i)
+ @version = version_string.split('.').map { |v| v.to_i }
end
def <=>(version_string)
- @version <=> version_string.split('.').map(&:to_i)
+ @version <=> version_string.split('.').map { |v| v.to_i }
end
end
def initialize(connection, logger, config)
super(connection, logger)
+ @statements = {}
@config = config
end
@@ -61,6 +62,16 @@ module ActiveRecord
sqlite_version >= '2.0.0'
end
+ def supports_savepoints?
+ sqlite_version >= '3.6.8'
+ end
+
+ # Returns +true+ when the connection adapter supports prepared statement
+ # caching, otherwise returns +false+
+ def supports_statement_cache?
+ true
+ end
+
def supports_migrations? #:nodoc:
true
end
@@ -79,9 +90,14 @@ module ActiveRecord
def disconnect!
super
+ clear_cache!
@connection.close rescue nil
end
+ def clear_cache!
+ @statements.clear
+ end
+
def supports_count_distinct? #:nodoc:
sqlite_version >= '3.2.6'
end
@@ -121,7 +137,7 @@ module ActiveRecord
# 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.acts_like?(:time) && value.respond_to?(:usec)
+ if value.respond_to?(:usec)
"#{super}.#{sprintf("%06d", value.usec)}"
else
super
@@ -131,6 +147,32 @@ module ActiveRecord
# DATABASE STATEMENTS ======================================
+ 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|
+ col ? col.type_cast(val) : val
+ }
+ end
+
+ ActiveRecord::Result.new(cols, stmt.to_a)
+ end
+ end
+
def execute(sql, name = nil) #:nodoc:
log(sql, name) { @connection.execute(sql) }
end
@@ -151,9 +193,19 @@ module ActiveRecord
alias :create :insert_sql
def select_rows(sql, name = nil)
- execute(sql, name).map do |row|
- (0...(row.size / 2)).map { |i| row[i] }
- end
+ 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:
@@ -177,24 +229,33 @@ module ActiveRecord
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
SQL
- execute(sql, name).map do |row|
+ exec_query(sql, name).map do |row|
row['name']
end
end
def columns(table_name, name = nil) #:nodoc:
table_structure(table_name).map do |field|
+ case field["dflt_value"]
+ when /^null$/i
+ field["dflt_value"] = nil
+ when /^'(.*)'$/
+ field["dflt_value"] = $1.gsub(/''/, "'")
+ when /^"(.*)"$/
+ field["dflt_value"] = $1.gsub(/""/, '"')
+ end
+
SQLiteColumn.new(field['name'], field['dflt_value'], field['type'], field['notnull'].to_i == 0)
end
end
def indexes(table_name, name = nil) #:nodoc:
- execute("PRAGMA index_list(#{quote_table_name(table_name)})", name).map do |row|
+ exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", name).map do |row|
IndexDefinition.new(
table_name,
row['name'],
- row['unique'].to_i != 0,
- execute("PRAGMA index_info('#{row['name']}')").map { |col|
+ row['unique'] != 0,
+ exec_query("PRAGMA index_info('#{row['name']}')").map { |col|
col['name']
})
end
@@ -202,17 +263,17 @@ module ActiveRecord
def primary_key(table_name) #:nodoc:
column = table_structure(table_name).find { |field|
- field['pk'].to_i == 1
+ field['pk'] == 1
}
column && column['name']
end
def remove_index!(table_name, index_name) #:nodoc:
- execute "DROP INDEX #{quote_column_name(index_name)}"
+ exec_query "DROP INDEX #{quote_column_name(index_name)}"
end
def rename_table(name, new_name)
- execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
+ exec_query "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
end
# See: http://www.sqlite.org/lang_altertable.html
@@ -249,7 +310,7 @@ module ActiveRecord
def change_column_null(table_name, column_name, null, default = nil)
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")
+ 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
@@ -275,23 +336,21 @@ module ActiveRecord
alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s})
end
+ def null_insert_value
+ Arel.sql 'NULL'
+ end
+
def empty_insert_statement_value
"VALUES(NULL)"
end
protected
- def select(sql, name = nil) #:nodoc:
- execute(sql, name).map do |row|
- record = {}
- row.each do |key, value|
- record[key.sub(/^"?\w+"?\./, '')] = value if key.is_a?(String)
- end
- record
- end
+ def select(sql, name = nil, binds = []) #:nodoc:
+ exec_query(sql, name, binds).to_a
end
def table_structure(table_name)
- structure = @connection.table_info(quote_table_name(table_name))
+ structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})").to_hash
raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
structure
end
@@ -345,7 +404,7 @@ module ActiveRecord
name = name[5..-1]
end
- to_column_names = columns(to).map(&:name)
+ 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
@@ -360,18 +419,18 @@ module ActiveRecord
end
def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
- column_mappings = Hash[*columns.map {|name| [name, name]}.flatten]
- rename.inject(column_mappings) {|map, a| map[a.last] = a.first; map}
+ 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)
- @connection.execute "SELECT * FROM #{quote_table_name(from)}" do |row|
+ exec_query("SELECT * FROM #{quote_table_name(from)}").each do |row|
sql = "INSERT INTO #{quoted_to} (#{quoted_columns}) VALUES ("
sql << columns.map {|col| quote row[column_mappings[col]]} * ', '
sql << ')'
- @connection.execute sql
+ exec_query sql
end
end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index 237cd56683..7839f03848 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -30,9 +30,10 @@ module ActiveRecord
reflection = belongs_to.find { |e| e.class_name == expected_name }
counter_name = reflection.counter_cache_column
- self.unscoped.where(arel_table[self.primary_key].eq(object.id)).arel.update({
+ stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
arel_table[counter_name] => object.send(association).count
})
+ connection.update stmt.to_sql
end
return true
end
@@ -56,15 +57,15 @@ module ActiveRecord
# Post.update_counters 5, :comment_count => -1, :action_count => 1
# # Executes the following SQL:
# # UPDATE posts
- # # SET comment_count = comment_count - 1,
- # # action_count = action_count + 1
+ # # 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 = comment_count + 1,
+ # # 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|
@@ -73,6 +74,8 @@ module ActiveRecord
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
end
+ IdentityMap.remove_by_id(symbolized_base_class, id) if IdentityMap.enabled?
+
update_all(updates.join(', '), primary_key => id )
end
diff --git a/activerecord/lib/active_record/dynamic_finder_match.rb b/activerecord/lib/active_record/dynamic_finder_match.rb
index 0dc965bd26..b309df9b1b 100644
--- a/activerecord/lib/active_record/dynamic_finder_match.rb
+++ b/activerecord/lib/active_record/dynamic_finder_match.rb
@@ -1,45 +1,48 @@
module ActiveRecord
# = Active Record Dynamic Finder Match
- #
+ #
# Refer to ActiveRecord::Base documentation for Dynamic attribute-based finders for detailed info
#
class DynamicFinderMatch
def self.match(method)
- df_match = self.new(method)
- df_match.finder ? df_match : nil
- end
-
- def initialize(method)
- @finder = :first
- @bang = false
- @instantiator = nil
+ finder = :first
+ bang = false
+ instantiator = nil
case method.to_s
- when /^find_(all_by|last_by|by)_([_a-zA-Z]\w*)$/
- @finder = :last if $1 == 'last_by'
- @finder = :all if $1 == 'all_by'
+ when /^find_(all_|last_)?by_([_a-zA-Z]\w*)$/
+ finder = :last if $1 == 'last_'
+ finder = :all if $1 == 'all_'
names = $2
when /^find_by_([_a-zA-Z]\w*)\!$/
- @bang = true
+ bang = true
names = $1
when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/
- @instantiator = $1 == 'initialize' ? :new : :create
+ instantiator = $1 == 'initialize' ? :new : :create
names = $2
else
- @finder = nil
+ return nil
end
- @attribute_names = names && names.split('_and_')
+
+ new(finder, instantiator, bang, names.split('_and_'))
+ end
+
+ def initialize(finder, instantiator, bang, attribute_names)
+ @finder = finder
+ @instantiator = instantiator
+ @bang = bang
+ @attribute_names = attribute_names
end
attr_reader :finder, :attribute_names, :instantiator
def finder?
- !@finder.nil? && @instantiator.nil?
+ @finder && !@instantiator
end
def instantiator?
- @finder == :first && !@instantiator.nil?
+ @finder == :first && @instantiator
end
def creator?
diff --git a/activerecord/lib/active_record/dynamic_scope_match.rb b/activerecord/lib/active_record/dynamic_scope_match.rb
index 15f65be6bc..c832e927d6 100644
--- a/activerecord/lib/active_record/dynamic_scope_match.rb
+++ b/activerecord/lib/active_record/dynamic_scope_match.rb
@@ -1,32 +1,23 @@
module ActiveRecord
# = Active Record Dynamic Scope Match
- #
+ #
# Provides dynamic attribute-based scopes such as <tt>scoped_by_price(4.99)</tt>
# if, for example, the <tt>Product</tt> has an attribute with that name. You can
# chain more <tt>scoped_by_* </tt> methods after the other. It acts like a named
# scope except that it's dynamic.
class DynamicScopeMatch
def self.match(method)
- ds_match = self.new(method)
- ds_match.scope ? ds_match : nil
+ return unless method.to_s =~ /^scoped_by_([_a-zA-Z]\w*)$/
+ new(true, $1 && $1.split('_and_'))
end
- def initialize(method)
- @scope = true
- case method.to_s
- when /^scoped_by_([_a-zA-Z]\w*)$/
- names = $1
- else
- @scope = nil
- end
- @attribute_names = names && names.split('_and_')
+ def initialize(scope, attribute_names)
+ @scope = scope
+ @attribute_names = attribute_names
end
attr_reader :scope, :attribute_names
-
- def scope?
- !@scope.nil?
- end
+ alias :scope? :scope
end
end
diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb
index e9ac5516ec..ea1709cb1f 100644
--- a/activerecord/lib/active_record/errors.rb
+++ b/activerecord/lib/active_record/errors.rb
@@ -30,7 +30,7 @@ module ActiveRecord
class SerializationTypeMismatch < ActiveRecordError
end
- # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
+ # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
# misses adapter field).
class AdapterNotSpecified < ActiveRecordError
end
@@ -39,7 +39,7 @@ module ActiveRecord
class AdapterNotFound < ActiveRecordError
end
- # Raised when connection to the database could not been established (for example when <tt>connection=</tt>
+ # 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
@@ -53,7 +53,7 @@ module ActiveRecord
class RecordNotSaved < ActiveRecordError
end
- # Raised when SQL statement cannot be executed by the database (for example, it's often the case for
+ # Raised when SQL statement cannot be executed by the database (for example, it's often the case for
# MySQL when Ruby driver used is too old).
class StatementInvalid < ActiveRecordError
end
@@ -81,7 +81,7 @@ module ActiveRecord
class InvalidForeignKey < WrappedDatabaseException
end
- # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
+ # 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.
#
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index e44102b538..d523c643ba 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -1,4 +1,10 @@
require 'erb'
+
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
require 'csv'
require 'zlib'
@@ -6,15 +12,7 @@ require 'active_support/dependencies'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/logger'
-
-if RUBY_VERSION < '1.9'
- module YAML #:nodoc:
- class Omap #:nodoc:
- def keys; map { |k, v| k } end
- def values; map { |k, v| v } end
- end
- end
-end
+require 'active_support/ordered_hash'
if defined? ActiveRecord
class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
@@ -24,6 +22,8 @@ else
end
end
+class FixturesFileNotFound < StandardError; end
+
# Fixtures are a way of organizing data that you want to test against; in short, sample data.
#
# = Fixture formats
@@ -39,9 +39,9 @@ end
# This type of fixture is in YAML format and the preferred default. YAML is a file format which describes data structures
# in a non-verbose, human-readable format. It ships with Ruby 1.8.1+.
#
-# Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed
-# in the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is
-# automatically configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
+# Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed
+# in the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is
+# automatically configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
# The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a YAML fixture file looks like this:
#
@@ -59,7 +59,7 @@ end
# indented list of key/value pairs in the "key: value" format. Records are separated by a blank line for your viewing
# pleasure.
#
-# Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
+# Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
# See http://yaml.org/type/omap.html
# for the specification. You will need ordered fixtures when you have foreign key constraints on keys in the same table.
# This is commonly needed for tree structures. Example:
@@ -81,7 +81,7 @@ end
# (Rails example: <tt><your-rails-app>/test/fixtures/web_sites.csv</tt>).
#
# The format of this type of fixture file is much more compact than the others, but also a little harder to read by us
-# humans. The first line of the CSV file is a comma-separated list of field names. The rest of the
+# humans. The first line of the CSV file is a comma-separated list of field names. The rest of the
# file is then comprised
# of the actual data (1 per line). Here's an example:
#
@@ -102,15 +102,15 @@ end
#
# == Single-file fixtures
#
-# This type of fixture was the original format for Active Record that has since been deprecated in
+# This type of fixture was the original format for Active Record that has since been deprecated in
# favor of the YAML and CSV formats.
-# Fixtures for this format are created by placing text files in a sub-directory (with the name of the model)
-# to the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
+# Fixtures for this format are created by placing text files in a sub-directory (with the name of the model)
+# to 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/<your-model-name>/</tt> --
# like <tt><your-rails-app>/test/fixtures/web_sites/</tt> for the WebSite model).
#
# Each text file placed in this directory represents a "record". Usually these types of fixtures are named without
-# extensions, but if you are on a Windows machine, you might consider adding <tt>.txt</tt> as the extension.
+# extensions, but if you are on a Windows machine, you might consider adding <tt>.txt</tt> as the extension.
# Here's what the above example might look like:
#
# web_sites/google
@@ -137,7 +137,7 @@ end
# end
# end
#
-# By default, the <tt>test_helper module</tt> will load all of your fixtures into your test database,
+# By default, the <tt>test_helper module</tt> will load all of your fixtures into your test database,
# so this test will succeed.
# The testing environment will automatically load the all fixtures into the database before each test.
# To ensure consistent data, the environment deletes the fixtures before running the load.
@@ -187,14 +187,14 @@ end
# This will create 1000 very simple YAML fixtures.
#
# Using ERb, you can also inject dynamic values into your fixtures with inserts like <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
-# This is however a feature to be used with some caution. The point of fixtures are that they're
-# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
-# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
+# This is however a feature to be used with some caution. The point of fixtures are that they're
+# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
+# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
# in fixtures are to be considered a code smell.
#
# = Transactional fixtures
#
-# TestCases can use begin+rollback to isolate their changes to the database instead of having to
+# TestCases can use begin+rollback to isolate their changes to the database instead of having to
# delete+insert for every test case.
#
# class FooTest < ActiveSupport::TestCase
@@ -212,17 +212,17 @@ end
# end
#
# If you preload your test database with all fixture data (probably in the Rakefile task) and use transactional fixtures,
-# then you may omit all fixtures declarations in your test cases since all the data's already there
+# 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
+# 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
+# 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.
@@ -444,20 +444,23 @@ end
#
# Any fixture labeled "DEFAULTS" is safely ignored.
-class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
+class Fixtures
MAX_ID = 2 ** 30 - 1
- DEFAULT_FILTER_RE = /\.ya?ml$/
- @@all_cached_fixtures = {}
+ @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
- def self.reset_cache(connection = nil)
- connection ||= ActiveRecord::Base.connection
- @@all_cached_fixtures[connection.object_id] = {}
+ def self.find_table_name(table_name) # :nodoc:
+ ActiveRecord::Base.pluralize_table_names ?
+ table_name.to_s.singularize.camelize :
+ table_name.to_s.camelize
+ end
+
+ def self.reset_cache
+ @@all_cached_fixtures.clear
end
def self.cache_for_connection(connection)
- @@all_cached_fixtures[connection.object_id] ||= {}
- @@all_cached_fixtures[connection.object_id]
+ @@all_cached_fixtures[connection]
end
def self.fixture_is_cached?(connection, table_name)
@@ -466,27 +469,23 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
def self.cached_fixtures(connection, keys_to_fetch = nil)
if keys_to_fetch
- fixtures = cache_for_connection(connection).values_at(*keys_to_fetch)
+ cache_for_connection(connection).values_at(*keys_to_fetch)
else
- fixtures = cache_for_connection(connection).values
+ cache_for_connection(connection).values
end
- fixtures.size > 1 ? fixtures : fixtures.first
end
def self.cache_fixtures(connection, fixtures_map)
cache_for_connection(connection).update(fixtures_map)
end
- def self.instantiate_fixtures(object, table_name, fixtures, load_instances = true)
- object.instance_variable_set "@#{table_name.to_s.gsub('.','_')}", fixtures
+ def self.instantiate_fixtures(object, fixture_name, fixtures, load_instances = true)
if load_instances
- ActiveRecord::Base.silence do
- fixtures.each do |name, fixture|
- begin
- object.instance_variable_set "@#{name}", fixture.find
- rescue FixtureClassNotFound
- nil
- end
+ fixtures.each do |name, fixture|
+ begin
+ object.instance_variable_set "@#{name}", fixture.find
+ rescue FixtureClassNotFound
+ nil
end
end
end
@@ -503,36 +502,56 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
def self.create_fixtures(fixtures_directory, table_names, class_names = {})
table_names = [table_names].flatten.map { |n| n.to_s }
- table_names.each { |n| class_names[n.tr('/', '_').to_sym] = n.classify if n.include?('/') }
- connection = block_given? ? yield : ActiveRecord::Base.connection
+ table_names.each { |n|
+ class_names[n.tr('/', '_').to_sym] = n.classify if n.include?('/')
+ }
- table_names_to_fetch = table_names.reject { |table_name| fixture_is_cached?(connection, table_name) }
+ # FIXME: Apparently JK uses this.
+ connection = block_given? ? yield : ActiveRecord::Base.connection
- unless table_names_to_fetch.empty?
- ActiveRecord::Base.silence do
- connection.disable_referential_integrity do
- fixtures_map = {}
+ files_to_read = table_names.reject { |table_name| fixture_is_cached?(connection, table_name) }
- fixtures = table_names_to_fetch.map do |table_name|
- fixtures_map[table_name] = Fixtures.new(connection, table_name.tr('/', '_'), class_names[table_name.tr('/', '_').to_sym], File.join(fixtures_directory, table_name))
- end
+ unless files_to_read.empty?
+ connection.disable_referential_integrity do
+ fixtures_map = {}
+
+ fixture_files = files_to_read.map do |path|
+ table_name = path.tr '/', '_'
+
+ fixtures_map[path] = Fixtures.new(
+ connection,
+ table_name,
+ class_names[table_name.to_sym],
+ File.join(fixtures_directory, path))
+ end
+
+ all_loaded_fixtures.update(fixtures_map)
- all_loaded_fixtures.update(fixtures_map)
+ connection.transaction(:requires_new => true) do
+ fixture_files.each do |ff|
+ conn = ff.model_class.respond_to?(:connection) ? ff.model_class.connection : connection
+ table_rows = ff.table_rows
- connection.transaction(:requires_new => true) do
- fixtures.reverse.each { |fixture| fixture.delete_existing_fixtures }
- fixtures.each { |fixture| fixture.insert_fixtures }
+ table_rows.keys.each do |table|
+ conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
+ end
- # Cap primary key sequences to max(pk).
- if connection.respond_to?(:reset_pk_sequence!)
- table_names.each do |table_name|
- connection.reset_pk_sequence!(table_name.tr('/', '_'))
+ table_rows.each do |table_name,rows|
+ rows.each do |row|
+ conn.insert_fixture(row, table_name)
end
end
end
- cache_fixtures(connection, fixtures_map)
+ # Cap primary key sequences to max(pk).
+ if connection.respond_to?(:reset_pk_sequence!)
+ table_names.each do |table_name|
+ connection.reset_pk_sequence!(table_name.tr('/', '_'))
+ end
+ end
end
+
+ cache_fixtures(connection, fixtures_map)
end
end
cached_fixtures(connection, table_names)
@@ -544,40 +563,59 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
Zlib.crc32(label.to_s) % MAX_ID
end
- attr_reader :table_name, :name
+ attr_reader :table_name, :name, :fixtures, :model_class
+
+ def initialize(connection, table_name, class_name, fixture_path)
+ @connection = connection
+ @table_name = table_name
+ @fixture_path = fixture_path
+ @name = table_name # preserve fixture base name
+ @class_name = class_name
+
+ @fixtures = ActiveSupport::OrderedHash.new
+ @table_name = "#{ActiveRecord::Base.table_name_prefix}#{@table_name}#{ActiveRecord::Base.table_name_suffix}"
+
+ # Should be an AR::Base type class
+ if class_name.is_a?(Class)
+ @table_name = class_name.table_name
+ @connection = class_name.connection
+ @model_class = class_name
+ else
+ @model_class = class_name.constantize rescue nil
+ end
- def initialize(connection, table_name, class_name, fixture_path, file_filter = DEFAULT_FILTER_RE)
- @connection, @table_name, @fixture_path, @file_filter = connection, table_name, fixture_path, file_filter
- @name = table_name # preserve fixture base name
- @class_name = class_name ||
- (ActiveRecord::Base.pluralize_table_names ? @table_name.singularize.camelize : @table_name.camelize)
- @table_name = "#{ActiveRecord::Base.table_name_prefix}#{@table_name}#{ActiveRecord::Base.table_name_suffix}"
- @table_name = class_name.table_name if class_name.respond_to?(:table_name)
- @connection = class_name.connection if class_name.respond_to?(:connection)
read_fixture_files
end
- def delete_existing_fixtures
- @connection.delete "DELETE FROM #{@connection.quote_table_name(table_name)}", 'Fixture Delete'
+ def [](x)
+ fixtures[x]
+ end
+
+ def []=(k,v)
+ fixtures[k] = v
+ end
+
+ def each(&block)
+ fixtures.each(&block)
+ end
+
+ def size
+ fixtures.size
end
- def insert_fixtures
+ # Return a hash of rows to be inserted. The key is the table, the value is
+ # a list of rows to insert to that table.
+ def table_rows
now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
now = now.to_s(:db)
# allow a standard key to be used for doing defaults in YAML
- if is_a?(Hash)
- delete('DEFAULTS')
- else
- delete(assoc('DEFAULTS'))
- end
+ fixtures.delete('DEFAULTS')
# track any join tables we need to insert later
- habtm_fixtures = Hash.new do |h, habtm|
- h[habtm] = HabtmFixtures.new(@connection, habtm.options[:join_table], nil, nil)
- end
+ rows = Hash.new { |h,table| h[table] = [] }
- each do |label, fixture|
+ rows[table_name] = fixtures.map do |label, fixture|
row = fixture.to_hash
if model_class && model_class < ActiveRecord::Base
@@ -613,14 +651,9 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
- if association.options[:polymorphic]
- if value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
- target_type = $1
- target_type_name = (association.options[:foreign_type] || "#{association.name}_type").to_s
-
- # support polymorphic belongs_to as "label (Type)"
- row[target_type_name] = target_type
- end
+ if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
+ # support polymorphic belongs_to as "label (Type)"
+ row[association.foreign_type] = $1
end
row[fk_name] = Fixtures.identify(value)
@@ -628,47 +661,22 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
when :has_and_belongs_to_many
if (targets = row.delete(association.name.to_s))
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
- join_fixtures = habtm_fixtures[association]
-
- targets.each do |target|
- join_fixtures["#{label}_#{target}"] = Fixture.new(
- { association.primary_key_name => row[primary_key_name],
- association.association_foreign_key => Fixtures.identify(target) },
- nil, @connection)
- end
+ table_name = association.options[:join_table]
+ rows[table_name].concat targets.map { |target|
+ { association.foreign_key => row[primary_key_name],
+ association.association_foreign_key => Fixtures.identify(target) }
+ }
end
end
end
end
- @connection.insert_fixture(fixture, @table_name)
- end
-
- # insert any HABTM join tables we discovered
- habtm_fixtures.values.each do |fixture|
- fixture.delete_existing_fixtures
- fixture.insert_fixtures
+ row
end
+ rows
end
private
- class HabtmFixtures < ::Fixtures #:nodoc:
- def read_fixture_files; end
- end
-
- def model_class
- unless defined?(@model_class)
- @model_class =
- if @class_name.nil? || @class_name.is_a?(Class)
- @class_name
- else
- @class_name.constantize rescue nil
- end
- end
-
- @model_class
- end
-
def primary_key_name
@primary_key_name ||= model_class && model_class.primary_key
end
@@ -688,7 +696,7 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
end
def column_names
- @column_names ||= @connection.columns(@table_name).collect(&:name)
+ @column_names ||= @connection.columns(@table_name).collect { |c| c.name }
end
def read_fixture_files
@@ -696,15 +704,15 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
read_yaml_fixture_files
elsif File.file?(csv_file_path)
read_csv_fixture_files
+ else
+ raise FixturesFileNotFound, "Could not find #{yaml_file_path} or #{csv_file_path}"
end
end
def read_yaml_fixture_files
- yaml_string = ""
- Dir["#{@fixture_path}/**/*.yml"].select { |f| test(?f, f) }.each do |subfixture_path|
- yaml_string << IO.read(subfixture_path)
- end
- yaml_string << IO.read(yaml_file_path)
+ yaml_string = (Dir["#{@fixture_path}/**/*.yml"].select { |f|
+ File.file?(f)
+ } + [yaml_file_path]).map { |file_path| IO.read(file_path) }.join
if yaml = parse_yaml_string(yaml_string)
# If the file is an ordered map, extract its children.
@@ -722,7 +730,7 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
raise Fixture::FormatError, "Bad data for #{@class_name} fixture named #{name} (nil)"
end
- self[name] = Fixture.new(data, model_class, @connection)
+ fixtures[name] = Fixture.new(data, model_class)
end
end
end
@@ -735,7 +743,7 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
reader.each do |row|
data = {}
row.each_with_index { |cell, j| data[header[j].to_s.strip] = cell.to_s.strip }
- self["#{@class_name.to_s.underscore}_#{i+=1}"] = Fixture.new(data, model_class, @connection)
+ fixtures["#{@class_name.to_s.underscore}_#{i+=1}"] = Fixture.new(data, model_class)
end
end
@@ -771,44 +779,30 @@ class Fixture #:nodoc:
class FormatError < FixtureError #:nodoc:
end
- attr_reader :model_class
+ attr_reader :model_class, :fixture
- def initialize(fixture, model_class, connection = ActiveRecord::Base.connection)
- @connection = connection
- @fixture = fixture
- @model_class = model_class.is_a?(Class) ? model_class : model_class.constantize rescue nil
+ def initialize(fixture, model_class)
+ @fixture = fixture
+ @model_class = model_class
end
def class_name
- @model_class.name if @model_class
+ model_class.name if model_class
end
def each
- @fixture.each { |item| yield item }
+ fixture.each { |item| yield item }
end
def [](key)
- @fixture[key]
- end
-
- def to_hash
- @fixture
+ fixture[key]
end
- def key_list
- @fixture.keys.map { |column_name| @connection.quote_column_name(column_name) }.join(', ')
- end
-
- def value_list
- cols = (model_class && model_class < ActiveRecord::Base) ? model_class.columns_hash : {}
- @fixture.map do |key, value|
- @connection.quote(value, cols[key]).gsub('[^\]\\n', "\n").gsub('[^\]\\r', "\r")
- end.join(', ')
- end
+ alias :to_hash :fixture
def find
if model_class
- model_class.find(self[model_class.primary_key])
+ model_class.find(fixture[model_class.primary_key])
else
raise FixtureClassNotFound, "No class attached to find."
end
@@ -823,19 +817,21 @@ module ActiveRecord
setup :setup_fixtures
teardown :teardown_fixtures
- superclass_delegating_accessor :fixture_path
- superclass_delegating_accessor :fixture_table_names
- superclass_delegating_accessor :fixture_class_names
- superclass_delegating_accessor :use_transactional_fixtures
- superclass_delegating_accessor :use_instantiated_fixtures # true, false, or :no_instances
- superclass_delegating_accessor :pre_loaded_fixtures
+ class_attribute :fixture_path
+ 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 = {}
+ self.fixture_class_names = Hash.new do |h, table_name|
+ h[table_name] = Fixtures.find_table_name(table_name)
+ end
end
module ClassMethods
@@ -843,17 +839,17 @@ module ActiveRecord
self.fixture_class_names = self.fixture_class_names.merge(class_names)
end
- def fixtures(*table_names)
- if table_names.first == :all
- table_names = Dir["#{fixture_path}/**/*.{yml,csv}"]
- table_names.map! { |f| f[(fixture_path.size + 1)..-5] }
+ def fixtures(*fixture_names)
+ if fixture_names.first == :all
+ fixture_names = Dir["#{fixture_path}/**/*.{yml,csv}"]
+ fixture_names.map! { |f| f[(fixture_path.size + 1)..-5] }
else
- table_names = table_names.flatten.map { |n| n.to_s }
+ fixture_names = fixture_names.flatten.map { |n| n.to_s }
end
- self.fixture_table_names |= table_names
- require_fixture_classes(table_names)
- setup_fixture_accessors(table_names)
+ self.fixture_table_names |= fixture_names
+ require_fixture_classes(fixture_names)
+ setup_fixture_accessors(fixture_names)
end
def try_to_load_dependency(file_name)
@@ -868,43 +864,48 @@ module ActiveRecord
end
end
- def require_fixture_classes(table_names = nil)
- (table_names || fixture_table_names).each do |table_name|
- file_name = table_name.to_s
+ def require_fixture_classes(fixture_names = nil)
+ (fixture_names || fixture_table_names).each do |fixture_name|
+ file_name = fixture_name.to_s
file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names
try_to_load_dependency(file_name)
end
end
- def setup_fixture_accessors(table_names = nil)
- table_names = Array.wrap(table_names || fixture_table_names)
- table_names.each do |table_name|
- table_name = table_name.to_s.tr('./', '_')
+ def setup_fixture_accessors(fixture_names = nil)
+ fixture_names = Array.wrap(fixture_names || fixture_table_names)
+ methods = Module.new do
+ fixture_names.each do |fixture_name|
+ fixture_name = fixture_name.to_s.tr('./', '_')
- redefine_method(table_name) do |*fixtures|
- force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload
+ define_method(fixture_name) do |*fixtures|
+ force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload
- @fixture_cache[table_name] ||= {}
+ @fixture_cache[fixture_name] ||= {}
- instances = fixtures.map do |fixture|
- @fixture_cache[table_name].delete(fixture) if force_reload
+ instances = fixtures.map do |fixture|
+ @fixture_cache[fixture_name].delete(fixture) if force_reload
- if @loaded_fixtures[table_name][fixture.to_s]
- @fixture_cache[table_name][fixture] ||= @loaded_fixtures[table_name][fixture.to_s].find
- else
- raise StandardError, "No fixture with name '#{fixture}' found for table '#{table_name}'"
+ if @loaded_fixtures[fixture_name][fixture.to_s]
+ ActiveRecord::IdentityMap.without do
+ @fixture_cache[fixture_name][fixture] ||= @loaded_fixtures[fixture_name][fixture.to_s].find
+ end
+ else
+ raise StandardError, "No fixture with name '#{fixture}' found for table '#{fixture_name}'"
+ end
end
- end
- instances.size == 1 ? instances.first : instances
+ instances.size == 1 ? instances.first : instances
+ end
+ private fixture_name
end
- private table_name
end
+ include methods
end
def uses_transaction(*methods)
@uses_transaction = [] unless defined?(@uses_transaction)
- @uses_transaction.concat methods.map(&:to_s)
+ @uses_transaction.concat methods.map { |m| m.to_s }
end
def uses_transaction?(method)
@@ -919,7 +920,7 @@ module ActiveRecord
end
def setup_fixtures
- return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
+ return unless !ActiveRecord::Base.configurations.blank?
if pre_loaded_fixtures && !use_transactional_fixtures
raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
@@ -933,7 +934,7 @@ module ActiveRecord
if @@already_loaded_fixtures[self.class]
@loaded_fixtures = @@already_loaded_fixtures[self.class]
else
- load_fixtures
+ @loaded_fixtures = load_fixtures
@@already_loaded_fixtures[self.class] = @loaded_fixtures
end
ActiveRecord::Base.connection.increment_open_transactions
@@ -943,7 +944,7 @@ module ActiveRecord
else
Fixtures.reset_cache
@@already_loaded_fixtures[self.class] = nil
- load_fixtures
+ @loaded_fixtures = load_fixtures
end
# Instantiate fixtures for every test if requested.
@@ -967,15 +968,8 @@ module ActiveRecord
private
def load_fixtures
- @loaded_fixtures = {}
fixtures = Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
- unless fixtures.nil?
- if fixtures.instance_of?(Fixtures)
- @loaded_fixtures[fixtures.name] = fixtures
- else
- fixtures.each { |f| @loaded_fixtures[f.name] = f }
- end
- end
+ Hash[fixtures.map { |f| [f.name, f] }]
end
# for pre_loaded_fixtures, only require the classes once. huge speed improvement
@@ -991,8 +985,8 @@ module ActiveRecord
Fixtures.instantiate_all_loaded_fixtures(self, load_instances?)
else
raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
- @loaded_fixtures.each do |table_name, fixtures|
- Fixtures.instantiate_fixtures(self, table_name, fixtures, load_instances?)
+ @loaded_fixtures.each do |fixture_name, fixtures|
+ Fixtures.instantiate_fixtures(self, fixture_name, fixtures, load_instances?)
end
end
end
diff --git a/activerecord/lib/active_record/identity_map.rb b/activerecord/lib/active_record/identity_map.rb
new file mode 100644
index 0000000000..d18b2b0a54
--- /dev/null
+++ b/activerecord/lib/active_record/identity_map.rb
@@ -0,0 +1,102 @@
+module ActiveRecord
+ # = Active Record Identity Map
+ #
+ # Ensures that each object gets loaded only once by keeping every loaded
+ # object in a map. Looks up objects using the map when referring to them.
+ #
+ # More information on Identity Map pattern:
+ # http://www.martinfowler.com/eaaCatalog/identityMap.html
+ #
+ # == Configuration
+ #
+ # In order to enable IdentityMap, set <tt>config.active_record.identity_map = true</tt>
+ # in your <tt>config/application.rb</tt> file.
+ #
+ # IdentityMap is disabled by default.
+ #
+ module IdentityMap
+ extend ActiveSupport::Concern
+
+ class << self
+ def enabled=(flag)
+ Thread.current[:identity_map_enabled] = flag
+ end
+
+ def enabled
+ Thread.current[:identity_map_enabled]
+ end
+ alias enabled? enabled
+
+ def repository
+ Thread.current[:identity_map] ||= Hash.new { |h,k| h[k] = {} }
+ end
+
+ def use
+ old, self.enabled = enabled, true
+
+ yield if block_given?
+ ensure
+ self.enabled = old
+ clear
+ end
+
+ def without
+ old, self.enabled = enabled, false
+
+ yield if block_given?
+ ensure
+ self.enabled = old
+ end
+
+ def get(klass, primary_key)
+ obj = repository[klass.symbolized_base_class][primary_key]
+ obj.is_a?(klass) ? obj : nil
+ end
+
+ def add(record)
+ repository[record.class.symbolized_base_class][record.id] = record
+ end
+
+ def remove(record)
+ repository[record.class.symbolized_base_class].delete(record.id)
+ end
+
+ def remove_by_id(symbolized_base_class, id)
+ repository[symbolized_base_class].delete(id)
+ end
+
+ def clear
+ repository.clear
+ end
+ end
+
+ # Reinitialize an Identity Map model object from +coder+.
+ # +coder+ must contain the attributes necessary for initializing an empty
+ # model object.
+ def reinit_with(coder)
+ @attributes_cache = {}
+ dirty = @changed_attributes.keys
+ @attributes.update(coder['attributes'].except(*dirty))
+ @changed_attributes.update(coder['attributes'].slice(*dirty))
+ @changed_attributes.delete_if{|k,v| v.eql? @attributes[k]}
+
+ set_serialized_attributes
+
+ run_callbacks :find
+
+ self
+ end
+
+ class Middleware
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ ActiveRecord::IdentityMap.use do
+ @app.call(env)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/locale/en.yml b/activerecord/lib/active_record/locale/en.yml
index a0e94cbec1..44328f63b6 100644
--- a/activerecord/lib/active_record/locale/en.yml
+++ b/activerecord/lib/active_record/locale/en.yml
@@ -22,7 +22,7 @@ en:
# attributes:
# login:
# blank: "This is a custom blank message for User login"
- # Will define custom blank validation message for User model and
+ # Will define custom blank validation message for User model and
# custom blank validation message for login attribute of User model.
#models:
@@ -31,7 +31,7 @@ en:
# 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,
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index b6f87a57b8..9a31675782 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -23,7 +23,7 @@ module ActiveRecord
# p2.first_name = "should fail"
# p2.save # Raises a ActiveRecord::StaleObjectError
#
- # Optimistic locking will also check for stale data when objects are destroyed. Example:
+ # Optimistic locking will also check for stale data when objects are destroyed. Example:
#
# p1 = Person.find(1)
# p2 = Person.find(1)
@@ -58,6 +58,12 @@ module ActiveRecord
end
private
+ def increment_lock
+ lock_col = self.class.locking_column
+ previous_lock_value = send(lock_col).to_i
+ send(lock_col + '=', previous_lock_value + 1)
+ end
+
def attributes_from_column_definition
result = super
@@ -70,7 +76,7 @@ module ActiveRecord
result[self.class.locking_column] ||= 0
end
- return result
+ result
end
def update(attribute_names = @attributes.keys) #:nodoc:
@@ -78,8 +84,8 @@ module ActiveRecord
return 0 if attribute_names.empty?
lock_col = self.class.locking_column
- previous_value = send(lock_col).to_i
- send(lock_col + '=', previous_value + 1)
+ previous_lock_value = send(lock_col).to_i
+ increment_lock
attribute_names += [lock_col]
attribute_names.uniq!
@@ -87,11 +93,13 @@ module ActiveRecord
begin
relation = self.class.unscoped
- affected_rows = relation.where(
+ stmt = relation.where(
relation.table[self.class.primary_key].eq(quoted_id).and(
- relation.table[self.class.locking_column].eq(quote_value(previous_value))
+ relation.table[lock_col].eq(quote_value(previous_lock_value))
)
- ).arel.update(arel_attributes_values(false, false, attribute_names))
+ ).arel.compile_update(arel_attributes_values(false, false, attribute_names))
+
+ affected_rows = connection.update stmt.to_sql
unless affected_rows == 1
raise ActiveRecord::StaleObjectError, "Attempted to update a stale object: #{self.class.name}"
@@ -101,7 +109,7 @@ module ActiveRecord
# If something went wrong, revert the version.
rescue Exception
- send(lock_col + '=', previous_value)
+ send(lock_col + '=', previous_lock_value)
raise
end
end
@@ -109,13 +117,11 @@ module ActiveRecord
def destroy #:nodoc:
return super unless locking_enabled?
- unless new_record?
- lock_col = self.class.locking_column
- previous_value = send(lock_col).to_i
-
+ if persisted?
table = self.class.arel_table
- predicate = table[self.class.primary_key].eq(id)
- predicate = predicate.and(table[self.class.locking_column].eq(previous_value))
+ lock_col = self.class.locking_column
+ predicate = table[self.class.primary_key].eq(id).
+ and(table[lock_col].eq(send(lock_col).to_i))
affected_rows = self.class.unscoped.where(predicate).delete_all
diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb
index fcc9ebb4af..862cf8f72a 100644
--- a/activerecord/lib/active_record/locking/pessimistic.rb
+++ b/activerecord/lib/active_record/locking/pessimistic.rb
@@ -9,13 +9,12 @@ module ActiveRecord
# 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'.
+ # of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
#
- # Example:
# Account.transaction do
# # select * from accounts where name = 'shugo' limit 1 for update
- # shugo = Account.find(:first, :conditions => "name = 'shugo'", :lock => true)
- # yuko = Account.find(:first, :conditions => "name = 'yuko'", :lock => true)
+ # shugo = Account.where("name = 'shugo'").lock(true).first
+ # yuko = Account.where("name = 'shugo'").lock(true).first
# shugo.balance -= 100
# shugo.save!
# yuko.balance += 100
@@ -24,9 +23,10 @@ module ActiveRecord
#
# You can also use ActiveRecord::Base#lock! 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.find(:all, :conditions => ...)
+ # accounts = Account.where(...).all
# account1 = accounts.detect { |account| ... }
# account2 = accounts.detect { |account| ... }
# # select * from accounts where id=? for update
@@ -40,14 +40,14 @@ module ActiveRecord
#
# Database-specific information on row locking:
# MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
- # PostgreSQL: http://www.postgresql.org/docs/8.1/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
+ # PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
module Pessimistic
# Obtain a row lock on this record. Reloads the record to obtain the requested
# lock. Pass an SQL locking clause to append the end of the SELECT statement
- # or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
+ # or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
# the locked record.
def lock!(lock = true)
- reload(:lock => lock) unless new_record?
+ reload(:lock => lock) if persisted?
self
end
end
diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb
index c7ae12977a..afadbf03ef 100644
--- a/activerecord/lib/active_record/log_subscriber.rb
+++ b/activerecord/lib/active_record/log_subscriber.rb
@@ -22,8 +22,16 @@ module ActiveRecord
self.class.runtime += event.duration
return unless logger.debug?
- name = '%s (%.1fms)' % [event.payload[:name], event.duration]
- sql = event.payload[:sql].squeeze(' ')
+ payload = event.payload
+ name = '%s (%.1fms)' % [payload[:name], event.duration]
+ sql = payload[:sql].squeeze(' ')
+ binds = nil
+
+ unless (payload[:binds] || []).empty?
+ binds = " " + payload[:binds].map { |col,v|
+ [col.name, v]
+ }.inspect
+ end
if odd?
name = color(name, CYAN, true)
@@ -32,7 +40,7 @@ module ActiveRecord
name = color(name, MAGENTA, true)
end
- debug " #{name} #{sql}"
+ debug " #{name} #{sql}#{binds}"
end
def odd?
@@ -45,4 +53,4 @@ module ActiveRecord
end
end
-ActiveRecord::LogSubscriber.attach_to :active_record \ No newline at end of file
+ActiveRecord::LogSubscriber.attach_to :active_record
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 5e272f0ba4..640111096d 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -1,5 +1,4 @@
-require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/module/aliasing'
+require "active_support/core_ext/array/wrap"
module ActiveRecord
# Exception that can be raised to stop migrations from going backwards.
@@ -31,39 +30,39 @@ module ActiveRecord
end
# = Active Record Migrations
- #
- # Migrations can manage the evolution of a schema used by several physical
+ #
+ # 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
+ # 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
+ # 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 self.up
+ # def up
# add_column :accounts, :ssl_enabled, :boolean, :default => 1
# end
#
- # def self.down
+ # 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 class methods +up+ and +down+ that describes the transformations
+ # 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 class 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
+ # 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 self.up
+ # def up
# create_table :system_settings do |t|
# t.string :name
# t.string :label
@@ -72,58 +71,58 @@ module ActiveRecord
# t.integer :position
# end
#
- # SystemSetting.create :name => "notice",
- # :label => "Use notice?",
+ # SystemSetting.create :name => "notice",
+ # :label => "Use notice?",
# :value => 1
# end
#
- # def self.down
+ # def down
# drop_table :system_settings
# end
# end
#
- # This migration first adds the system_settings table, then creates the very
+ # 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
+ # 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
+ # * <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
+ # 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>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
+ # * <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
+ # * <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>: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
+ # 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
+ # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
# the column to a different type using the same parameters as add_column.
- # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named
+ # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named
# +column_name+ from the table called +table_name+.
- # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
+ # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
# with the name of the column. Other options include
- # <tt>:name</tt> and <tt>:unique</tt> (e.g.
+ # <tt>:name</tt> and <tt>:unique</tt> (e.g.
# <tt>{ :name => "users_name_index", :unique => true }</tt>).
- # * <tt>remove_index(table_name, index_name)</tt>: Removes the index specified
+ # * <tt>remove_index(table_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>
+ # 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
@@ -134,11 +133,11 @@ module ActiveRecord
# 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
+ # 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>self.up</tt> and <tt>self.down</tt> methods of
+ # 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.
@@ -147,11 +146,11 @@ module ActiveRecord
#
# This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
# class AddFieldnameToTablename < ActiveRecord::Migration
- # def self.up
+ # def up
# add_column :tablenames, :fieldname, :string
# end
#
- # def self.down
+ # def down
# remove_column :tablenames, :fieldname
# end
# end
@@ -179,11 +178,11 @@ module ActiveRecord
# Not all migrations change the schema. Some just fix the data:
#
# class RemoveEmptyTags < ActiveRecord::Migration
- # def self.up
+ # def up
# Tag.find(:all).each { |tag| tag.destroy if tag.pages.empty? }
# end
#
- # def self.down
+ # def down
# # not much we can do to restore deleted data
# raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
# end
@@ -192,12 +191,12 @@ module ActiveRecord
# Others remove columns when they migrate up instead of down:
#
# class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
- # def self.up
+ # def up
# remove_column :items, :incomplete_items_count
# remove_column :items, :completed_items_count
# end
#
- # def self.down
+ # def down
# add_column :items, :incomplete_items_count
# add_column :items, :completed_items_count
# end
@@ -206,24 +205,24 @@ module ActiveRecord
# And sometimes you need to do something in SQL not abstracted directly by migrations:
#
# class MakeJoinUnique < ActiveRecord::Migration
- # def self.up
+ # def up
# execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
# end
#
- # def self.down
+ # 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
+ # 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 self.up
+ # def up
# add_column :people, :salary, :integer
# Person.reset_column_information
# Person.find(:all).each do |p|
@@ -243,7 +242,7 @@ module ActiveRecord
# You can also insert your own messages and benchmarks by using the +say_with_time+
# method:
#
- # def self.up
+ # def up
# ...
# say_with_time "Updating salaries..." do
# Person.find(:all).each do |p|
@@ -286,111 +285,216 @@ module ActiveRecord
#
# 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.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>.
class Migration
- @@verbose = true
- cattr_accessor :verbose
+ autoload :CommandRecorder, 'active_record/migration/command_recorder'
class << self
- def up_with_benchmarks #:nodoc:
- migrate(:up)
- end
-
- def down_with_benchmarks #:nodoc:
- migrate(:down)
- end
+ attr_accessor :delegate # :nodoc:
+ end
- # Execute this migration in the named direction
- def migrate(direction)
- return unless respond_to?(direction)
+ def self.method_missing(name, *args, &block) # :nodoc:
+ (delegate || superclass.delegate).send(name, *args, &block)
+ end
- case direction
- when :up then announce "migrating"
- when :down then announce "reverting"
- end
+ cattr_accessor :verbose
- result = nil
- time = Benchmark.measure { result = send("#{direction}_without_benchmarks") }
+ attr_accessor :name, :version
- case direction
- when :up then announce "migrated (%.4fs)" % time.real; write
- when :down then announce "reverted (%.4fs)" % time.real; write
- end
+ def initialize
+ @name = self.class.name
+ @version = nil
+ @connection = nil
+ end
- result
- end
+ # instantiate the delegate object after initialize is defined
+ self.verbose = true
+ self.delegate = new
- # Because the method added may do an alias_method, it can be invoked
- # recursively. We use @ignore_new_methods as a guard to indicate whether
- # it is safe for the call to proceed.
- def singleton_method_added(sym) #:nodoc:
- return if defined?(@ignore_new_methods) && @ignore_new_methods
+ def up
+ self.class.delegate = self
+ return unless self.class.respond_to?(:up)
+ self.class.up
+ end
- begin
- @ignore_new_methods = true
+ def down
+ self.class.delegate = self
+ return unless self.class.respond_to?(:down)
+ self.class.down
+ end
- case sym
- when :up, :down
- singleton_class.send(:alias_method_chain, sym, "benchmarks")
+ # 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|
+ @connection = conn
+ if respond_to?(:change)
+ if direction == :down
+ recorder = CommandRecorder.new(@connection)
+ suppress_messages do
+ @connection = recorder
+ change
+ end
+ @connection = conn
+ time = Benchmark.measure {
+ recorder.inverse.each do |cmd, args|
+ send(cmd, *args)
+ end
+ }
+ else
+ time = Benchmark.measure { change }
end
- ensure
- @ignore_new_methods = false
+ else
+ time = Benchmark.measure { send(direction) }
end
+ @connection = nil
end
- def write(text="")
- puts(text) if verbose
+ case direction
+ when :up then announce "migrated (%.4fs)" % time.real; write
+ when :down then announce "reverted (%.4fs)" % time.real; write
end
+ end
- def announce(message)
- version = defined?(@version) ? @version : nil
+ def write(text="")
+ puts(text) if verbose
+ end
- text = "#{version} #{name}: #{message}"
- length = [0, 75 - text.length].max
- write "== %s %s" % [text, "=" * length]
- 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(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 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 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 } * ', '
- def connection
- ActiveRecord::Base.connection
+ say_with_time "#{method}(#{arg_list})" do
+ unless arguments.empty? || method == :execute
+ arguments[0] = Migrator.proper_table_name(arguments.first)
+ 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 |name, path|
+ source_migrations = ActiveRecord::Migrator.migrations(path)
- def method_missing(method, *arguments, &block)
- arg_list = arguments.map(&:inspect) * ', '
+ source_migrations.each do |migration|
+ source = File.read(migration.filename)
+ source = "# This migration comes from #{name} (originally #{migration.version})\n#{source}"
- say_with_time "#{method}(#{arg_list})" do
- unless arguments.empty? || method == :execute
- arguments[0] = Migrator.proper_table_name(arguments.first)
+ if duplicate = destination_migrations.detect { |m| m.name == migration.name }
+ options[:on_skip].call(name, migration) if File.read(duplicate.filename) != source && options[:on_skip]
+ next
end
- connection.send(method, *arguments, &block)
+
+ migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
+ new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.rb")
+ old_path, migration.filename = migration.filename, new_path
+ last = migration
+
+ FileUtils.cp(old_path, migration.filename)
+ copied << migration
+ options[:on_copy].call(name, 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
end
# MigrationProxy is used to defer loading of the actual migration classes
# until they are needed
- class MigrationProxy
+ class MigrationProxy < Struct.new(:name, :version, :filename)
- attr_accessor :name, :version, :filename
+ def initialize(name, version, filename)
+ super
+ @migration = nil
+ end
+
+ def basename
+ File.basename(filename)
+ end
delegate :migrate, :announce, :write, :to=>:migration
@@ -402,47 +506,47 @@ module ActiveRecord
def load_migration
require(File.expand_path(filename))
- name.constantize
+ name.constantize.new
end
end
class Migrator#:nodoc:
class << self
- def migrate(migrations_path, target_version = nil)
+ attr_writer :migrations_paths
+ alias :migrations_path= :migrations_paths=
+
+ def migrate(migrations_paths, target_version = nil)
case
when target_version.nil?
- up(migrations_path, target_version)
+ up(migrations_paths, target_version)
when current_version == 0 && target_version == 0
+ []
when current_version > target_version
- down(migrations_path, target_version)
+ down(migrations_paths, target_version)
else
- up(migrations_path, target_version)
+ up(migrations_paths, target_version)
end
end
- def rollback(migrations_path, steps=1)
- move(:down, migrations_path, steps)
+ def rollback(migrations_paths, steps=1)
+ move(:down, migrations_paths, steps)
end
- def forward(migrations_path, steps=1)
- move(:up, migrations_path, steps)
+ def forward(migrations_paths, steps=1)
+ move(:up, migrations_paths, steps)
end
- def up(migrations_path, target_version = nil)
- self.new(:up, migrations_path, target_version).migrate
+ def up(migrations_paths, target_version = nil)
+ self.new(:up, migrations_paths, target_version).migrate
end
- def down(migrations_path, target_version = nil)
- self.new(:down, migrations_path, target_version).migrate
+ def down(migrations_paths, target_version = nil)
+ self.new(:down, migrations_paths, target_version).migrate
end
- def run(direction, migrations_path, target_version)
- self.new(direction, migrations_path, target_version).run
- end
-
- def migrations_path
- 'db/migrate'
+ def run(direction, migrations_paths, target_version)
+ self.new(direction, migrations_paths, target_version).run
end
def schema_migrations_table_name
@@ -451,7 +555,7 @@ module ActiveRecord
def get_all_versions
table = Arel::Table.new(schema_migrations_table_name)
- Base.connection.select_values(table.project(table['version']).to_sql).map(&:to_i).sort
+ Base.connection.select_values(table.project(table['version']).to_sql).map{ |v| v.to_i }.sort
end
def current_version
@@ -468,24 +572,59 @@ module ActiveRecord
name.table_name rescue "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}"
end
+ def migrations_paths
+ @migrations_paths ||= ['db/migrate']
+ # just to not break things if someone uses: migration_path = some_string
+ Array.wrap(@migrations_paths)
+ end
+
+ def migrations_path
+ migrations_paths.first
+ end
+
+ def migrations(paths)
+ paths = Array.wrap(paths)
+
+ files = Dir[*paths.map { |p| "#{p}/[0-9]*_*.rb" }]
+
+ seen = Hash.new false
+
+ migrations = files.map do |file|
+ version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first
+
+ raise IllegalMigrationNameError.new(file) unless version
+ version = version.to_i
+ name = name.camelize
+
+ raise DuplicateMigrationVersionError.new(version) if seen[version]
+ raise DuplicateMigrationNameError.new(name) if seen[name]
+
+ seen[version] = seen[name] = true
+
+ MigrationProxy.new(name, version, file)
+ end
+
+ migrations.sort_by(&:version)
+ end
+
private
- def move(direction, migrations_path, steps)
- migrator = self.new(direction, migrations_path)
+ def move(direction, migrations_paths, steps)
+ migrator = self.new(direction, 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_path, version)
+ send(direction, migrations_paths, version)
end
end
end
- def initialize(direction, migrations_path, target_version = nil)
+ def initialize(direction, migrations_paths, target_version = nil)
raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
Base.connection.initialize_schema_migrations_table
- @direction, @migrations_path, @target_version = direction, migrations_path, target_version
+ @direction, @migrations_paths, @target_version = direction, migrations_paths, target_version
end
def current_version
@@ -509,7 +648,7 @@ module ActiveRecord
current = migrations.detect { |m| m.version == current_version }
target = migrations.detect { |m| m.version == @target_version }
- if target.nil? && !@target_version.nil? && @target_version > 0
+ if target.nil? && @target_version && @target_version > 0
raise UnknownMigrationVersionError.new(@target_version)
end
@@ -518,16 +657,19 @@ module ActiveRecord
runnable = migrations[start..finish]
# skip the last migration if we're headed down, but not ALL the way down
- runnable.pop if down? && !target.nil?
+ runnable.pop if down? && target
+ ran = []
runnable.each do |migration|
Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
+ seen = migrated.include?(migration.version.to_i)
+
# On our way up, we skip migrating the ones we've already migrated
- next if up? && migrated.include?(migration.version.to_i)
+ next if up? && seen
# On our way down, we skip reverting the ones we've never migrated
- if down? && !migrated.include?(migration.version.to_i)
+ if down? && !seen
migration.announce 'never migrated, skipping'; migration.write
next
end
@@ -537,39 +679,18 @@ module ActiveRecord
migration.migrate(@direction)
record_version_state_after_migrating(migration.version)
end
+ ran << migration
rescue => e
canceled_msg = Base.connection.supports_ddl_transactions? ? "this and " : ""
raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
end
end
+ ran
end
def migrations
@migrations ||= begin
- files = Dir["#{@migrations_path}/[0-9]*_*.rb"]
-
- migrations = files.inject([]) do |klasses, file|
- version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first
-
- raise IllegalMigrationNameError.new(file) unless version
- version = version.to_i
-
- if klasses.detect { |m| m.version == version }
- raise DuplicateMigrationVersionError.new(version)
- end
-
- if klasses.detect { |m| m.name == name.camelize }
- raise DuplicateMigrationNameError.new(name.camelize)
- end
-
- migration = MigrationProxy.new
- migration.name = name.camelize
- migration.version = version
- migration.filename = file
- klasses << migration
- end
-
- migrations = migrations.sort_by(&:version)
+ migrations = self.class.migrations(@migrations_paths)
down? ? migrations.reverse : migrations
end
end
@@ -590,10 +711,12 @@ module ActiveRecord
@migrated_versions ||= []
if down?
@migrated_versions.delete(version)
- table.where(table["version"].eq(version.to_s)).delete
+ stmt = table.where(table["version"].eq(version.to_s)).compile_delete
+ Base.connection.delete stmt.to_sql
else
@migrated_versions.push(version).sort!
- table.insert table["version"] => version.to_s
+ stmt = table.compile_insert table["version"] => version.to_s
+ Base.connection.insert stmt.to_sql
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 0000000000..c9d57ce812
--- /dev/null
+++ b/activerecord/lib/active_record/migration/command_recorder.rb
@@ -0,0 +1,103 @@
+module ActiveRecord
+ class Migration
+ # ActiveRecord::Migration::CommandRecorder 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_timestamp
+ # * create_table
+ # * remove_timestamps
+ # * rename_column
+ # * rename_index
+ # * rename_table
+ class CommandRecorder
+ attr_accessor :commands, :delegate
+
+ def initialize(delegate = nil)
+ @commands = []
+ @delegate = delegate
+ end
+
+ # record +command+. +command+ should be a method name and arguments.
+ # For example:
+ #
+ # recorder.record(:method_name, [:arg1, arg2])
+ def record(*command)
+ @commands << command
+ end
+
+ # Returns a list that represents commands that are the inverse of the
+ # commands stored in +commands+. For example:
+ #
+ # recorder.record(:rename_table, [:old, :new])
+ # recorder.inverse # => [:rename_table, [:new, :old]]
+ #
+ # This method will raise an IrreversibleMigration exception if it cannot
+ # invert the +commands+.
+ def inverse
+ @commands.reverse.map { |name, args|
+ method = :"invert_#{name}"
+ raise IrreversibleMigration unless respond_to?(method, true)
+ send(method, args)
+ }
+ end
+
+ def respond_to?(*args) # :nodoc:
+ super || delegate.respond_to?(*args)
+ end
+
+ [:create_table, :rename_table, :add_column, :remove_column, :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps, :change_column, :change_column_default].each do |method|
+ class_eval <<-EOV, __FILE__, __LINE__ + 1
+ def #{method}(*args)
+ record(:"#{method}", args)
+ end
+ EOV
+ end
+
+ private
+
+ def invert_create_table(args)
+ [:drop_table, args]
+ end
+
+ def invert_rename_table(args)
+ [:rename_table, args.reverse]
+ end
+
+ def invert_add_column(args)
+ [:remove_column, args.first(2)]
+ end
+
+ def invert_rename_index(args)
+ [:rename_index, args.reverse]
+ end
+
+ def invert_rename_column(args)
+ [:rename_column, [args.first] + args.last(2).reverse]
+ end
+
+ def invert_add_index(args)
+ table, columns, _ = *args
+ [:remove_index, [table, {:column => columns}]]
+ end
+
+ def invert_remove_timestamps(args)
+ [:add_timestamps, args]
+ end
+
+ def invert_add_timestamps(args)
+ [:remove_timestamps, args]
+ end
+
+ # Forwards any missing method call to the \target.
+ def method_missing(method, *args, &block)
+ @delegate.send(method, *args, &block)
+ rescue NoMethodError => e
+ raise e, e.message.sub(/ for #<.*$/, " via proxy for #{@delegate}")
+ end
+
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb
index 0e560418dc..d291632260 100644
--- a/activerecord/lib/active_record/named_scope.rb
+++ b/activerecord/lib/active_record/named_scope.rb
@@ -2,12 +2,18 @@ require 'active_support/core_ext/array'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/class/attribute'
module ActiveRecord
# = Active Record Named \Scopes
module NamedScope
extend ActiveSupport::Concern
+ included do
+ class_attribute :scopes
+ self.scopes = {}
+ end
+
module ClassMethods
# Returns an anonymous \scope.
#
@@ -20,10 +26,10 @@ module ActiveRecord
# fruits = fruits.limit(10) if limited?
#
# Anonymous \scopes tend to be useful when procedurally generating complex
- # queries, where passing intermediate values (\scopes) around as first-class
+ # queries, where passing intermediate values (\scopes) around as first-class
# objects is convenient.
#
- # You can define a \scope that applies to all finders using
+ # You can define a \scope that applies to all finders using
# ActiveRecord::Base.default_scope.
def scoped(options = nil)
if options
@@ -33,10 +39,6 @@ module ActiveRecord
end
end
- def scopes
- read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
- 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>.
#
@@ -48,20 +50,20 @@ module ActiveRecord
# The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
# in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>.
#
- # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
- # resembles the association object constructed by a <tt>has_many</tt> 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;
+ # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
+ # resembles the association object constructed by a <tt>has_many</tt> 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 Shirt.red really was an Array.
#
- # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce
+ # 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
+ # 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
+ # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which
# the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If,
#
# class Person < ActiveRecord::Base
@@ -88,14 +90,22 @@ module ActiveRecord
# end
# end
# end
- def scope(name, scope_options = {}, &block)
+ #
+ # 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
+ def scope(name, scope_options = {})
name = name.to_sym
valid_scope_name?(name)
+ extension = Module.new(&Proc.new) if block_given?
- extension = Module.new(&block) if block_given?
-
- scopes[name] = lambda do |*args|
- options = scope_options.is_a?(Proc) ? scope_options.call(*args) : scope_options
+ scope_proc = lambda do |*args|
+ options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options
relation = if options.is_a?(Hash)
scoped.apply_finder_options(options)
@@ -108,12 +118,9 @@ module ActiveRecord
extension ? relation.extending(extension) : relation
end
- singleton_class.send(:redefine_method, name, &scopes[name])
- end
+ self.scopes = self.scopes.merge name => scope_proc
- def named_scope(*args, &block)
- ActiveSupport::Deprecation.warn("Base.named_scope has been deprecated, please use Base.scope instead", caller)
- scope(*args, &block)
+ singleton_class.send(:redefine_method, name, &scopes[name])
end
protected
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index e652296e2c..522c0cfc9f 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -2,6 +2,7 @@ require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/indifferent_access'
+require 'active_support/core_ext/class/attribute'
module ActiveRecord
module NestedAttributes #:nodoc:
@@ -11,7 +12,7 @@ module ActiveRecord
extend ActiveSupport::Concern
included do
- class_inheritable_accessor :nested_attributes_options, :instance_writer => false
+ class_attribute :nested_attributes_options, :instance_writer => false
self.nested_attributes_options = {}
end
@@ -25,7 +26,7 @@ module ActiveRecord
#
# 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>.
#
@@ -190,6 +191,34 @@ module ActiveRecord
# 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.
+ #
+ # === Using with attr_accessible
+ #
+ # The use of <tt>attr_accessible</tt> can interfere with nested attributes
+ # if you're not careful. For example, if the <tt>Member</tt> model above
+ # was using <tt>attr_accessible</tt> like this:
+ #
+ # attr_accessible :name
+ #
+ # You would need to modify it to look like this:
+ #
+ # attr_accessible :name, :posts_attributes
+ #
+ # === 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? { |_, value| value.blank? } }
@@ -240,7 +269,11 @@ module ActiveRecord
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)
# def pirate_attributes=(attributes)
@@ -287,18 +320,15 @@ module ActiveRecord
# 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 = nested_attributes_options[association_name]
+ options = self.nested_attributes_options[association_name]
attributes = attributes.with_indifferent_access
- check_existing_record = (options[:update_only] || !attributes['id'].blank?)
- if check_existing_record && (record = send(association_name)) &&
+ 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])
+ assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
- elsif attributes['id']
- existing_record = self.class.reflect_on_association(association_name).klass.find(attributes['id'])
- assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
- self.send(association_name.to_s+'=', existing_record)
+ 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}"
@@ -338,7 +368,7 @@ module ActiveRecord
# { :id => '2', :_destroy => true }
# ])
def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
- options = nested_attributes_options[association_name]
+ 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})"
@@ -349,16 +379,21 @@ module ActiveRecord
end
if attributes_collection.is_a? Hash
- attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
+ keys = attributes_collection.keys
+ attributes_collection = if keys.include?('id') || keys.include?(:id)
+ Array.wrap(attributes_collection)
+ else
+ attributes_collection.sort_by { |i, _| i.to_i }.map { |_, attributes| attributes }
+ end
end
- association = send(association_name)
+ association = association(association_name)
existing_records = if association.loaded?
- association.to_a
+ association.target
else
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
- attribute_ids.present? ? association.all(:conditions => {association.primary_key => attribute_ids}) : []
+ attribute_ids.empty? ? [] : association.scoped.where(association.klass.primary_key => attribute_ids)
end
attributes_collection.each do |attributes|
@@ -368,16 +403,31 @@ module ActiveRecord
unless reject_new_record?(association_name, attributes)
association.build(attributes.except(*UNASSIGNABLE_KEYS))
end
-
elsif existing_records.count == 0 #Existing record but not yet associated
existing_record = self.class.reflect_on_association(association_name).klass.find(attributes['id'])
- association.send(:add_record_to_target_with_callbacks, existing_record) unless association.loaded?
- assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
-
+ if !call_reject_if(association_name, attributes)
+ association.send(:add_record_to_target_with_callbacks, existing_record) if !association.loaded?
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
+ end
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
- association.send(:add_record_to_target_with_callbacks, existing_record) unless association.loaded?
- assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
+ unless association.loaded? || call_reject_if(association_name, attributes)
+ # Make sure we are operating on the actual object which is in the association's
+ # proxy_target array (either by finding it, or adding it if not found)
+ target_record = association.target.detect { |record| record == existing_record }
+
+ if target_record
+ existing_record = target_record
+ else
+ association.add_to_target(existing_record)
+ end
+ end
+
+ if !call_reject_if(association_name, attributes)
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
+ end
+ else
+ raise_nested_attributes_record_not_found(association_name, attributes['id'])
end
end
end
@@ -385,11 +435,8 @@ module ActiveRecord
# 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)
- if has_destroy_flag?(attributes) && allow_destroy
- record.mark_for_destruction
- else
- record.attributes = attributes.except(*UNASSIGNABLE_KEYS)
- end
+ record.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.
@@ -397,7 +444,7 @@ module ActiveRecord
ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
end
- # Determines if a new record should be built by checking for
+ # 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)
@@ -405,7 +452,7 @@ module ActiveRecord
end
def call_reject_if(association_name, attributes)
- case callback = nested_attributes_options[association_name][:reject_if]
+ case callback = self.nested_attributes_options[association_name][:reject_if]
when Symbol
method(callback).arity == 0 ? send(callback) : send(callback, attributes)
when Proc
@@ -413,5 +460,8 @@ module ActiveRecord
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/observer.rb b/activerecord/lib/active_record/observer.rb
index 78bac55bf2..0893d7e337 100644
--- a/activerecord/lib/active_record/observer.rb
+++ b/activerecord/lib/active_record/observer.rb
@@ -3,7 +3,7 @@ require 'active_support/core_ext/class/attribute'
module ActiveRecord
# = Active Record Observer
#
- # Observer classes respond to lifecycle callbacks to implement trigger-like
+ # Observer classes respond to life cycle callbacks to implement trigger-like
# behavior outside the original class. This is a great way to reduce the
# clutter that normally comes when the model class is burdened with
# functionality that doesn't pertain to the core responsibility of the
@@ -67,7 +67,7 @@ module ActiveRecord
#
# == Configuration
#
- # In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration
+ # In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration
# setting in your <tt>config/application.rb</tt> file.
#
# config.active_record.observers = :comment_observer, :signup_observer
@@ -89,50 +89,31 @@ module ActiveRecord
# singletons and that call instantiates and registers them.
#
class Observer < ActiveModel::Observer
- class_attribute :observed_methods
- self.observed_methods = [].freeze
-
- def initialize
- super
- observed_descendants.each { |klass| add_observer!(klass) }
- end
-
- def self.method_added(method)
- method = method.to_sym
-
- if ActiveRecord::Callbacks::CALLBACKS.include?(method)
- self.observed_methods += [method]
- self.observed_methods.freeze
- end
- end
protected
- def observed_descendants
- observed_classes.sum([]) { |klass| klass.descendants }
- end
-
- def observe_callbacks?
- self.class.observed_methods.any?
+ def observed_classes
+ klasses = super
+ klasses + klasses.map { |klass| klass.descendants }.flatten
end
def add_observer!(klass)
super
- define_callbacks klass if observe_callbacks?
+ define_callbacks klass
end
def define_callbacks(klass)
- existing_methods = klass.instance_methods.map(&:to_sym)
observer = self
observer_name = observer.class.name.underscore.gsub('/', '__')
- self.class.observed_methods.each do |method|
- callback = :"_notify_#{observer_name}_for_#{method}"
- unless existing_methods.include? callback
- klass.send(:define_method, callback) do # def _notify_user_observer_for_before_save
- observer.update(method, self) # observer.update(:before_save, self)
- end # end
- klass.send(method, callback) # before_save :_notify_user_observer_for_before_save
+ ActiveRecord::Callbacks::CALLBACKS.each do |callback|
+ next unless respond_to?(callback)
+ callback_meth = :"_notify_#{observer_name}_for_#{callback}"
+ unless klass.respond_to?(callback_meth)
+ klass.send(:define_method, callback_meth) do
+ observer.send(callback, self)
+ end
+ klass.send(callback, callback_meth)
end
end
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 71b46beaef..17a64b6e86 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -1,7 +1,7 @@
module ActiveRecord
# = Active Record Persistence
module Persistence
- # Returns true if this object hasn't been saved yet -- that is, a record
+ # 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?
@new_record
@@ -18,9 +18,6 @@ module ActiveRecord
!(new_record? || destroyed?)
end
- # :call-seq:
- # save(options)
- #
# Saves the model.
#
# If the model is new a record gets created in the database, otherwise
@@ -67,15 +64,19 @@ module ActiveRecord
# callbacks, Observer methods, or any <tt>:dependent</tt> association
# options, use <tt>#destroy</tt>.
def delete
- self.class.delete(id) if persisted?
+ if persisted?
+ self.class.delete(id)
+ IdentityMap.remove(self) if IdentityMap.enabled?
+ end
@destroyed = true
freeze
end
- # Deletes the record in the database and freezes this instance to reflect
+ # Deletes the record in the database and freezes this instance to reflect
# that no changes should be made (since they can't be persisted).
def destroy
if persisted?
+ IdentityMap.remove(self) if IdentityMap.enabled?
self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).delete_all
end
@@ -83,15 +84,15 @@ module ActiveRecord
freeze
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
+ # 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.
+ # 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
@@ -99,37 +100,23 @@ module ActiveRecord
became.instance_variable_set("@attributes_cache", @attributes_cache)
became.instance_variable_set("@new_record", new_record?)
became.instance_variable_set("@destroyed", destroyed?)
+ became.type = klass.name unless self.class.descends_from_active_record?
became
end
- # Updates a single attribute and saves the record.
+ # Updates a single attribute and saves the record.
# This is especially useful for boolean flags on existing records. Also note that
#
- # * The attribute being updated must be a column name.
# * Validation is skipped.
- # * No callbacks are invoked.
+ # * Callbacks are invoked.
# * updated_at/updated_on column is updated if that column is available.
- # * Does not work on associations.
- # * Does not work on attr_accessor attributes.
- # * Does not work on new record. <tt>record.new_record?</tt> should return false for this method to work.
- # * Updates only the attribute that is input to the method. If there are other changed attributes then
- # those attributes are left alone. In that case even after this method has done its work <tt>record.changed?</tt>
- # will return true.
+ # * Updates all the attributes that are dirty in this object.
#
def update_attribute(name, value)
- raise ActiveRecordError, "#{name.to_s} is marked as readonly" if self.class.readonly_attributes.include? name.to_s
-
- changes = record_update_timestamps || {}
-
- if name
- name = name.to_s
- send("#{name}=", value)
- changes[name] = read_attribute(name)
- end
-
- @changed_attributes.except!(*changes.keys)
- primary_key = self.class.primary_key
- self.class.update_all(changes, { primary_key => self[primary_key] }) == 1
+ name = name.to_s
+ raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
+ send("#{name}=", value)
+ save(:validate => false)
end
# Updates the attributes of the model from the passed-in hash and saves the
@@ -213,22 +200,54 @@ module ActiveRecord
def reload(options = nil)
clear_aggregation_cache
clear_association_cache
- @attributes.update(self.class.unscoped { self.class.find(self.id, options) }.instance_variable_get('@attributes'))
+
+ IdentityMap.without do
+ fresh_object = self.class.unscoped { self.class.find(self.id, options) }
+ @attributes.update(fresh_object.instance_variable_get('@attributes'))
+ end
+
@attributes_cache = {}
self
end
# 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
+ # If an attribute name is passed, that attribute is updated along with
# updated_at/on attributes.
#
- # Examples:
- #
# product.touch # updates updated_at/on
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
- def touch(attribute = nil)
- update_attribute(attribute, current_time_from_proper_timezone)
+ #
+ # 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
+ def touch(name = nil)
+ attributes = timestamp_attributes_for_update_in_model
+ attributes << name if name
+
+ unless attributes.empty?
+ current_time = current_time_from_proper_timezone
+ changes = {}
+
+ attributes.each do |column|
+ changes[column.to_s] = write_attribute(column.to_s, current_time)
+ end
+
+ changes[self.class.locking_column] = increment_lock if locking_enabled?
+
+ @changed_attributes.except!(*changes.keys)
+ primary_key = self.class.primary_key
+ self.class.update_all(changes, { primary_key => self[primary_key] }) == 1
+ end
end
private
@@ -243,26 +262,21 @@ module ActiveRecord
def update(attribute_names = @attributes.keys)
attributes_with_values = arel_attributes_values(false, false, attribute_names)
return 0 if attributes_with_values.empty?
- self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).arel.update(attributes_with_values)
+ klass = self.class
+ stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
+ klass.connection.update stmt.to_sql
end
# Creates a record with values matching those of the instance attributes
# and returns its id.
def create
- if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
- self.id = connection.next_sequence_value(self.class.sequence_name)
- end
+ attributes_values = arel_attributes_values(!id.nil?)
- attributes_values = arel_attributes_values
-
- new_id = if attributes_values.empty?
- self.class.unscoped.insert connection.empty_insert_statement_value
- else
- self.class.unscoped.insert attributes_values
- end
+ new_id = self.class.unscoped.insert attributes_values
self.id ||= new_id
+ IdentityMap.add(self) if IdentityMap.enabled?
@new_record = false
id
end
@@ -272,10 +286,9 @@ module ActiveRecord
# that a new instance, or one populated from a passed-in Hash, still has all the attributes
# that instances loaded from the database would.
def attributes_from_column_definition
- self.class.columns.inject({}) do |attributes, column|
- attributes[column.name] = column.default unless column.name == self.class.primary_key
- attributes
- end
+ Hash[self.class.columns.map do |column|
+ [column.name, column.default]
+ end]
end
end
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index 78fdb77216..cace6f0cc0 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -13,10 +13,14 @@ module ActiveRecord
class Railtie < Rails::Railtie
config.active_record = ActiveSupport::OrderedOptions.new
- config.generators.orm :active_record, :migration => true,
- :timestamps => true
+ 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::QueryCache"
+
+ config.app_middleware.insert_after "::ActionDispatch::Callbacks",
+ "ActiveRecord::ConnectionAdapters::ConnectionManagement"
rake_tasks do
load "active_record/railties/databases.rake"
@@ -39,6 +43,11 @@ module ActiveRecord
ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
end
+ initializer "active_record.identity_map" do |app|
+ config.app_middleware.insert_after "::ActionDispatch::Callbacks",
+ "ActiveRecord::IdentityMap::Middleware" if config.active_record.delete(:identity_map)
+ end
+
initializer "active_record.set_configs" do |app|
ActiveSupport.on_load(:active_record) do
app.config.active_record.each do |k,v|
@@ -65,27 +74,19 @@ module ActiveRecord
end
initializer "active_record.set_dispatch_hooks", :before => :set_clear_dependencies_hook do |app|
- unless app.config.cache_classes
- ActiveSupport.on_load(:active_record) do
- ActionDispatch::Callbacks.after do
- ActiveRecord::Base.clear_reloadable_connections!
- end
+ ActiveSupport.on_load(:active_record) do
+ ActionDispatch::Reloader.to_cleanup do
+ ActiveRecord::Base.clear_reloadable_connections!
+ ActiveRecord::Base.clear_cache!
end
end
end
- initializer "active_record.add_concurrency_middleware" do |app|
- if app.config.allow_concurrency
- app.config.middleware.insert_after "::ActionDispatch::Callbacks",
- "ActiveRecord::ConnectionAdapters::ConnectionManagement"
- end
- end
-
config.after_initialize do
ActiveSupport.on_load(:active_record) do
instantiate_observers
- ActionDispatch::Callbacks.to_prepare(:activerecord_instantiate_observers) do
+ ActionDispatch::Reloader.to_prepare do
ActiveRecord::Base.instantiate_observers
end
end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index ae605d3e7a..ff36814684 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -1,7 +1,14 @@
-namespace :db do
+db_namespace = namespace :db do
task :load_config => :rails_env do
require 'active_record'
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
+ ActiveRecord::Migrator.migrations_paths = Rails.application.paths["db/migrate"].to_a
+
+ if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
+ if engine.paths["db/migrate"].existent
+ ActiveRecord::Migrator.migrations_paths += engine.paths["db/migrate"].to_a
+ end
+ end
end
namespace :create do
@@ -45,8 +52,8 @@ namespace :db do
# Create the SQLite database
ActiveRecord::Base.establish_connection(config)
ActiveRecord::Base.connection
- rescue
- $stderr.puts $!, *($!.backtrace)
+ rescue Exception => e
+ $stderr.puts e, *(e.backtrace)
$stderr.puts "Couldn't create database for #{config.inspect}"
end
end
@@ -61,12 +68,14 @@ namespace :db do
@charset = ENV['CHARSET'] || 'utf8'
@collation = ENV['COLLATION'] || 'utf8_unicode_ci'
creation_options = {:charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation)}
+ error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
+ access_denied_error = 1045
begin
ActiveRecord::Base.establish_connection(config.merge('database' => nil))
ActiveRecord::Base.connection.create_database(config['database'], creation_options)
ActiveRecord::Base.establish_connection(config)
- rescue Mysql::Error => sqlerr
- if sqlerr.errno == Mysql::Error::ER_ACCESS_DENIED_ERROR
+ rescue error_class => sqlerr
+ if sqlerr.errno == access_denied_error
print "#{sqlerr.error}. \nPlease provide the root password for your mysql installation\n>"
root_password = $stdin.gets.strip
grant_statement = "GRANT ALL PRIVILEGES ON #{config['database']}.* " \
@@ -84,13 +93,13 @@ namespace :db do
end
end
when 'postgresql'
- @encoding = config[:encoding] || ENV['CHARSET'] || 'utf8'
+ @encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
begin
ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
ActiveRecord::Base.establish_connection(config)
- rescue
- $stderr.puts $!, *($!.backtrace)
+ rescue Exception => e
+ $stderr.puts e, *(e.backtrace)
$stderr.puts "Couldn't create database for #{config.inspect}"
end
end
@@ -135,21 +144,21 @@ namespace :db do
desc "Migrate the database (options: VERSION=x, VERBOSE=false)."
- task :migrate => :environment do
+ task :migrate => [:environment, :load_config] do
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
- ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
- Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
+ ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
+ db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
namespace :migrate do
# desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
- task :redo => :environment do
+ task :redo => [:environment, :load_config] do
if ENV["VERSION"]
- Rake::Task["db:migrate:down"].invoke
- Rake::Task["db:migrate:up"].invoke
+ db_namespace["migrate:down"].invoke
+ db_namespace["migrate:up"].invoke
else
- Rake::Task["db:rollback"].invoke
- Rake::Task["db:migrate"].invoke
+ db_namespace["rollback"].invoke
+ db_namespace["migrate"].invoke
end
end
@@ -157,23 +166,23 @@ namespace :db do
task :reset => ["db:drop", "db:create", "db:migrate"]
# desc 'Runs the "up" for a given migration VERSION.'
- task :up => :environment do
+ task :up => [:environment, :load_config] do
version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
raise "VERSION is required" unless version
- ActiveRecord::Migrator.run(:up, "db/migrate/", version)
- Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
+ ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version)
+ db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
# desc 'Runs the "down" for a given migration VERSION.'
- task :down => :environment do
+ task :down => [:environment, :load_config] do
version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
raise "VERSION is required" unless version
- ActiveRecord::Migrator.run(:down, "db/migrate/", version)
- Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
+ ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_paths, version)
+ db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
desc "Display status of migrations"
- task :status => :environment do
+ task :status => [:environment, :load_config] do
config = ActiveRecord::Base.configurations[Rails.env || 'development']
ActiveRecord::Base.establish_connection(config)
unless ActiveRecord::Base.connection.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
@@ -184,7 +193,7 @@ namespace :db do
file_list = []
Dir.foreach(File.join(Rails.root, 'db', 'migrate')) do |file|
# only files matching "20091231235959_some_name.rb" pattern
- if match_data = /(\d{14})_(.+)\.rb/.match(file)
+ if match_data = /^(\d{14})_(.+)\.rb$/.match(file)
status = db_list.delete(match_data[1]) ? 'up' : 'down'
file_list << [status, match_data[1], match_data[2]]
end
@@ -204,17 +213,17 @@ namespace :db do
end
desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
- task :rollback => :environment do
+ task :rollback => [:environment, :load_config] do
step = ENV['STEP'] ? ENV['STEP'].to_i : 1
- ActiveRecord::Migrator.rollback('db/migrate/', step)
- Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
+ ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
+ db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
# desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
- task :forward => :environment do
+ task :forward => [:environment, :load_config] do
step = ENV['STEP'] ? ENV['STEP'].to_i : 1
- ActiveRecord::Migrator.forward('db/migrate/', step)
- Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
+ ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step)
+ db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
# desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
@@ -258,7 +267,7 @@ namespace :db do
# desc "Raises an error if there are pending migrations"
task :abort_if_pending_migrations => :environment do
if defined? ActiveRecord
- pending_migrations = ActiveRecord::Migrator.new(:up, 'db/migrate').pending_migrations
+ pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations
if pending_migrations.any?
puts "You have #{pending_migrations.size} pending migrations:"
@@ -275,8 +284,7 @@ namespace :db do
desc 'Load the seed data from db/seeds.rb'
task :seed => 'db:abort_if_pending_migrations' do
- seed_file = File.join(Rails.root, 'db', 'seeds.rb')
- load(seed_file) if File.exist?(seed_file)
+ Rails.application.load_seed
end
namespace :fixtures do
@@ -288,8 +296,8 @@ namespace :db do
base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
- (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir["#{fixtures_dir}/**/*.{yml,csv}"]).each do |fixture_file|
- Fixtures.create_fixtures(fixtures_dir, fixture_file[(fixtures_dir.size + 1)..-5])
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.{yml,csv}"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
+ Fixtures.create_fixtures(fixtures_dir, fixture_file)
end
end
@@ -319,12 +327,12 @@ namespace :db do
namespace :schema do
desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
- task :dump => :environment do
+ task :dump => :load_config do
require 'active_record/schema_dumper'
File.open(ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb", "w") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
- Rake::Task["db:schema:dump"].reenable
+ db_namespace["schema:dump"].reenable
end
desc "Load a schema.rb file into the database"
@@ -333,7 +341,7 @@ namespace :db do
if File.exists?(file)
load(file)
else
- abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/boot.rb to limit the frameworks that will be loaded}
+ abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded}
end
end
end
@@ -367,7 +375,7 @@ namespace :db do
db_string = firebird_db_string(abcs[Rails.env])
sh "isql -a #{db_string} > #{Rails.root}/db/#{Rails.env}_structure.sql"
else
- raise "Task not supported by '#{abcs["test"]["adapter"]}'"
+ raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'"
end
if ActiveRecord::Base.connection.supports_migrations?
@@ -381,7 +389,7 @@ namespace :db do
task :load => 'db:test:purge' do
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
ActiveRecord::Schema.verbose = false
- Rake::Task["db:schema:load"].invoke
+ db_namespace["schema:load"].invoke
end
# desc "Recreate the test database from the current environment's database schema"
@@ -401,7 +409,7 @@ namespace :db do
ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
- `psql -U "#{abcs["test"]["username"]}" -f #{Rails.root}/db/#{Rails.env}_structure.sql #{abcs["test"]["database"]}`
+ `psql -U "#{abcs["test"]["username"]}" -f #{Rails.root}/db/#{Rails.env}_structure.sql #{abcs["test"]["database"]} #{abcs["test"]["template"]}`
when "sqlite", "sqlite3"
dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
`#{abcs["test"]["adapter"]} #{dbfile} < #{Rails.root}/db/#{Rails.env}_structure.sql`
@@ -455,7 +463,7 @@ namespace :db do
# desc 'Check for pending migrations and load the test schema'
task :prepare => 'db:abort_if_pending_migrations' do
if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
- Rake::Task[{ :sql => "db:test:clone_structure", :ruby => "db:test:load" }[ActiveRecord::Base.schema_format]].invoke
+ db_namespace[{ :sql => "test:clone_structure", :ruby => "test:load" }[ActiveRecord::Base.schema_format]].invoke
end
end
end
@@ -477,6 +485,34 @@ namespace :db do
end
end
+namespace :railties do
+ namespace :install do
+ # desc "Copies missing migrations from Railties (e.g. plugins, 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.all 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, old_path|
+ 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'
def drop_database(config)
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 7f47a812eb..e801bc4afa 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -1,10 +1,18 @@
+require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/module/deprecation'
+
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,
+ # 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.
@@ -20,36 +28,27 @@ module ActiveRecord
when :composed_of
reflection = AggregateReflection.new(macro, name, options, active_record)
end
- write_inheritable_hash :reflections, name => reflection
- reflection
- end
- # Returns a hash containing all AssociationReflection objects for the current class.
- # Example:
- #
- # Invoice.reflections
- # Account.reflections
- #
- def reflections
- read_inheritable_attribute(:reflections) || write_inheritable_attribute(:reflections, {})
+ 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.select { |reflection| reflection.is_a?(AggregateReflection) }
+ reflections.values.grep(AggregateReflection)
end
- # Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
+ # Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
#
- # Account.reflect_on_aggregation(:balance) #=> the balance AggregateReflection
+ # Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
#
def reflect_on_aggregation(aggregation)
reflections[aggregation].is_a?(AggregateReflection) ? reflections[aggregation] : nil
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>,
+ # 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:
@@ -58,7 +57,7 @@ module ActiveRecord
# 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.select { |reflection| reflection.is_a?(AssociationReflection) }
+ association_reflections = reflections.values.grep(AssociationReflection)
macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
end
@@ -78,7 +77,7 @@ module ActiveRecord
end
- # Abstract base class for AggregateReflection and AssociationReflection. Objects of
+ # Abstract base class for AggregateReflection and AssociationReflection. Objects of
# AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
class MacroReflection
attr_reader :active_record
@@ -89,23 +88,23 @@ module ActiveRecord
# Returns the name of the macro.
#
- # <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>:balance</tt>
+ # <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.
+ # 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
- # Returns the hash of options used for the macro.
+ # 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
- # Returns the class for the macro.
+ # 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
@@ -113,7 +112,7 @@ module ActiveRecord
@klass ||= class_name.constantize
end
- # Returns the class name for the macro.
+ # 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>
@@ -138,12 +137,12 @@ module ActiveRecord
end
- # Holds all the meta-data about an aggregation as it was specified in the
+ # Holds all the meta-data about an aggregation as it was specified in the
# Active Record class.
class AggregateReflection < MacroReflection #:nodoc:
end
- # Holds all the meta-data about an association as it was specified in the
+ # 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.
@@ -198,8 +197,21 @@ module ActiveRecord
@quoted_table_name ||= klass.quoted_table_name
end
+ def foreign_key
+ @foreign_key ||= options[:foreign_key] || derive_foreign_key
+ end
+
def primary_key_name
- @primary_key_name ||= options[:foreign_key] || derive_primary_key_name
+ foreign_key
+ end
+ deprecate :primary_key_name => :foreign_key
+
+ def foreign_type
+ @foreign_type ||= options[:foreign_type] || "#{name}_type"
+ end
+
+ def type
+ @type ||= "#{options[:as]}_type"
end
def primary_key_column
@@ -207,7 +219,18 @@ module ActiveRecord
end
def association_foreign_key
- @association_foreign_key ||= @options[:association_foreign_key] || class_name.foreign_key
+ @association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
+ end
+
+ def association_primary_key
+ @association_primary_key ||=
+ options[:primary_key] ||
+ !options[:polymorphic] && klass.primary_key ||
+ 'id'
+ end
+
+ def active_record_primary_key
+ @active_record_primary_key ||= options[:primary_key] || active_record.primary_key
end
def counter_cache_column
@@ -239,18 +262,32 @@ module ActiveRecord
end
def through_reflection
- false
- end
-
- def through_reflection_primary_key_name
+ 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
+
+ # An array of arrays of conditions. Each item in the outside array corresponds to a reflection
+ # in the #chain. The inside arrays are simply conditions (and each condition may itself be
+ # a hash, array, arel predicate, etc...)
+ def conditions
+ conditions = [options[:conditions]].compact
+ conditions << { type => active_record.base_class.name } if options[:as]
+ [conditions]
+ end
+
+ alias :source_macro :macro
+
def has_inverse?
- !@options[:inverse_of].nil?
+ @options[:inverse_of]
end
def inverse_of
@@ -289,22 +326,36 @@ module ActiveRecord
!options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
end
- def dependent_conditions(record, base_class, extra_conditions)
- dependent_conditions = []
- dependent_conditions << "#{primary_key_name} = #{record.send(name).send(:owner_quoted_id)}"
- dependent_conditions << "#{options[:as]}_type = '#{base_class.name}'" if options[:as]
- dependent_conditions << klass.send(:sanitize_sql, options[:conditions]) if options[:conditions]
- dependent_conditions << extra_conditions if extra_conditions
- dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ")
- dependent_conditions = dependent_conditions.gsub('@', '\@')
- dependent_conditions
- end
-
# Returns +true+ if +self+ is a +belongs_to+ reflection.
def belongs_to?
macro == :belongs_to
end
+ def association_class
+ case macro
+ when :belongs_to
+ if options[:polymorphic]
+ Associations::BelongsToPolymorphicAssociation
+ else
+ Associations::BelongsToAssociation
+ end
+ when :has_and_belongs_to_many
+ Associations::HasAndBelongsToManyAssociation
+ when :has_many
+ if options[:through]
+ Associations::HasManyThroughAssociation
+ else
+ Associations::HasManyAssociation
+ end
+ when :has_one
+ if options[:through]
+ Associations::HasOneThroughAssociation
+ else
+ Associations::HasOneAssociation
+ end
+ end
+ end
+
private
def derive_class_name
class_name = name.to_s.camelize
@@ -312,7 +363,7 @@ module ActiveRecord
class_name
end
- def derive_primary_key_name
+ def derive_foreign_key
if belongs_to?
"#{name}_id"
elsif options[:as]
@@ -326,6 +377,8 @@ module ActiveRecord
# Holds all the meta-data about a :through association as it was specified
# in the Active Record class.
class ThroughReflection < AssociationReflection #:nodoc:
+ delegate :foreign_key, :foreign_type, :association_foreign_key, :active_record_primary_key, :to => :source_reflection
+
# Gets the source of the through reflection. It checks both a singularized
# and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
#
@@ -353,6 +406,88 @@ module ActiveRecord
@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.
+ 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 conditions on Person.comment_tags, Article.comment_tags and/or Comment.tags,
+ # but only Comment.tags will be represented in the #chain. So this method creates an array
+ # of conditions corresponding to the chain. Each item in the #conditions array corresponds
+ # to an item in the #chain, and is itself an array of conditions from an arbitrary number
+ # of relevant reflections, plus any :source_type or polymorphic :as constraints.
+ def conditions
+ @conditions ||= begin
+ conditions = source_reflection.conditions
+
+ # Add to it the conditions from this reflection if necessary.
+ conditions.first << options[:conditions] if options[:conditions]
+
+ through_conditions = through_reflection.conditions
+
+ if options[:source_type]
+ through_conditions.first << { foreign_type => options[:source_type] }
+ end
+
+ # Recursively fill out the rest of the array from the through reflection
+ conditions += through_conditions
+
+ # And return
+ conditions
+ end
+ end
+
+ # The macro used by the source association
+ def source_macro
+ source_reflection.source_macro
+ end
+
+ # A through association is nested iff 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
+ @association_primary_key ||= begin
+ # Get the "actual" source reflection if the immediate source reflection has a
+ # source reflection itself
+ source_reflection = self.source_reflection
+ while source_reflection.source_reflection
+ source_reflection = source_reflection.source_reflection
+ end
+
+ source_reflection.options[:primary_key] || klass.primary_key
+ end
+ end
+
# Gets an array of possible <tt>:through</tt> source reflection names:
#
# [:singularized, :pluralized]
@@ -361,11 +496,23 @@ module ActiveRecord
@source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
end
+ def source_options
+ source_reflection.options
+ end
+
+ def through_options
+ through_reflection.options
+ end
+
def check_validity!
if through_reflection.nil?
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
end
+ if through_reflection.options[:polymorphic]
+ raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
+ end
+
if source_reflection.nil?
raise HasManyThroughSourceAssociationNotFoundError.new(self)
end
@@ -375,24 +522,16 @@ module ActiveRecord
end
if source_reflection.options[:polymorphic] && options[:source_type].nil?
- raise HasManyThroughAssociationPolymorphicError.new(active_record.name, self, source_reflection)
+ raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
end
- unless [:belongs_to, :has_many, :has_one].include?(source_reflection.macro) && source_reflection.options[:through].nil?
- raise HasManyThroughSourceAssociationMacroError.new(self)
+ if macro == :has_one && through_reflection.collection?
+ raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
end
check_validity_of_inverse!
end
- def through_reflection_primary_key
- through_reflection.belongs_to? ? through_reflection.klass.primary_key : through_reflection.primary_key_name
- end
-
- def through_reflection_primary_key_name
- through_reflection.primary_key_name if through_reflection.belongs_to?
- end
-
private
def derive_class_name
# get the class_name of the belongs_to association of the through reflection
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 30be723291..8e545f9cad 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -5,13 +5,14 @@ module ActiveRecord
class Relation
JoinOperation = Struct.new(:relation, :join_class, :on)
ASSOCIATION_METHODS = [:includes, :eager_load, :preload]
- MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having]
+ MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind]
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :create_with, :from]
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches
+ # These are explicitly delegated to improve performance (avoids method_missing)
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a
- delegate :insert, :to => :arel
+ delegate :table_name, :primary_key, :to => :klass
attr_reader :table, :klass, :loaded
attr_accessor :extensions
@@ -28,6 +29,36 @@ module ActiveRecord
@extensions = []
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
+
+ if values.empty? # empty insert
+ im.values = im.create_values [connection.null_insert_value], []
+ else
+ im.insert values
+ end
+
+ @klass.connection.insert(
+ im.to_sql,
+ 'SQL',
+ primary_key,
+ primary_key_value)
+ end
+
def new(*args, &block)
scoping { @klass.new(*args, &block) }
end
@@ -47,27 +78,30 @@ module ActiveRecord
end
def respond_to?(method, include_private = false)
- return true if arel.respond_to?(method, include_private) || Array.method_defined?(method) || @klass.respond_to?(method, include_private)
-
- if match = DynamicFinderMatch.match(method)
- return true if @klass.send(:all_attributes_exists?, match.attribute_names)
- elsif match = DynamicScopeMatch.match(method)
- return true if @klass.send(:all_attributes_exists?, match.attribute_names)
- else
+ arel.respond_to?(method, include_private) ||
+ Array.method_defined?(method) ||
+ @klass.respond_to?(method, include_private) ||
super
- end
end
def to_a
return @records if loaded?
- @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql)
+ @records = if @readonly_value.nil? && !@klass.locking_enabled?
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
+ else
+ IdentityMap.without do
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
+ end
+ end
preload = @preload_values
preload += @includes_values unless eager_loading?
- preload.each {|associations| @klass.send(:preload_associations, @records, associations) }
+ preload.each do |associations|
+ ActiveRecord::Associations::Preloader.new(@records, associations).run
+ end
- # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
+ # @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
@@ -76,7 +110,9 @@ module ActiveRecord
@records
end
- def as_json(options = nil) to_a end #:nodoc:
+ def as_json(options = nil) #:nodoc:
+ to_a.as_json(options)
+ end
# Returns size of the records.
def size
@@ -85,7 +121,10 @@ module ActiveRecord
# Returns true if there are no records.
def empty?
- loaded? ? @records.empty? : count.zero?
+ return @records.empty? if loaded?
+
+ c = count
+ c.respond_to?(:zero?) ? c.zero? : c.empty?
end
def any?
@@ -131,7 +170,7 @@ module ActiveRecord
# ==== Parameters
#
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
- # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
+ # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
# See conditions in the intro.
# * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
#
@@ -148,16 +187,29 @@ module ActiveRecord
#
# # Update all books that match conditions, but limit it to 5 ordered by date
# Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
+ #
+ # # Conditions from the current relation also works
+ # Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
+ #
+ # # The same idea applies to limit and order
+ # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
def update_all(updates, conditions = nil, options = {})
if conditions || options.present?
where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
else
+ limit = nil
+ order = []
# Apply limit and order only if they're both present
if @limit_value.present? == @order_values.present?
- arel.update(@klass.send(:sanitize_sql_for_assignment, updates))
- else
- except(:limit, :order).update_all(updates)
+ limit = arel.limit
+ order = arel.orders
end
+
+ stmt = arel.compile_update(Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)))
+ stmt.take limit if limit
+ stmt.order(*order)
+ stmt.key = table[primary_key]
+ @klass.connection.update stmt.to_sql
end
end
@@ -214,6 +266,7 @@ module ActiveRecord
#
# Person.destroy_all("last_login < '2004-04-04'")
# Person.destroy_all(:status => "inactive")
+ # Person.where(:age => 0..18).destroy_all
def destroy_all(conditions = nil)
if conditions
where(conditions).destroy_all
@@ -263,12 +316,20 @@ module ActiveRecord
#
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
+ # Post.where(:person_id => 5).where(:category => ['Something', 'Else']).delete_all
#
- # Both calls delete the affected posts all at once with a single DELETE statement.
- # If you need to destroy dependent associations or call your <tt>before_*</tt> or
+ # 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.
def delete_all(conditions = nil)
- conditions ? where(conditions).delete_all : arel.delete.tap { reset }
+ if conditions
+ where(conditions).delete_all
+ else
+ statement = arel.compile_delete
+ affected = @klass.connection.delete statement.to_sql
+ reset
+ affected
+ end
end
# Deletes the row with a primary key matching the +id+ argument, using a
@@ -292,7 +353,7 @@ module ActiveRecord
# # Delete multiple rows
# Todo.delete([2,3,4])
def delete(id_or_array)
- where(@klass.primary_key => id_or_array).delete_all
+ where(primary_key => id_or_array).delete_all
end
def reload
@@ -308,25 +369,20 @@ module ActiveRecord
self
end
- def primary_key
- @primary_key ||= table[@klass.primary_key]
- end
-
def to_sql
@to_sql ||= arel.to_sql
end
+ def where_values_hash
+ equalities = @where_values.grep(Arel::Nodes::Equality).find_all { |node|
+ node.left.relation.name == table_name
+ }
+
+ Hash[equalities.map { |where| [where.left.name, where.right] }]
+ end
+
def scope_for_create
- @scope_for_create ||= begin
- @create_with_value || Hash[
- @where_values.find_all { |w|
- w.respond_to?(:operator) && w.operator == :==
- }.map { |where|
- [where.operand1.name,
- where.operand2.respond_to?(:value) ?
- where.operand2.value : where.operand2]
- }]
- end
+ @scope_for_create ||= where_values_hash.merge(@create_with_value || {})
end
def eager_loading?
@@ -338,7 +394,7 @@ module ActiveRecord
when Relation
other.to_sql == to_sql
when Array
- to_a == other.to_a
+ to_a == other
end
end
@@ -357,15 +413,6 @@ module ActiveRecord
scoping { @klass.send(method, *args, &block) }
elsif arel.respond_to?(method)
arel.send(method, *args, &block)
- elsif match = DynamicFinderMatch.match(method)
- attributes = match.attribute_names
- super unless @klass.send(:all_attributes_exists?, attributes)
-
- if match.finder?
- find_by_attributes(match, attributes, *args)
- elsif match.instantiator?
- find_or_instantiator_by_attributes(match, attributes, *args, &block)
- end
else
super
end
@@ -374,8 +421,19 @@ module ActiveRecord
private
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 = (tables_in_string(arel.joins(arel)) + [table.name, table.table_alias]).compact.map(&:downcase).uniq
+ joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
+
(tables_in_string(to_sql) - joined_tables).any?
end
@@ -383,7 +441,7 @@ module ActiveRecord
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(&:downcase).uniq - ['raw_sql_']
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
end
end
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
index d7494ebb5a..bf5a60f458 100644
--- a/activerecord/lib/active_record/relation/batches.rb
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -1,7 +1,7 @@
require 'active_support/core_ext/object/blank'
module ActiveRecord
- module Batches # :nodoc:
+ module Batches
# Yields each record that was found by the find +options+. The find is
# performed by find_in_batches with a batch size of 1000 (or as
# specified by the <tt>:batch_size</tt> option).
@@ -39,7 +39,7 @@ module ActiveRecord
# ascending on the primary key ("id ASC") to make the batch ordering
# work. This also mean that this method only works with integer-based
# primary keys. You can't set the limit either, that's used to control
- # the the batch sizes.
+ # the batch sizes.
#
# Example:
#
@@ -50,7 +50,7 @@ module ActiveRecord
def find_in_batches(options = {})
relation = self
- if orders.present? || taken.present?
+ 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
@@ -65,7 +65,7 @@ module ActiveRecord
batch_size = options.delete(:batch_size) || 1000
relation = relation.except(:order).order(batch_order).limit(batch_size)
- records = relation.where(primary_key.gteq(start)).all
+ records = relation.where(table[primary_key].gteq(start)).all
while records.any?
yield records
@@ -73,7 +73,7 @@ module ActiveRecord
break if records.size < batch_size
if primary_key_offset = records.last.id
- records = relation.where(primary_key.gt(primary_key_offset)).to_a
+ records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
else
raise "Primary key not included in the custom select clause"
end
@@ -83,7 +83,7 @@ module ActiveRecord
private
def batch_order
- "#{@klass.table_name}.#{@klass.primary_key} ASC"
+ "#{table_name}.#{primary_key} ASC"
end
end
end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index a679c444cf..c1842b1a96 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -6,32 +6,30 @@ module ActiveRecord
# Count operates using three different approaches.
#
# * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
- # * Count using column: By passing a column name to count, it will return a count of all the
- # rows for the model with supplied column present
+ # * Count using column: By passing a column name to count, it will return a count of all the
+ # rows for the model with supplied column present.
# * Count using options will find the row count matched by the options used.
#
# The third approach, count using options, accepts an option hash as the only parameter. The options are:
#
- # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
+ # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
# See conditions in the intro to ActiveRecord::Base.
- # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
- # or named associations in the same form used for the <tt>:include</tt> option, which will
- # perform an INNER JOIN on the associated table(s).
- # If the value is a string, then the records will be returned read-only since they will have
- # attributes that do not correspond to the table's columns.
+ # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id"
+ # (rarely needed) or named associations in the same form used for the <tt>:include</tt> option, which will
+ # perform an INNER JOIN on the associated table(s). If the value is a string, then the records
+ # will be returned read-only since they will have attributes that do not correspond to the table's columns.
# Pass <tt>:readonly => false</tt> to override.
- # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs.
- # The symbols named refer to already defined associations. When using named associations, count
+ # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs.
+ # The symbols named refer to already defined associations. When using named associations, count
# returns the number of DISTINCT items for the model you're counting.
# See eager loading under Associations.
# * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
# * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
- # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example,
- # want to do a join but not
- # include the joined columns.
- # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as
+ # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example,
+ # want to do a join but not include the joined columns.
+ # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as
# SELECT COUNT(DISTINCT posts.id) ...
- # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an
+ # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an
# alternate table name (or even the name of a database view).
#
# Examples for counting all:
@@ -44,16 +42,16 @@ module ActiveRecord
# Person.count(:conditions => "age > 26")
#
# # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
- # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)
+ # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)
#
# # finds the number of rows matching the conditions and joins.
- # Person.count(:conditions => "age > 26 AND job.salary > 60000",
- # :joins => "LEFT JOIN jobs on jobs.person_id = person.id")
+ # Person.count(:conditions => "age > 26 AND job.salary > 60000",
+ # :joins => "LEFT JOIN jobs on jobs.person_id = person.id")
#
# Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
# Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
#
- # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition.
+ # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition.
# Use Person.count instead.
def count(column_name = nil, options = {})
column_name, options = nil, column_name if column_name.is_a?(Hash)
@@ -95,14 +93,14 @@ module ActiveRecord
calculate(:sum, column_name, options)
end
- # This calculates aggregate values in the given column. Methods for count, sum, average,
- # minimum, and maximum have been added as shortcuts. Options such as <tt>:conditions</tt>,
+ # This calculates aggregate values in the given column. Methods for count, sum, average,
+ # minimum, and maximum have been added as shortcuts. Options such as <tt>:conditions</tt>,
# <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
#
# There are two basic forms of output:
- # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
+ # * 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 by the
+ # * Grouped values: This returns an ordered hash of the values and groups them by the
# <tt>:group</tt> option. It takes either a column name, or the name of a belongs_to association.
#
# values = Person.maximum(:age, :group => 'last_name')
@@ -119,29 +117,29 @@ module ActiveRecord
# end
#
# Options:
- # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
+ # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
# See conditions in the intro to ActiveRecord::Base.
- # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything,
+ # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything,
# the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
- # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id".
+ # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id".
# (Rarely needed).
- # The records will be returned read-only since they will have attributes that do not correspond to the
+ # The records will be returned read-only since they will have attributes that do not correspond to the
# table's columns.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
- # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example
+ # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example
# want to do a join, but not include the joined columns.
- # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as
+ # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as
# SELECT COUNT(DISTINCT posts.id) ...
#
# Examples:
# Person.calculate(:count, :all) # The same as Person.count
# Person.average(:age) # SELECT AVG(age) FROM people...
- # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
+ # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
# # everyone with a last name other than 'Drake'
#
# # Selects the minimum age for any family without any minors
- # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)
+ # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)
#
# Person.sum("2 * age")
def calculate(operation, column_name, options = {})
@@ -163,80 +161,112 @@ module ActiveRecord
def perform_calculation(operation, column_name, options = {})
operation = operation.to_s.downcase
+ distinct = nil
+
if operation == "count"
column_name ||= (select_for_count || :all)
- joins = arel.joins(arel)
- if joins.present? && joins =~ /LEFT OUTER/i
+ unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
distinct = true
- column_name = @klass.primary_key if column_name == :all
+ column_name = primary_key if column_name == :all
end
- distinct = nil if column_name.to_s =~ /\s*DISTINCT\s+/i
- distinct ||= options[:distinct]
- else
- distinct = nil
+ distinct = nil if column_name =~ /\s*DISTINCT\s+/i
end
distinct = options[:distinct] || distinct
- column_name = :all if column_name.blank? && operation == "count"
if @group_values.any?
- return execute_grouped_calculation(operation, column_name)
+ execute_grouped_calculation(operation, column_name, distinct)
else
- return execute_simple_calculation(operation, column_name, distinct)
+ execute_simple_calculation(operation, column_name, distinct)
end
end
- def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
- column = if @klass.column_names.include?(column_name.to_s)
- Arel::Attribute.new(@klass.unscoped, column_name)
+ def aggregate_column(column_name)
+ if @klass.column_names.include?(column_name.to_s)
+ Arel::Attribute.new(@klass.unscoped.table, column_name)
else
- Arel::SqlLiteral.new(column_name == :all ? "*" : column_name.to_s)
+ Arel.sql(column_name == :all ? "*" : column_name.to_s)
end
+ end
- # Postgresql doesn't like ORDER BY when there are no GROUP BY
- relation = except(:order).select(operation == 'count' ? column.count(distinct) : column.send(operation))
- type_cast_calculated_value(@klass.connection.select_value(relation.to_sql), column_for(column_name), operation)
+ def operation_over_aggregate_column(column, operation, distinct)
+ operation == 'count' ? column.count(distinct) : column.send(operation)
end
- def execute_grouped_calculation(operation, column_name) #:nodoc:
- group_attr = @group_values.first
- association = @klass.reflect_on_association(group_attr.to_sym)
- associated = association && association.macro == :belongs_to # only count belongs_to associations
- group_field = associated ? association.primary_key_name : group_attr
- group_alias = column_alias_for(group_field)
- group_column = column_for(group_field)
+ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
+ column = aggregate_column(column_name)
- group = @klass.connection.adapter_name == 'FrontBase' ? group_alias : group_field
+ # Postgresql doesn't like ORDER BY when there are no GROUP BY
+ relation = except(:order)
+ select_value = operation_over_aggregate_column(column, operation, distinct)
+
+ relation.select_values = [select_value]
- aggregate_alias = column_alias_for(operation, column_name)
+ query_builder = relation.arel
- select_statement = if operation == 'count' && column_name == :all
- "COUNT(*) AS count_all"
+ if operation == "count"
+ limit = relation.limit_value
+ offset = relation.offset_value
+
+ unless limit && offset
+ query_builder.limit = nil
+ query_builder.offset = nil
+ end
+ end
+
+ type_cast_calculated_value(@klass.connection.select_value(query_builder.to_sql), column_for(column_name), operation)
+ end
+
+ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
+ group_attr = @group_values
+ association = @klass.reflect_on_association(group_attr.first.to_sym)
+ associated = group_attr.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
+ group_fields = Array(associated ? association.foreign_key : group_attr)
+ group_aliases = group_fields.map { |field| column_alias_for(field) }
+ group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
+ [aliaz, column_for(field)]
+ }
+
+ group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
+
+ if operation == 'count' && column_name == :all
+ aggregate_alias = 'count_all'
else
- Arel::Attribute.new(@klass.unscoped, column_name).send(operation).as(aggregate_alias).to_sql
+ aggregate_alias = column_alias_for(operation, column_name)
end
- select_statement << ", #{group_field} AS #{group_alias}"
+ select_values = [
+ operation_over_aggregate_column(
+ aggregate_column(column_name),
+ operation,
+ distinct).as(aggregate_alias)
+ ]
+
+ select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
+ "#{field} AS #{aliaz}"
+ }
- relation = except(:group).select(select_statement).group(group)
+ relation = except(:group).group(group.join(','))
+ relation.select_values = select_values
calculated_data = @klass.connection.select_all(relation.to_sql)
if association
- key_ids = calculated_data.collect { |row| row[group_alias] }
+ key_ids = calculated_data.collect { |row| row[group_aliases.first] }
key_records = association.klass.base_class.find(key_ids)
- key_records = key_records.inject({}) { |hsh, r| hsh.merge(r.id => r) }
+ key_records = Hash[key_records.map { |r| [r.id, r] }]
end
- calculated_data.inject(ActiveSupport::OrderedHash.new) do |all, row|
- key = type_cast_calculated_value(row[group_alias], group_column)
- key = key_records[key] if associated
- value = row[aggregate_alias]
- all[key] = type_cast_calculated_value(value, column_for(column_name), operation)
- all
- end
+ ActiveSupport::OrderedHash[calculated_data.map do |row|
+ key = group_columns.map { |aliaz, column|
+ 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
@@ -264,15 +294,11 @@ module ActiveRecord
end
def type_cast_calculated_value(value, column, operation = nil)
- if value.is_a?(String) || value.nil?
- case operation
- when 'count' then value.to_i
- when 'sum' then type_cast_using_column(value || '0', column)
- when 'average' then value.try(:to_d)
- else type_cast_using_column(value, column)
- end
- else
- value
+ 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
@@ -282,7 +308,7 @@ module ActiveRecord
def select_for_count
if @select_values.present?
- select = @select_values.join(", ")
+ select = @select_values.join(", ")
select if select !~ /(,|\*)/
end
end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index b34c11973b..25e23a9d55 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -19,29 +19,29 @@ module ActiveRecord
#
# All approaches accept an options hash as their last parameter.
#
- # ==== Parameters
+ # ==== Options
#
- # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>,
+ # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>["user_name = ?", username]</tt>,
# or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
- # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
+ # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
# <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
- # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
+ # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
# it would skip rows 0 through 4.
# * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
- # named associations in the same form used for the <tt>:include</tt> option, which will perform an
+ # named associations in the same form used for the <tt>:include</tt> option, which will perform an
# <tt>INNER JOIN</tt> on the associated table(s),
# or an array containing a mixture of both strings and named associations.
- # If the value is a string, then the records will be returned read-only since they will
+ # If the value is a string, then the records will be returned read-only since they will
# have attributes that do not correspond to the table's columns.
# Pass <tt>:readonly => false</tt> to override.
# * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
# to already defined associations. See eager loading under Associations.
- # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
+ # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
# for example, want to do a join but not include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
- # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
+ # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
# to an alternate table name (or even the name of a database view).
# * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
# * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
@@ -54,7 +54,7 @@ module ActiveRecord
# 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.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
+ # 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>
@@ -63,23 +63,23 @@ module ActiveRecord
# ==== Examples
#
# # find first
- # Person.find(:first) # returns the first object fetched by SELECT * FROM people
- # Person.find(:first, :conditions => [ "user_name = ?", user_name])
- # Person.find(:first, :conditions => [ "user_name = :u", { :u => user_name }])
- # Person.find(:first, :order => "created_on DESC", :offset => 5)
+ # 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
#
# # find last
- # Person.find(:last) # returns the last object fetched by SELECT * FROM people
- # Person.find(:last, :conditions => [ "user_name = ?", user_name])
- # Person.find(:last, :order => "created_on DESC", :offset => 5)
+ # 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
#
# # find all
- # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
- # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
- # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
- # Person.find(:all, :offset => 10, :limit => 10)
- # Person.find(:all, :include => [ :account, :friends ])
- # Person.find(:all, :group => "category")
+ # Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
+ # Person.where(["category IN (?)", categories]).limit(50).all
+ # Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
+ # Person.offset(10).limit(10).all
+ # Person.includes([:account, :friends]).all
+ # Person.group("category").all
#
# 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
@@ -88,7 +88,7 @@ module ActiveRecord
# expected <tt>person.visits == 4</tt>.
#
# Person.transaction do
- # person = Person.find(1, :lock => true)
+ # person = Person.lock(true).find(1)
# person.visits += 1
# person.save!
# end
@@ -123,6 +123,11 @@ module ActiveRecord
end
end
+ # Same as #first! but raises RecordNotFound if no record is returned
+ def first!(*args)
+ self.first(*args) or raise RecordNotFound
+ end
+
# A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
# same arguments to this method as you can to <tt>find(:last)</tt>.
def last(*args)
@@ -137,6 +142,11 @@ module ActiveRecord
end
end
+ # Same as #last! but raises RecordNotFound if no record is returned
+ def last!(*args)
+ self.last(*args) or raise RecordNotFound
+ end
+
# A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the
# same arguments to this method as you can to <tt>find(:all)</tt>.
def all(*args)
@@ -171,22 +181,25 @@ module ActiveRecord
def exists?(id = nil)
id = id.id if ActiveRecord::Base === id
+ relation = select("1").limit(1)
+
case id
when Array, Hash
- where(id).exists?
+ relation = relation.where(id)
else
- relation = select(primary_key).limit(1)
- relation = relation.where(primary_key.eq(id)) if id
- relation.first ? true : false
+ relation = relation.where(table[primary_key].eq(id)) if id
end
+
+ relation.first ? true : false
end
protected
def find_with_associations
including = (@eager_load_values + @includes_values).uniq
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, including, nil)
- rows = construct_relation_for_association_find(join_dependency).to_a
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
+ relation = construct_relation_for_association_find(join_dependency)
+ rows = connection.select_all(relation.to_sql, 'SQL', relation.bind_values)
join_dependency.instantiate(rows)
rescue ThrowResult
[]
@@ -194,13 +207,13 @@ module ActiveRecord
def construct_relation_for_association_calculations
including = (@eager_load_values + @includes_values).uniq
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, including, arel.joins(arel))
+ 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(column_aliases(join_dependency))
+ relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
apply_join_dependency(relation, join_dependency)
end
@@ -222,15 +235,15 @@ module ActiveRecord
end
def construct_limited_ids_condition(relation)
- orders = relation.order_values.join(", ")
- values = @klass.connection.distinct("#{@klass.connection.quote_table_name @klass.table_name}.#{@klass.primary_key}", orders)
+ orders = relation.order_values
+ values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
- ids_array = relation.select(values).collect {|row| row[@klass.primary_key]}
- ids_array.empty? ? raise(ThrowResult) : primary_key.in(ids_array)
+ ids_array = relation.select(values).collect {|row| row[primary_key]}
+ ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
end
def find_by_attributes(match, attributes, *args)
- conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h}
+ conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]
result = where(conditions).send(match.finder)
if match.bang? && result.blank?
@@ -288,19 +301,24 @@ module ActiveRecord
def find_one(id)
id = id.id if ActiveRecord::Base === id
- record = where(primary_key.eq(id)).first
+ column = columns_hash[primary_key]
+
+ substitute = connection.substitute_for(column, @bind_values)
+ relation = where(table[primary_key].eq(substitute))
+ relation.bind_values = [[column, id]]
+ record = relation.first
unless record
- conditions = arel.send(:where_clauses).join(', ')
- conditions = " [WHERE #{conditions}]" if conditions.present?
- raise RecordNotFound, "Couldn't find #{@klass.name} with ID=#{id}#{conditions}"
+ conditions = arel.where_sql
+ conditions = " [#{conditions}]" if conditions
+ raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
end
record
end
def find_some(ids)
- result = where(primary_key.in(ids)).all
+ result = where(table[primary_key].in(ids)).all
expected_size =
if @limit_value && ids.size > @limit_value
@@ -317,7 +335,7 @@ module ActiveRecord
if result.size == expected_size
result
else
- conditions = arel.send(:where_clauses).join(', ')
+ conditions = arel.wheres.map { |x| x.value }.join(', ')
conditions = " [WHERE #{conditions}]" if conditions.present?
error = "Couldn't find all #{@klass.name.pluralize} with IDs "
@@ -342,14 +360,8 @@ module ActiveRecord
end
end
- def column_aliases(join_dependency)
- join_dependency.joins.collect{|join| join.column_names_with_alias.collect{|column_name, aliased_name|
- "#{connection.quote_table_name join.aliased_table_name}.#{connection.quote_column_name column_name} AS #{aliased_name}"}}.flatten.join(", ")
- end
-
def using_limitable_reflections?(reflections)
- reflections.none?(&:collection?)
+ reflections.none? { |r| r.collection? }
end
-
end
end
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index 5cea2328e8..982b3d7e9f 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -1,33 +1,38 @@
module ActiveRecord
- class PredicateBuilder
-
- def initialize(engine)
- @engine = engine
- end
-
- def build_from_hash(attributes, default_table)
+ class PredicateBuilder # :nodoc:
+ def self.build_from_hash(engine, attributes, default_table)
predicates = attributes.map do |column, value|
table = default_table
if value.is_a?(Hash)
- table = Arel::Table.new(column, :engine => @engine)
- build_from_hash(value, table)
+ table = Arel::Table.new(column, engine)
+ build_from_hash(engine, value, table)
else
column = column.to_s
if column.include?('.')
table_name, column = column.split('.', 2)
- table = Arel::Table.new(table_name, :engine => @engine)
+ table = Arel::Table.new(table_name, engine)
end
- attribute = table[column] || Arel::Attribute.new(table, column)
+ attribute = table[column.to_sym]
case value
- when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::Relation
- values = value.to_a
+ when ActiveRecord::Relation
+ value.select_values = [value.klass.arel_table['id']] if value.select_values.empty?
+ attribute.in(value.arel.ast)
+ when Array, ActiveRecord::Associations::CollectionProxy
+ values = value.to_a.map { |x|
+ x.is_a?(ActiveRecord::Base) ? x.id : x
+ }
attribute.in(values)
when Range, Arel::Relation
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
@@ -36,6 +41,5 @@ module ActiveRecord
predicates.flatten
end
-
end
end
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index e71f1cca72..9470e7c6c5 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -6,247 +6,299 @@ module ActiveRecord
extend ActiveSupport::Concern
attr_accessor :includes_values, :eager_load_values, :preload_values,
- :select_values, :group_values, :order_values, :joins_values, :where_values, :having_values,
+ :select_values, :group_values, :order_values, :joins_values,
+ :where_values, :having_values, :bind_values,
:limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, :from_value
def includes(*args)
- args.reject! { |a| a.blank? }
- clone.tap {|r| r.includes_values += args if args.present? }
+ args.reject! {|a| a.blank? }
+
+ return self if args.empty?
+
+ relation = clone
+ relation.includes_values = (relation.includes_values + args).flatten.uniq
+ relation
end
def eager_load(*args)
- clone.tap {|r| r.eager_load_values += args if args.present? }
+ return self if args.blank?
+
+ relation = clone
+ relation.eager_load_values += args
+ relation
end
def preload(*args)
- clone.tap {|r| r.preload_values += args if args.present? }
+ return self if args.blank?
+
+ relation = clone
+ relation.preload_values += args
+ relation
end
- def select(*args)
+ def select(value = Proc.new)
if block_given?
- to_a.select {|*block_args| yield(*block_args) }
+ to_a.select {|*block_args| value.call(*block_args) }
else
- clone.tap {|r| r.select_values += args if args.present? }
+ relation = clone
+ relation.select_values += Array.wrap(value)
+ relation
end
end
def group(*args)
- clone.tap {|r| r.group_values += args.flatten if args.present? }
+ return self if args.blank?
+
+ relation = clone
+ relation.group_values += args.flatten
+ relation
end
def order(*args)
- clone.tap {|r| r.order_values += args if args.present? }
- end
+ return self if args.blank?
- def reorder(*args)
- clone.tap {|r| r.order_values = args if args.present? }
+ relation = clone
+ relation.order_values += args.flatten
+ relation
end
def joins(*args)
+ return self if args.compact.blank?
+
+ relation = clone
+
args.flatten!
- clone.tap {|r| r.joins_values += args if args.present? }
+ relation.joins_values += args
+
+ relation
+ end
+
+ def bind(value)
+ relation = clone
+ relation.bind_values += [value]
+ relation
end
def where(opts, *rest)
- value = build_where(opts, rest)
- value ? clone.tap {|r| r.where_values += Array.wrap(value) } : clone
+ return self if opts.blank?
+
+ relation = clone
+ relation.where_values += build_where(opts, rest)
+ relation
end
def having(*args)
- value = build_where(*args)
- clone.tap {|r| r.having_values += Array.wrap(value) if value.present? }
+ return self if args.blank?
+
+ relation = clone
+ relation.having_values += build_where(*args)
+ relation
end
- def limit(value = true)
- clone.tap {|r| r.limit_value = value }
+ def limit(value)
+ relation = clone
+ relation.limit_value = value
+ relation
end
- def offset(value = true)
- clone.tap {|r| r.offset_value = value }
+ def offset(value)
+ relation = clone
+ relation.offset_value = value
+ relation
end
def lock(locks = true)
+ relation = clone
+
case locks
when String, TrueClass, NilClass
- clone.tap {|r| r.lock_value = locks || true }
+ relation.lock_value = locks || true
else
- clone.tap {|r| r.lock_value = false }
+ relation.lock_value = false
end
+
+ relation
end
def readonly(value = true)
- clone.tap {|r| r.readonly_value = value }
+ relation = clone
+ relation.readonly_value = value
+ relation
end
- def create_with(value = true)
- clone.tap {|r| r.create_with_value = value }
+ def create_with(value)
+ relation = clone
+ relation.create_with_value = value && (@create_with_value || {}).merge(value)
+ relation
end
- def from(value = true)
- clone.tap {|r| r.from_value = value }
+ def from(value)
+ relation = clone
+ relation.from_value = value
+ relation
end
- def extending(*modules, &block)
- modules << Module.new(&block) if block_given?
- clone.tap {|r| r.send(:apply_modules, *modules) }
+ def extending(*modules)
+ modules << Module.new(&Proc.new) if block_given?
+
+ return self if modules.empty?
+
+ relation = clone
+ relation.send(:apply_modules, modules.flatten)
+ relation
end
def reverse_order
- order_clause = arel.send(:order_clauses).join(', ')
- relation = except(:order)
+ order_clause = arel.order_clauses
- unless order_clauses.blank?
- relation.order(reverse_sql_order(order_clause))
- else
- relation.order("#{@klass.table_name}.#{@klass.primary_key} DESC")
- end
+ order = order_clause.empty? ?
+ "#{table_name}.#{primary_key} DESC" :
+ reverse_sql_order(order_clause).join(', ')
+
+ except(:order).order(Arel.sql(order))
end
def arel
@arel ||= build_arel
end
- def custom_join_sql(*joins)
- arel = table
- joins.each do |join|
- next if join.blank?
+ def build_arel
+ arel = table.from table
- @implicit_readonly = true
+ build_joins(arel, @joins_values) unless @joins_values.empty?
- case join
- when Hash, Array, Symbol
- if array_of_strings?(join)
- join_string = join.join(' ')
- arel = arel.join(join_string)
- end
- else
- arel = arel.join(join)
- end
- end
- arel.joins(arel)
- end
+ collapse_wheres(arel, (@where_values - ['']).uniq)
- def build_arel
- arel = table
+ arel.having(*@having_values.uniq.reject{|h| h.blank?}) unless @having_values.empty?
- arel = build_joins(arel, @joins_values) unless @joins_values.empty?
+ arel.take(connection.sanitize_limit(@limit_value)) if @limit_value
+ arel.skip(@offset_value) if @offset_value
- @where_values.uniq.each do |where|
- next if where.blank?
+ arel.group(*@group_values.uniq.reject{|g| g.blank?}) unless @group_values.empty?
- case where
- when Arel::SqlLiteral
- arel = arel.where(where)
- else
- sql = where.is_a?(String) ? where : where.to_sql
- arel = arel.where(Arel::SqlLiteral.new("(#{sql})"))
- end
- end
+ arel.order(*@order_values.uniq.reject{|o| o.blank?}) unless @order_values.empty?
- arel = arel.having(*@having_values.uniq.select{|h| h.present?}) unless @having_values.empty?
+ build_select(arel, @select_values.uniq)
- arel = arel.take(@limit_value) if @limit_value
- arel = arel.skip(@offset_value) if @offset_value
+ arel.from(@from_value) if @from_value
+ arel.lock(@lock_value) if @lock_value
- arel = arel.group(*@group_values.uniq.select{|g| g.present?}) unless @group_values.empty?
+ arel
+ end
- arel = arel.order(*@order_values.uniq.select{|o| o.present?}) unless @order_values.empty?
+ private
- arel = build_select(arel, @select_values.uniq)
+ def custom_join_ast(table, joins)
+ joins = joins.reject { |join| join.blank? }
- arel = arel.from(@from_value) if @from_value
- arel = arel.lock(@lock_value) if @lock_value
+ return [] if joins.empty?
- arel
+ @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))
+ [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
when Hash
attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
- PredicateBuilder.new(table.engine).build_from_hash(attributes, table)
+ PredicateBuilder.build_from_hash(table.engine, attributes, table)
else
- opts
+ [opts]
end
end
- private
-
- def build_joins(relation, joins)
- joined_associations = []
- association_joins = []
-
- joins = @joins_values.map {|j| j.respond_to?(:strip) ? j.strip : j}.uniq
-
- joins.each do |join|
- association_joins << join if [Hash, Array, Symbol].include?(join.class) && !array_of_strings?(join)
+ 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
- stashed_association_joins = joins.select {|j| j.is_a?(ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation)}
+ association_joins = buckets['association_join'] || []
+ stashed_association_joins = buckets['stashed_join'] || []
+ join_nodes = buckets['join_node'] || []
+ string_joins = (buckets['string_join'] || []).map { |x|
+ x.strip
+ }.uniq
- non_association_joins = (joins - association_joins - stashed_association_joins)
- custom_joins = custom_join_sql(*non_association_joins)
+ join_list = custom_join_ast(manager, string_joins)
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, custom_joins)
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(
+ @klass,
+ association_joins,
+ join_list
+ )
+
+ join_nodes.each do |join|
+ join_dependency.alias_tracker.aliased_name_for(join.left.name.downcase)
+ end
join_dependency.graft(*stashed_association_joins)
@implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
- to_join = []
-
+ # FIXME: refactor this to build an AST
join_dependency.join_associations.each do |association|
- if (association_relation = association.relation).is_a?(Array)
- to_join << [association_relation.first, association.join_class, association.association_join.first]
- to_join << [association_relation.last, association.join_class, association.association_join.last]
- else
- to_join << [association_relation, association.join_class, association.association_join]
- end
+ association.join_to(manager)
end
- to_join.each do |tj|
- unless joined_associations.detect {|ja| ja[0] == tj[0] && ja[1] == tj[1] && ja[2] == tj[2] }
- joined_associations << tj
- relation = relation.join(tj[0], tj[1]).on(*tj[2])
- end
- end
+ manager.join_sources.concat join_nodes.uniq
+ manager.join_sources.concat join_list
- relation.join(custom_joins)
+ manager
end
def build_select(arel, selects)
- if selects.present?
+ unless selects.empty?
@implicit_readonly = false
- # TODO: fix this ugly hack, we should refactor the callers to get an ARel compatible array.
- # Before this change we were passing to ARel the last element only, and ARel is capable of handling an array
- if selects.all? {|s| s.is_a?(String) || !s.is_a?(Arel::Expression) } && !(selects.last =~ /^COUNT\(/)
- arel.project(*selects)
- else
- arel.project(selects.last)
- end
+ arel.project(*selects)
else
- arel.project(@klass.quoted_table_name + '.*')
+ arel.project(@klass.arel_table[Arel.star])
end
end
def apply_modules(modules)
- values = Array.wrap(modules)
- @extensions += values if values.present?
- values.each {|extension| extend(extension) }
+ unless modules.empty?
+ @extensions += modules
+ modules.each {|extension| extend(extension) }
+ end
end
def reverse_sql_order(order_query)
- order_query.split(',').each { |s|
- if s.match(/\s(asc|ASC)$/)
- s.gsub!(/\s(asc|ASC)$/, ' DESC')
- elsif s.match(/\s(desc|DESC)$/)
- s.gsub!(/\s(desc|DESC)$/, ' ASC')
- else
- s.concat(' DESC')
- end
- }.join(',')
+ order_query.join(', ').split(',').collect do |s|
+ s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
+ end
end
def array_of_strings?(o)
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
index 7712ad2569..128e0fbd86 100644
--- a/activerecord/lib/active_record/relation/spawn_methods.rb
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -3,71 +3,109 @@ require 'active_support/core_ext/object/blank'
module ActiveRecord
module SpawnMethods
def merge(r)
+ return self unless r
+ return to_a & r if r.is_a?(Array)
+
merged_relation = clone
- return merged_relation unless r
- ((Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS) - [:joins, :where]).each do |method|
+ Relation::ASSOCIATION_METHODS.each do |method|
value = r.send(:"#{method}_values")
- merged_relation.send(:"#{method}_values=", value) if value.present?
- end
-
- merged_relation = merged_relation.joins(r.joins_values)
- merged_wheres = @where_values
-
- r.where_values.each do |w|
- if w.is_a?(Arel::Predicates::Equality)
- merged_wheres = merged_wheres.reject {|p| p.is_a?(Arel::Predicates::Equality) && p.operand1.name == w.operand1.name }
+ unless value.empty?
+ if method == :includes
+ merged_relation = merged_relation.includes(value)
+ else
+ merged_relation.send(:"#{method}_values=", value)
+ end
end
+ end
- merged_wheres += [w]
+ (Relation::MULTI_VALUE_METHODS - [:joins, :where]).each do |method|
+ value = r.send(:"#{method}_values")
+ merged_relation.send(:"#{method}_values=", merged_relation.send(:"#{method}_values") + value) if value.present?
+ end
+
+ merged_relation.joins_values += r.joins_values
+
+ merged_wheres = @where_values + r.where_values
+
+ unless @where_values.empty?
+ # Remove duplicates, last one wins.
+ seen = Hash.new { |h,table| h[table] = {} }
+ merged_wheres = merged_wheres.reverse.reject { |w|
+ nuke = false
+ if w.respond_to?(:operator) && w.operator == :==
+ name = w.left.name
+ table = w.left.relation.name
+ nuke = seen[table][name]
+ seen[table][name] = true
+ end
+ nuke
+ }.reverse
end
merged_relation.where_values = merged_wheres
- Relation::SINGLE_VALUE_METHODS.reject {|m| m == :lock}.each do |method|
- unless (value = r.send(:"#{method}_value")).nil?
- merged_relation.send(:"#{method}_value=", value)
- end
+ (Relation::SINGLE_VALUE_METHODS - [:lock, :create_with]).each do |method|
+ value = r.send(:"#{method}_value")
+ merged_relation.send(:"#{method}_value=", value) unless value.nil?
end
merged_relation.lock_value = r.lock_value unless merged_relation.lock_value
+ merged_relation = merged_relation.create_with(r.create_with_value) if r.create_with_value
+
# Apply scope extension modules
merged_relation.send :apply_modules, r.extensions
merged_relation
end
- alias :& :merge
-
+ # Removes from the query the condition(s) specified in +skips+.
+ #
+ # Example:
+ #
+ # Post.order('id asc').except(:order) # discards the order condition
+ # Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
+ #
def except(*skips)
result = self.class.new(@klass, table)
- (Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS).each do |method|
- result.send(:"#{method}_values=", send(:"#{method}_values")) unless skips.include?(method)
+ ((Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS) - skips).each do |method|
+ result.send(:"#{method}_values=", send(:"#{method}_values"))
end
- Relation::SINGLE_VALUE_METHODS.each do |method|
- result.send(:"#{method}_value=", send(:"#{method}_value")) unless skips.include?(method)
+ (Relation::SINGLE_VALUE_METHODS - skips).each do |method|
+ result.send(:"#{method}_value=", send(:"#{method}_value"))
end
+ # Apply scope extension modules
+ result.send(:apply_modules, extensions)
+
result
end
+ # Removes any condition from the query other than the one(s) specified in +onlies+.
+ #
+ # Example:
+ #
+ # Post.order('id asc').only(:where) # discards the order condition
+ # Post.order('id asc').only(:where, :order) # uses the specified order
+ #
def only(*onlies)
result = self.class.new(@klass, table)
- onlies.each do |only|
- if (Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS).include?(only)
- result.send(:"#{only}_values=", send(:"#{only}_values"))
- elsif Relation::SINGLE_VALUE_METHODS.include?(only)
- result.send(:"#{only}_value=", send(:"#{only}_value"))
- else
- raise "Invalid argument : #{only}"
- end
+ ((Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS) & onlies).each do |method|
+ result.send(:"#{method}_values=", send(:"#{method}_values"))
+ end
+
+ (Relation::SINGLE_VALUE_METHODS & onlies).each do |method|
+ result.send(:"#{method}_value=", send(:"#{method}_value"))
end
+ # Apply scope extension modules
+ result.send(:apply_modules, extensions)
+
result
end
@@ -79,19 +117,16 @@ module ActiveRecord
return relation unless options
options.assert_valid_keys(VALID_FIND_OPTIONS)
+ finders = options.dup
+ finders.delete_if { |key, value| value.nil? && key != :limit }
- [:joins, :select, :group, :having, :limit, :offset, :from, :lock, :readonly].each do |finder|
- relation = relation.send(finder, options[finder]) if options.has_key?(finder)
- end
-
- # Give precedence to newly-applied orders and groups to play nicely with with_scope
- [:group, :order].each do |finder|
- relation.send("#{finder}_values=", Array.wrap(options[finder]) + relation.send("#{finder}_values")) if options.has_key?(finder)
+ ([:joins, :select, :group, :order, :having, :limit, :offset, :from, :lock, :readonly] & finders.keys).each do |finder|
+ relation = relation.send(finder, finders[finder])
end
- relation = relation.where(options[:conditions]) if options.has_key?(:conditions)
- relation = relation.includes(options[:include]) if options.has_key?(:include)
- relation = relation.extending(options[:extend]) if options.has_key?(:extend)
+ relation = relation.where(finders[:conditions]) if options.has_key?(:conditions)
+ relation = relation.includes(finders[:include]) if options.has_key?(:include)
+ relation = relation.extending(finders[:extend]) if options.has_key?(:extend)
relation
end
diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb
new file mode 100644
index 0000000000..0465b21e88
--- /dev/null
+++ b/activerecord/lib/active_record/result.rb
@@ -0,0 +1,34 @@
+module ActiveRecord
+ ###
+ # This class encapsulates a Result returned from calling +exec+ on any
+ # database connection adapter. For example:
+ #
+ # x = ActiveRecord::Base.connection.exec('SELECT * FROM foo')
+ # x # => #<ActiveRecord::Result:0xdeadbeef>
+ class Result
+ include Enumerable
+
+ attr_reader :columns, :rows
+
+ def initialize(columns, rows)
+ @columns = columns
+ @rows = rows
+ @hash_rows = nil
+ end
+
+ def each
+ hash_rows.each { |row| yield row }
+ end
+
+ def to_hash
+ hash_rows
+ end
+
+ private
+ def hash_rows
+ @hash_rows ||= @rows.map { |row|
+ Hash[@columns.zip(row)]
+ }
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb
index c1bc3214ea..d815ab05ac 100644
--- a/activerecord/lib/active_record/schema.rb
+++ b/activerecord/lib/active_record/schema.rb
@@ -30,10 +30,8 @@ module ActiveRecord
# ActiveRecord::Schema is only supported by database adapters that also
# support migrations, the two features being very similar.
class Schema < Migration
- private_class_method :new
-
- def self.migrations_path
- ActiveRecord::Migrator.migrations_path
+ def migrations_paths
+ ActiveRecord::Migrator.migrations_paths
end
# Eval the given block. All methods available to the current connection
@@ -48,11 +46,12 @@ module ActiveRecord
# ...
# end
def self.define(info={}, &block)
- instance_eval(&block)
+ schema = new
+ schema.instance_eval(&block)
unless info[:version].blank?
initialize_schema_migrations_table
- assume_migrated_upto_version(info[:version], migrations_path)
+ assume_migrated_upto_version(info[:version], schema.migrations_paths)
end
end
end
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index e9af20e1b6..a893c0ad85 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -41,11 +41,11 @@ module ActiveRecord
define_params = @version ? ":version => #{@version}" : ""
stream.puts <<HEADER
-# This file is auto-generated from the current state of the database. Instead
+# 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
+# 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
@@ -83,7 +83,7 @@ HEADER
# first dump primary key column
if @connection.respond_to?(:pk_and_sequence_for)
- pk, pk_seq = @connection.pk_and_sequence_for(table)
+ pk, _ = @connection.pk_and_sequence_for(table)
elsif @connection.respond_to?(:primary_key)
pk = @connection.primary_key(table)
end
@@ -114,16 +114,16 @@ HEADER
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.nil?
- spec[:scale] = column.scale.inspect if !column.scale.nil?
- spec[:null] = 'false' if !column.null
+ 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.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")}
spec
end.compact
# find all migration keys used in this table
- keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map(&:keys).flatten
+ keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map{ |k| k.keys }.flatten
# 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 }
@@ -176,13 +176,15 @@ HEADER
def indexes(table, stream)
if (indexes = @connection.indexes(table)).any?
add_index_statements = indexes.map do |index|
- statement_parts = [ ('add_index ' + index.table.inspect) ]
- statement_parts << index.columns.inspect
- statement_parts << (':name => ' + index.name.inspect)
+ statement_parts = [
+ ('add_index ' + index.table.inspect),
+ index.columns.inspect,
+ (':name => ' + index.name.inspect),
+ ]
statement_parts << ':unique => true' if index.unique
- index_lengths = index.lengths.compact if index.lengths.is_a?(Array)
- statement_parts << (':length => ' + Hash[*index.columns.zip(index.lengths).flatten].inspect) if index_lengths.present?
+ index_lengths = (index.lengths || []).compact
+ statement_parts << (':length => ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty?
' ' + statement_parts.join(', ')
end
diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb
index 2d8bd184f3..2bde06f562 100644
--- a/activerecord/lib/active_record/serialization.rb
+++ b/activerecord/lib/active_record/serialization.rb
@@ -5,7 +5,7 @@ module ActiveRecord #:nodoc:
include ActiveModel::Serializers::JSON
def serializable_hash(options = nil)
- options ||= {}
+ options = options.try(:clone) || {}
options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
options[:except] |= Array.wrap(self.class.inheritance_column)
@@ -22,8 +22,8 @@ module ActiveRecord #:nodoc:
end
private
- # Add associations specified via the <tt>:includes</tt> option.
- #
+ # 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
@@ -45,7 +45,7 @@ module ActiveRecord #:nodoc:
send(association)
end
- unless records.nil?
+ if records
association_options = include_has_options ? include_associations[association] : base_only_or_except
opts = options.merge(association_options)
yield(association, records, opts)
diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb
index b2d4a48945..8c4adf7116 100644
--- a/activerecord/lib/active_record/serializers/xml_serializer.rb
+++ b/activerecord/lib/active_record/serializers/xml_serializer.rb
@@ -80,7 +80,7 @@ module ActiveRecord #:nodoc:
# 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 ]
#
@@ -226,17 +226,17 @@ module ActiveRecord #:nodoc:
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
def compute_type
- type = @serializable.class.serialized_attributes.has_key?(name) ?
- super : @serializable.class.columns_hash[name].type
+ klass = @serializable.class
+ type = if klass.serialized_attributes.key?(name)
+ super
+ elsif klass.columns_hash.key?(name)
+ klass.columns_hash[name].type
+ else
+ NilClass
+ end
- case type
- when :text
- :string
- when :time
- :datetime
- else
- type
- end
+ { :text => :string,
+ :time => :datetime }[type] || type
end
protected :compute_type
end
diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb
index becde0fbfd..7e77aefb21 100644
--- a/activerecord/lib/active_record/session_store.rb
+++ b/activerecord/lib/active_record/session_store.rb
@@ -9,7 +9,7 @@ module ActiveRecord
# +id+ (numeric primary key),
# +session_id+ (text, or longtext if your session data exceeds 65K), and
# +data+ (text or longtext; careful if your session data exceeds 65KB).
- #
+ #
# The +session_id+ column should always be indexed for speedy lookups.
# Session data is marshaled to the +data+ column in Base64 format.
# If the data you write is larger than the column's size limit,
@@ -59,17 +59,17 @@ module ActiveRecord
end
def drop_table!
- connection.execute "DROP TABLE #{table_name}"
+ connection_pool.clear_table_cache!(table_name)
+ connection.drop_table table_name
end
def create_table!
- connection.execute <<-end_sql
- CREATE TABLE #{table_name} (
- id #{connection.type_to_sql(:primary_key)},
- #{connection.quote_column_name(session_id_column)} VARCHAR(255) UNIQUE,
- #{connection.quote_column_name(data_column_name)} TEXT
- )
- end_sql
+ connection_pool.clear_table_cache!(table_name)
+ connection.create_table(table_name) do |t|
+ t.string session_id_column, :limit => 255
+ t.text data_column_name
+ end
+ connection.add_index table_name, session_id_column, :unique => true
end
end
@@ -205,6 +205,7 @@ module ActiveRecord
class << self
alias :data_column_name :data_column
+ remove_method :connection
def connection
@@connection ||= ActiveRecord::Base.connection
end
@@ -289,6 +290,7 @@ module ActiveRecord
self.session_class = Session
SESSION_RECORD_KEY = 'rack.session.record'
+ ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY
private
def get_session(env, sid)
@@ -300,7 +302,7 @@ module ActiveRecord
end
end
- def set_session(env, sid, session_data)
+ def set_session(env, sid, session_data, options)
Base.silence do
record = get_session_model(env, sid)
record.data = session_data
@@ -317,12 +319,15 @@ module ActiveRecord
sid
end
- def destroy(env)
+ def destroy_session(env, session_id, options)
if sid = current_session_id(env)
Base.silence do
get_session_model(env, sid).destroy
+ env[SESSION_RECORD_KEY] = nil
end
end
+
+ generate_sid unless options[:drop]
end
def get_session_model(env, sid)
diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb
index e61a378d17..29efbbcb8c 100644
--- a/activerecord/lib/active_record/test_case.rb
+++ b/activerecord/lib/active_record/test_case.rb
@@ -1,8 +1,18 @@
module ActiveRecord
# = Active Record Test Case
- #
+ #
# Defines some test assertions to test against SQL queries.
class TestCase < ActiveSupport::TestCase #:nodoc:
+ setup :cleanup_identity_map
+
+ def setup
+ cleanup_identity_map
+ end
+
+ def cleanup_identity_map
+ ActiveRecord::IdentityMap.clear
+ end
+
def assert_date_from_db(expected, actual, message = nil)
# SybaseAdapter doesn't have a separate column type just for dates,
# so the time is in the string and incorrectly formatted
@@ -16,12 +26,13 @@ module ActiveRecord
def assert_sql(*patterns_to_match)
$queries_executed = []
yield
+ $queries_executed
ensure
failed_patterns = []
patterns_to_match.each do |pattern|
failed_patterns << pattern unless $queries_executed.any?{ |sql| pattern === sql }
end
- assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map(&:inspect).join(', ')} not found.#{$queries_executed.size == 0 ? '' : "\nQueries:\n#{$queries_executed.join("\n")}"}"
+ assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{$queries_executed.size == 0 ? '' : "\nQueries:\n#{$queries_executed.join("\n")}"}"
end
def assert_queries(num = 1)
@@ -36,21 +47,6 @@ module ActiveRecord
assert_queries(0, &block)
end
- def self.use_concurrent_connections
- setup :connection_allow_concurrency_setup
- teardown :connection_allow_concurrency_teardown
- end
-
- def connection_allow_concurrency_setup
- @connection = ActiveRecord::Base.remove_connection
- ActiveRecord::Base.establish_connection(@connection.merge({:allow_concurrency => true}))
- end
-
- def connection_allow_concurrency_teardown
- ActiveRecord::Base.clear_all_connections!
- ActiveRecord::Base.establish_connection(@connection)
- end
-
def with_kcode(kcode)
if RUBY_VERSION < '1.9'
orig_kcode, $KCODE = $KCODE, kcode
diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb
index 5531d12a41..1511c71ffc 100644
--- a/activerecord/lib/active_record/timestamp.rb
+++ b/activerecord/lib/active_record/timestamp.rb
@@ -1,72 +1,83 @@
+require 'active_support/core_ext/class/attribute'
+
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
+ # table has fields named <tt>created_at/created_on</tt> or
# <tt>updated_at/updated_on</tt>.
#
# Timestamping can be turned off by setting:
#
- # <tt>ActiveRecord::Base.record_timestamps = false</tt>
+ # config.active_record.record_timestamps = false
#
# Timestamps are in the local timezone by default but you can use UTC by setting:
#
- # <tt>ActiveRecord::Base.default_timezone = :utc</tt>
+ # config.active_record.default_timezone = :utc
#
# == Time Zone aware attributes
#
# By default, ActiveRecord::Base keeps all the datetime columns time zone aware by executing following code.
#
- # ActiveRecord::Base.time_zone_aware_attributes = true
+ # config.active_record.time_zone_aware_attributes = true
#
# This feature can easily be turned off by assigning value <tt>false</tt> .
#
- # If your attributes are time zone aware and you desire to skip time zone conversion for certain
- # attributes then you can do following:
+ # If your attributes are time zone aware and you desire to skip time zone conversion to the current Time.zone
+ # when reading certain attributes then you can do following:
#
- # Topic.skip_time_zone_conversion_for_attributes = [:written_on]
+ # class Topic < ActiveRecord::Base
+ # self.skip_time_zone_conversion_for_attributes = [:written_on]
+ # end
module Timestamp
extend ActiveSupport::Concern
included do
- class_inheritable_accessor :record_timestamps, :instance_writer => false
+ class_attribute :record_timestamps, :instance_writer => false
self.record_timestamps = true
end
private
def create #:nodoc:
- if record_timestamps
+ if self.record_timestamps
current_time = current_time_from_proper_timezone
- timestamp_attributes_for_create.each do |column|
+ all_timestamp_attributes.each do |column|
write_attribute(column.to_s, current_time) if respond_to?(column) && self.send(column).nil?
end
-
- timestamp_attributes_for_update_in_model.each do |column|
- write_attribute(column.to_s, current_time) if self.send(column).nil?
- end
end
super
end
def update(*args) #:nodoc:
- record_update_timestamps if !partial_updates? || changed?
+ 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 record_update_timestamps #:nodoc:
- return unless record_timestamps
- current_time = current_time_from_proper_timezone
- timestamp_attributes_for_update_in_model.inject({}) do |hash, column|
- hash[column.to_s] = write_attribute(column.to_s, current_time)
- hash
- end
+ def should_record_timestamps?
+ self.record_timestamps && (!partial_updates? || changed? || (attributes.keys & self.class.serialized_attributes.keys).present?)
+ end
+
+ def timestamp_attributes_for_create_in_model
+ timestamp_attributes_for_create.select { |c| self.class.column_names.include?(c.to_s) }
+ end
+
+ def timestamp_attributes_for_update_in_model
+ timestamp_attributes_for_update.select { |c| self.class.column_names.include?(c.to_s) }
end
- def timestamp_attributes_for_update_in_model #:nodoc:
- timestamp_attributes_for_update.select { |elem| respond_to?(elem) }
+ def all_timestamp_attributes_in_model
+ timestamp_attributes_for_create_in_model + timestamp_attributes_for_update_in_model
end
def timestamp_attributes_for_update #:nodoc:
@@ -78,9 +89,9 @@ module ActiveRecord
end
def all_timestamp_attributes #:nodoc:
- timestamp_attributes_for_update + timestamp_attributes_for_create
+ timestamp_attributes_for_create + timestamp_attributes_for_update
end
-
+
def current_time_from_proper_timezone #:nodoc:
self.class.default_timezone == :utc ? Time.now.utc : Time.now
end
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index a7709b9489..60d4c256c4 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -11,6 +11,7 @@ module ActiveRecord
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
@@ -130,7 +131,7 @@ module ActiveRecord
#
# +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:
+ # transaction. For example, the following behavior may be surprising:
#
# User.transaction do
# User.create(:username => 'Kotori')
@@ -140,12 +141,15 @@ module ActiveRecord
# end
# end
#
- # User.find(:all) # => empty
+ # 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.
#
- # It is also possible to requires a 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. For example:
+ # 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')
@@ -155,12 +159,12 @@ module ActiveRecord
# end
# end
#
- # User.find(:all) # => Returns only Kotori
+ # only "Kotori" is created. (This works on MySQL and PostgreSQL, but not on SQLite3.)
#
# 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. See
+ # transactions by using savepoints on MySQL and PostgreSQL. See
# http://dev.mysql.com/doc/refman/5.0/en/savepoints.html
# for more information about savepoints.
#
@@ -224,8 +228,8 @@ module ActiveRecord
end
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
- def transaction(&block)
- self.class.transaction(&block)
+ def transaction(options = {}, &block)
+ self.class.transaction(options, &block)
end
def destroy #:nodoc:
@@ -247,6 +251,7 @@ module ActiveRecord
remember_transaction_record_state
yield
rescue Exception
+ IdentityMap.remove(self) if IdentityMap.enabled?
restore_transaction_record_state
raise
ensure
@@ -255,7 +260,7 @@ module ActiveRecord
# Call the after_commit callbacks
def committed! #:nodoc:
- _run_commit_callbacks
+ run_callbacks :commit
ensure
clear_transaction_record_state
end
@@ -263,7 +268,7 @@ module ActiveRecord
# Call the after rollback callbacks. The restore_state argument indicates if the record
# state should be rolled back to the beginning or just to the last savepoint.
def rolledback!(force_restore_state = false) #:nodoc:
- _run_rollback_callbacks
+ run_callbacks :rollback
ensure
restore_transaction_record_state(force_restore_state)
end
@@ -297,8 +302,8 @@ module ActiveRecord
# Save the new record state and id of a record so it can be restored later if a transaction fails.
def remember_transaction_record_state #:nodoc
@_start_transaction_state ||= {}
+ @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
unless @_start_transaction_state.include?(:new_record)
- @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
@_start_transaction_state[:new_record] = @new_record
end
unless @_start_transaction_state.include?(:destroyed)
@@ -321,16 +326,14 @@ module ActiveRecord
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
if @_start_transaction_state[:level] < 1
restore_state = remove_instance_variable(:@_start_transaction_state)
- if restore_state
- @attributes = @attributes.dup if @attributes.frozen?
- @new_record = restore_state[:new_record]
- @destroyed = restore_state[:destroyed]
- if restore_state[:id]
- self.id = restore_state[:id]
- else
- @attributes.delete(self.class.primary_key)
- @attributes_cache.delete(self.class.primary_key)
- end
+ @attributes = @attributes.dup if @attributes.frozen?
+ @new_record = restore_state[:new_record]
+ @destroyed = restore_state[:destroyed]
+ if restore_state.has_key?(:id)
+ self.id = restore_state[:id]
+ else
+ @attributes.delete(self.class.primary_key)
+ @attributes_cache.delete(self.class.primary_key)
end
end
end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index b98fd353aa..d73fce9fd0 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -1,5 +1,5 @@
module ActiveRecord
- # = Active Record Validations
+ # = Active Record RecordInvalid
#
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
# +record+ method to retrieve the record which did not validate.
@@ -18,6 +18,13 @@ module ActiveRecord
end
end
+ # = Active Record Validations
+ #
+ # Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
+ # all of which accept the <tt>:on</tt> argument to define the context where the
+ # validations are active. Active Record will always supply either the context of
+ # <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
+ # <tt>new_record?</tt>.
module Validations
extend ActiveSupport::Concern
include ActiveModel::Validations
@@ -37,7 +44,7 @@ module ActiveRecord
end
end
- # The validation process on save can be skipped by passing false. The regular Base#save method is
+ # The validation process on save can be skipped by passing :validate => false. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save(options={})
perform_validations(options) ? super : false
@@ -49,33 +56,25 @@ module ActiveRecord
perform_validations(options) ? super : raise(RecordInvalid.new(self))
end
- # Runs all the specified validations and returns true if no errors were added otherwise false.
+ # Runs all the validations within the specified context. Returns true if no errors are found,
+ # false otherwise.
+ #
+ # If the argument is false (default is +nil+), the context is set to <tt>:create</tt> if
+ # <tt>new_record?</tt> is true, and to <tt>:update</tt> if it is not.
+ #
+ # Validations with no <tt>:on</tt> option will run no matter the context. Validations with
+ # some <tt>:on</tt> option will only run in the specified context.
def valid?(context = nil)
context ||= (new_record? ? :create : :update)
output = super(context)
-
- deprecated_callback_method(:validate)
- deprecated_callback_method(:"validate_on_#{context}")
-
errors.empty? && output
end
protected
def perform_validations(options={})
- perform_validation = case options
- when Hash
- options[:validate] != false
- else
- ActiveSupport::Deprecation.warn "save(#{options}) is deprecated, please give save(:validate => #{options}) instead", caller
- options
- end
-
- if perform_validation
- valid?(options.is_a?(Hash) ? options[:context] : nil)
- else
- true
- end
+ perform_validation = options[:validate] != false
+ perform_validation ? valid?(options[:context]) : true
end
end
end
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
index 15b587de45..3a783aeb00 100644
--- a/activerecord/lib/active_record/validations/associated.rb
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -27,13 +27,15 @@ module ActiveRecord
#
# this would specify 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
+ # 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 (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index bf863c7063..9cd6c26322 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -14,19 +14,23 @@ module ActiveRecord
def validate_each(record, attribute, value)
finder_class = find_finder_class_for(record)
- table = finder_class.unscoped
- table_name = record.class.quoted_table_name
- sql, params = mount_sql_and_params(finder_class, table_name, attribute, value)
+ coder = record.class.serialized_attributes[attribute.to_s]
- relation = table.where(sql, *params)
+ if value && coder
+ value = coder.dump value
+ end
+
+ sql, params = mount_sql_and_params(finder_class, record.class.quoted_table_name, attribute, value)
+
+ relation = finder_class.unscoped.where(sql, *params)
Array.wrap(options[:scope]).each do |scope_item|
scope_value = record.send(scope_item)
relation = relation.where(scope_item => scope_value)
end
- unless record.new_record?
+ if record.persisted?
# TODO : This should be in Arel
relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
end
@@ -78,24 +82,29 @@ module ActiveRecord
end
module ClassMethods
- # Validates whether the value of the specified attributes are unique across the system.
+ # 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, :scope => :account_id
+ # validates_uniqueness_of :user_name
# end
#
- # It can also validate whether the value of the specified attributes are unique based on multiple
- # scope parameters. For example, making sure that a teacher can only be on the schedule once
+ # It can also validate whether the value of the specified attributes are unique based on a scope parameter:
+ #
+ # class Person < ActiveRecord::Base
+ # validates_uniqueness_of :user_name, :scope => :account_id
+ # end
+ #
+ # Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once
# per semester for a particular class.
#
# class TeacherSchedule < ActiveRecord::Base
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
# end
#
- # When the record is created, a check is performed to make sure that no record exists in the database
- # with the given value for the specified attribute (that maps to a column). When the record is updated,
+ # When the record is created, a check is performed to make sure that no record exists in the database
+ # with the given value for the specified attribute (that maps to a column). When the record is updated,
# the same check is made but disregarding the record itself.
#
# Configuration options:
@@ -105,11 +114,11 @@ module ActiveRecord
# * <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>).
+ # 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
+ # 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.
#
# === Concurrency and integrity
@@ -149,33 +158,32 @@ module ActiveRecord
# | # title!
#
# This could even happen if you use transactions with the 'serializable'
- # isolation level. There are several ways to get around this problem:
+ # 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
#
- # - By locking the database table before validating, and unlocking it after
- # saving. However, table locking is very expensive, and thus not
- # recommended.
- # - By locking a lock file before validating, and unlocking it after saving.
- # This does not work if you've scaled your Rails application across
- # multiple web servers (because they cannot share lock files, or cannot
- # do that efficiently), and thus not recommended.
- # - Creating a unique index on the field, by 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
- #
- # Active Record currently provides no way to distinguish unique
- # index constraint errors from other types of database errors, so you
- # will have to parse the (database-specific) exception message to detect
- # such a case.
+ # 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::SQLiteAdapter
+ # * ActiveRecord::ConnectionAdapters::SQLite3Adapter
+ # * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
#
def validates_uniqueness_of(*attr_names)
validates_with UniquenessValidator, _merge_attributes(attr_names)
diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb
index a467ffa960..0667be7d23 100644
--- a/activerecord/lib/active_record/version.rb
+++ b/activerecord/lib/active_record/version.rb
@@ -1,10 +1,10 @@
module ActiveRecord
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activerecord/lib/rails/generators/active_record.rb b/activerecord/lib/rails/generators/active_record.rb
index 5d8a8e81bc..4b3d1db216 100644
--- a/activerecord/lib/rails/generators/active_record.rb
+++ b/activerecord/lib/rails/generators/active_record.rb
@@ -1,12 +1,14 @@
require 'rails/generators/named_base'
require 'rails/generators/migration'
require 'rails/generators/active_model'
+require 'rails/generators/active_record/migration'
require 'active_record'
module ActiveRecord
module Generators
class Base < Rails::Generators::NamedBase #:nodoc:
include Rails::Generators::Migration
+ extend ActiveRecord::Generators::Migration
# Set the current directory as base for the inherited generators.
def self.base_root
@@ -16,11 +18,7 @@ module ActiveRecord
# Implement the required interface for Rails::Generators::Migration.
def self.next_migration_number(dirname) #:nodoc:
next_migration_number = current_migration_number(dirname) + 1
- if ActiveRecord::Base.timestamped_migrations
- [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max
- else
- "%.3d" % next_migration_number
- end
+ ActiveRecord::Migration.next_migration_number(next_migration_number)
end
end
end
diff --git a/activerecord/lib/rails/generators/active_record/migration.rb b/activerecord/lib/rails/generators/active_record/migration.rb
new file mode 100644
index 0000000000..7f2f2e06a5
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record/migration.rb
@@ -0,0 +1,15 @@
+module ActiveRecord
+ module Generators
+ module Migration
+ # Implement the required interface for Rails::Generators::Migration.
+ def next_migration_number(dirname) #:nodoc:
+ next_migration_number = current_migration_number(dirname) + 1
+ if ActiveRecord::Base.timestamped_migrations
+ [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max
+ else
+ "%.3d" % next_migration_number
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
index 8ac21c1410..ce8d7eed42 100644
--- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
@@ -1,5 +1,12 @@
class <%= migration_class_name %> < ActiveRecord::Migration
- def self.up
+<%- if migration_action == 'add' -%>
+ def change
+<% attributes.each do |attribute| -%>
+ add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %>
+<%- end -%>
+ end
+<%- else -%>
+ def up
<% attributes.each do |attribute| -%>
<%- if migration_action -%>
<%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end %>
@@ -7,11 +14,12 @@ class <%= migration_class_name %> < ActiveRecord::Migration
<%- end -%>
end
- def self.down
+ def down
<% attributes.reverse.each do |attribute| -%>
<%- if migration_action -%>
<%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><% 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
index 960c29c49c..f7caa43ac8 100644
--- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb
+++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
@@ -10,6 +10,7 @@ module ActiveRecord
class_option :migration, :type => :boolean
class_option :timestamps, :type => :boolean
class_option :parent, :type => :string, :desc => "The parent class for the generated model"
+ class_option :indexes, :type => :boolean, :default => true, :desc => "Add indexes for references and belongs_to columns"
def create_migration_file
return unless options[:migration] && options[:parent].nil?
@@ -21,7 +22,7 @@ module ActiveRecord
end
def create_module_file
- return if class_path.empty?
+ return if regular_class_path.empty?
template 'module.rb', File.join('app/models', "#{class_path.join('/')}.rb") if behavior == :invoke
end
diff --git a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb
index 1f68487304..4f81a52fd0 100644
--- a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb
@@ -1,5 +1,5 @@
class <%= migration_class_name %> < ActiveRecord::Migration
- def self.up
+ def change
create_table :<%= table_name %> do |t|
<% for attribute in attributes -%>
t.<%= attribute.type %> :<%= attribute.name %>
@@ -8,9 +8,10 @@ class <%= migration_class_name %> < ActiveRecord::Migration
t.timestamps
<% end -%>
end
- end
-
- def self.down
- drop_table :<%= table_name %>
+<% if options[:indexes] -%>
+<% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
+ add_index :<%= table_name %>, :<%= attribute.name %>_id
+<% end -%>
+<% end -%>
end
end
diff --git a/activerecord/lib/rails/generators/active_record/model/templates/model.rb b/activerecord/lib/rails/generators/active_record/model/templates/model.rb
index 21ae29e9f2..5c47f8b241 100644
--- a/activerecord/lib/rails/generators/active_record/model/templates/model.rb
+++ b/activerecord/lib/rails/generators/active_record/model/templates/model.rb
@@ -1,5 +1,7 @@
+<% module_namespacing do -%>
class <%= class_name %> < <%= parent_class_name.classify %>
<% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
belongs_to :<%= attribute.name %>
<% 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
index bb4220f038..fca2908080 100644
--- a/activerecord/lib/rails/generators/active_record/model/templates/module.rb
+++ b/activerecord/lib/rails/generators/active_record/model/templates/module.rb
@@ -1,5 +1,7 @@
+<% module_namespacing do -%>
module <%= class_path.map(&:camelize).join('::') %>
def self.table_name_prefix
'<%= class_path.join('_') %>_'
end
end
+<% end -%>
diff --git a/activerecord/lib/rails/generators/active_record/observer/templates/observer.rb b/activerecord/lib/rails/generators/active_record/observer/templates/observer.rb
index b9a3004161..eaa256a9bd 100644
--- a/activerecord/lib/rails/generators/active_record/observer/templates/observer.rb
+++ b/activerecord/lib/rails/generators/active_record/observer/templates/observer.rb
@@ -1,2 +1,4 @@
+<% module_namespacing do -%>
class <%= class_name %>Observer < ActiveRecord::Observer
end
+<% end -%>
diff --git a/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb
index 919822af7b..8f0bf1ef0d 100644
--- a/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb
@@ -1,5 +1,5 @@
class <%= migration_class_name %> < ActiveRecord::Migration
- def self.up
+ def up
create_table :<%= session_table_name %> do |t|
t.string :session_id, :null => false
t.text :data
@@ -10,7 +10,7 @@ class <%= migration_class_name %> < ActiveRecord::Migration
add_index :<%= session_table_name %>, :updated_at
end
- def self.down
+ def down
drop_table :<%= session_table_name %>
end
end
diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
new file mode 100644
index 0000000000..1c2942170e
--- /dev/null
+++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
@@ -0,0 +1,36 @@
+module ActiveRecord
+ class Base
+ def self.fake_connection(config)
+ ConnectionAdapters::FakeAdapter.new nil, logger
+ end
+ end
+
+ module ConnectionAdapters
+ class FakeAdapter < AbstractAdapter
+ attr_accessor :tables, :primary_keys
+
+ def initialize(connection, logger)
+ super
+ @tables = []
+ @primary_keys = {}
+ @columns = Hash.new { |h,k| h[k] = [] }
+ end
+
+ def primary_key(table)
+ @primary_keys[table]
+ end
+
+ def merge_column(table_name, name, sql_type = nil, options = {})
+ @columns[table_name] << ActiveRecord::ConnectionAdapters::Column.new(
+ name.to_s,
+ options[:default],
+ sql_type.to_s,
+ options[:null])
+ end
+
+ def columns(table_name, message)
+ @columns[table_name]
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb
index 646aa88d80..49b2e945c3 100644
--- a/activerecord/test/cases/adapter_test.rb
+++ b/activerecord/test/cases/adapter_test.rb
@@ -141,16 +141,4 @@ class AdapterTest < ActiveRecord::TestCase
end
end
end
-
- def test_add_limit_offset_should_sanitize_sql_injection_for_limit_without_comas
- sql_inject = "1 select * from schema"
- assert_no_match(/schema/, @connection.add_limit_offset!("", :limit=>sql_inject))
- assert_no_match(/schema/, @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7))
- end
-
- def test_add_limit_offset_should_sanitize_sql_injection_for_limit_with_comas
- sql_inject = "1, 7 procedure help()"
- assert_no_match(/procedure/, @connection.add_limit_offset!("", :limit=>sql_inject))
- assert_no_match(/procedure/, @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7))
- end
end
diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
index 8e4842a1b6..eb3f8143e7 100644
--- a/activerecord/test/cases/adapters/mysql/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql/connection_test.rb
@@ -41,13 +41,72 @@ class MysqlConnectionTest < ActiveRecord::TestCase
sleep 2
@connection.verify!
assert @connection.active?
- end
+ end
+
+ def test_bind_value_substitute
+ bind_param = @connection.substitute_for('foo', [])
+ 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")')
+ 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 Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
+ if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
def test_multi_results
rows = ActiveRecord::Base.connection.select_rows('CALL ten();')
assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
+ assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'"
end
end
diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
index 90d8b0d923..43015098c9 100644
--- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
@@ -78,24 +78,6 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
- #fixtures :group
-
- def test_fixtures
- f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
-
- assert_nothing_raised {
- f.each do |x|
- x.delete_existing_fixtures
- end
- }
-
- assert_nothing_raised {
- f.each do |x|
- x.insert_fixtures
- end
- }
- end
-
#activerecord model class with reserved-word table name
def test_activerecord_model
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
@@ -105,9 +87,9 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
assert_nothing_raised { x.save }
x.order = 'y'
assert_nothing_raised { x.save }
- assert_nothing_raised { y = Group.find_by_order('y') }
- assert_nothing_raised { y = Group.find(1) }
- x = Group.find(1)
+ assert_nothing_raised { Group.find_by_order('y') }
+ assert_nothing_raised { Group.find(1) }
+ Group.find(1)
end
# has_one association with reserved-word table name
diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb
new file mode 100644
index 0000000000..c6c1d1dad5
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/schema_test.rb
@@ -0,0 +1,36 @@
+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(Post) do
+ set_table_name "#{db}.#{table}"
+ def self.name; 'Post'; end
+ end
+ end
+
+ def test_schema
+ assert @omgpost.find(:first)
+ 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
+ end if current_adapter?(:MysqlAdapter)
+ 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 0000000000..3ca2917ca4
--- /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/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
index b973da621b..26091c713b 100644
--- a/activerecord/test/cases/adapters/mysql2/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -27,7 +27,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase
sleep 2
@connection.verify!
assert @connection.active?
- end
+ end
private
diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
index 90d8b0d923..1efa7deaeb 100644
--- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
@@ -78,24 +78,6 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
- #fixtures :group
-
- def test_fixtures
- f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
-
- assert_nothing_raised {
- f.each do |x|
- x.delete_existing_fixtures
- end
- }
-
- assert_nothing_raised {
- f.each do |x|
- x.insert_fixtures
- end
- }
- end
-
#activerecord model class with reserved-word table name
def test_activerecord_model
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
index 7b72151b57..b0a4a4e39d 100644
--- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
@@ -5,6 +5,8 @@ module ActiveRecord
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, data character varying(255))')
end
def test_table_alias_length
@@ -12,6 +14,55 @@ module ActiveRecord
@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_for
+ bind = @connection.substitute_for(nil, [])
+ assert_equal Arel.sql('$1'), bind
+
+ bind = @connection.substitute_for(nil, [nil])
+ assert_equal Arel.sql('$2'), bind
+ 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
index 6f372edc38..d5e1838543 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb
@@ -43,6 +43,36 @@ class SchemaAuthorizationTest < ActiveRecord::TestCase
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
@@ -78,7 +108,7 @@ class SchemaAuthorizationTest < ActiveRecord::TestCase
private
def set_session_auth auth = nil
- @connection.execute "SET SESSION AUTHORIZATION #{auth || 'default'}"
+ @connection.session_auth = auth || 'default'
end
end
diff --git a/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb b/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb
index ce0b2f5f5b..d1fc470907 100644
--- a/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite/sqlite_adapter_test.rb
@@ -1,8 +1,13 @@
+# encoding: utf-8
require "cases/helper"
+require 'models/binary'
module ActiveRecord
module ConnectionAdapters
class SQLiteAdapterTest < ActiveRecord::TestCase
+ class DualEncoding < ActiveRecord::Base
+ end
+
def setup
@ctx = Base.sqlite3_connection :database => ':memory:',
:adapter => 'sqlite3',
@@ -15,6 +20,20 @@ module ActiveRecord
eosql
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
+ end
+
def test_execute
@ctx.execute "INSERT INTO items (number) VALUES (10)"
records = @ctx.execute "SELECT * FROM items"
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 934cf72f72..b8abdface4 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -3,6 +3,17 @@ require "cases/helper"
module ActiveRecord
module ConnectionAdapters
class SQLite3AdapterTest < ActiveRecord::TestCase
+ def setup
+ @conn = Base.sqlite3_connection :database => ':memory:',
+ :adapter => 'sqlite3',
+ :timeout => 100
+ end
+
+ def test_primary_key_returns_nil_for_no_pk
+ @conn.exec_query('create table ex(id int, data string)')
+ assert_nil @conn.primary_key('ex')
+ end
+
def test_connection_no_db
assert_raises(ArgumentError) do
Base.sqlite3_connection {}
@@ -38,18 +49,58 @@ module ActiveRecord
end
def test_connect
- conn = Base.sqlite3_connection :database => ':memory:',
- :adapter => 'sqlite3',
- :timeout => 100
- assert conn, 'should have connection'
+ assert @conn, 'should have connection'
end
# sqlite3 defaults to UTF-8 encoding
def test_encoding
- conn = Base.sqlite3_connection :database => ':memory:',
- :adapter => 'sqlite3',
- :timeout => 100
- assert_equal 'UTF-8', conn.encoding
+ assert_equal 'UTF-8', @conn.encoding
+ end
+
+ def test_bind_value_substitute
+ bind_param = @conn.substitute_for('foo', [])
+ 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
end
end
diff --git a/activerecord/test/cases/aggregations_test.rb b/activerecord/test/cases/aggregations_test.rb
index 9e285e57dc..3e0e6dce2c 100644
--- a/activerecord/test/cases/aggregations_test.rb
+++ b/activerecord/test/cases/aggregations_test.rb
@@ -99,7 +99,7 @@ class AggregationsTest < ActiveRecord::TestCase
customers(:zaphod).save
customers(:zaphod).reload
assert_kind_of Address, customers(:zaphod).address
- assert customers(:zaphod).address.street.nil?
+ assert_nil customers(:zaphod).address.street
end
def test_nil_assignment_results_in_nil
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index a1ce9b1689..9006914508 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -17,12 +17,12 @@ require 'models/essay'
class BelongsToAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
:developers_projects, :computers, :authors, :author_addresses,
- :posts, :tags, :taggings, :comments
+ :posts, :tags, :taggings, :comments, :sponsors, :members
def test_belongs_to
Client.find(3).firm.name
assert_equal companies(:first_firm).name, Client.find(3).firm.name
- assert !Client.find(3).firm.nil?, "Microsoft should have a firm"
+ assert_not_nil Client.find(3).firm, "Microsoft should have a firm"
end
def test_belongs_to_with_primary_key
@@ -50,11 +50,6 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised { account.firm = account.firm }
end
- def test_triple_equality
- assert Client.find(3).firm === Firm
- assert Firm === Client.find(3).firm
- end
-
def test_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
@@ -75,23 +70,17 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
end
def test_eager_loading_with_primary_key
- apple = Firm.create("name" => "Apple")
- citibank = Client.create("name" => "Citibank", :firm_name => "Apple")
+ Firm.create("name" => "Apple")
+ Client.create("name" => "Citibank", :firm_name => "Apple")
citibank_result = Client.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key)
- assert_not_nil citibank_result.instance_variable_get("@firm_with_primary_key")
+ assert citibank_result.association_cache.key?(:firm_with_primary_key)
end
- def test_no_unexpected_aliasing
- first_firm = companies(:first_firm)
- another_firm = companies(:another_firm)
-
- citibank = Account.create("credit_limit" => 10)
- citibank.firm = first_firm
- original_proxy = citibank.firm
- citibank.firm = another_firm
-
- assert_equal first_firm.object_id, original_proxy.target.object_id
- assert_equal another_firm.object_id, citibank.firm.target.object_id
+ def test_eager_loading_with_primary_key_as_symbol
+ Firm.create("name" => "Apple")
+ Client.create("name" => "Citibank", :firm_name => "Apple")
+ citibank_result = Client.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key_symbols)
+ assert citibank_result.association_cache.key?(:firm_with_primary_key_symbols)
end
def test_creating_the_belonging_object
@@ -126,6 +115,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal apple.name, client.firm_name
end
+ def test_create!
+ client = Client.create!(:name => "Jimmy")
+ account = client.create_account!(:credit_limit => 10)
+ assert_equal account, client.account
+ assert account.persisted?
+ client.save
+ client.reload
+ assert_equal account, client.account
+ end
+
+ def test_failing_create!
+ client = Client.create!(:name => "Jimmy")
+ assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
+ assert_not_nil client.account
+ assert client.account.new_record?
+ end
+
def test_natural_assignment_to_nil
client = Client.find(3)
client.firm = nil
@@ -152,6 +158,15 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
end
+ def test_with_polymorphic_and_condition
+ sponsor = Sponsor.create
+ member = Member.create :name => "Bert"
+ sponsor.sponsorable = member
+
+ assert_equal member, sponsor.sponsorable
+ assert_nil sponsor.sponsorable_with_conditions
+ end
+
def test_with_select
assert_equal Company.find(2).firm_with_select.attributes.size, 1
assert_equal Company.find(2, :include => :firm_with_select ).firm_with_select.attributes.size, 1
@@ -168,17 +183,6 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
end
- def test_belongs_to_with_primary_key_counter
- debate = Topic.create("title" => "debate")
- assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet"
-
- trash = debate.replies_with_primary_key.create("title" => "blah!", "content" => "world around!")
- assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply created"
-
- trash.destroy
- assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
- end
-
def test_belongs_to_counter_with_assigning_nil
p = Post.find(1)
c = Comment.find(1)
@@ -191,16 +195,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal 1, Post.find(p.id).comments.size
end
- def test_belongs_to_with_primary_key_counter_with_assigning_nil
- debate = Topic.create("title" => "debate")
- reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")
+ def test_belongs_to_with_primary_key_counter
+ debate = Topic.create("title" => "debate")
+ debate2 = Topic.create("title" => "debate2")
+ reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")
- assert_equal debate.title, reply.parent_title
- assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count")
+ 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, Topic.find(debate.id).send(:read_attribute, "replies_count")
+ assert_equal 0, debate.reload.replies_count
+ assert_equal 0, debate2.reload.replies_count
end
def test_belongs_to_counter_with_reassigning
@@ -278,10 +289,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm = firm
- assert final_cut.new_record?
+ assert !final_cut.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !firm.new_record?
+ assert final_cut.persisted?
+ assert firm.persisted?
assert_equal firm, final_cut.firm
assert_equal firm, final_cut.firm(true)
end
@@ -290,10 +301,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm_with_primary_key = firm
- assert final_cut.new_record?
+ assert !final_cut.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !firm.new_record?
+ 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
@@ -304,13 +315,21 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal Firm.find(:first, :order => "id"), c.firm_with_basic_id
end
- def test_forgetting_the_load_when_foreign_key_enters_late
- c = Client.new
- assert_nil c.firm_with_basic_id
+ def test_setting_foreign_key_after_nil_target_loaded
+ client = Client.new
+ client.firm_with_basic_id
+ client.firm_id = 1
- c.firm_id = 1
- # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- assert_equal Firm.find(:first, :order => "id"), c.firm_with_basic_id
+ assert_equal companies(:first_firm), client.firm_with_basic_id
+ end
+
+ def test_polymorphic_setting_foreign_key_after_nil_target_loaded
+ sponsor = Sponsor.new
+ sponsor.sponsorable
+ sponsor.sponsorable_id = 1
+ sponsor.sponsorable_type = "Member"
+
+ assert_equal members(:groucho), sponsor.sponsorable
end
def test_field_name_same_as_foreign_key
@@ -412,6 +431,18 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_nil sponsor.sponsorable_id
end
+ def test_assignment_updates_foreign_id_field_for_new_and_saved_records
+ client = Client.new
+ saved_firm = Firm.create :name => "Saved"
+ new_firm = Firm.new
+
+ client.firm = saved_firm
+ assert_equal saved_firm.id, client.client_of
+
+ client.firm = new_firm
+ assert_nil client.client_of
+ end
+
def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records
essay = Essay.new
saved_writer = Author.create(:name => "David")
@@ -474,4 +505,125 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
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_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 'post.reload.taggings_count', -1 do
+ assert_difference 'comment.reload.taggings_count', +1 do
+ tagging.taggable = comment
+ end
+ end
+ end
+
+ def test_polymorphic_with_custom_foreign_type
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ groucho = members(:groucho)
+ other = members(:some_other_guy)
+
+ assert_equal groucho, sponsor.sponsorable
+ assert_equal groucho, sponsor.thing
+
+ sponsor.thing = other
+
+ assert_equal other, sponsor.sponsorable
+ assert_equal other, sponsor.thing
+
+ sponsor.sponsorable = groucho
+
+ assert_equal groucho, sponsor.sponsorable
+ assert_equal groucho, sponsor.thing
+ end
+
+ def test_build_with_conditions
+ client = companies(:second_client)
+ firm = client.build_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_bang_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm!
+
+ assert_equal "Bob", firm.name
+ end
end
diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb
index 15537d6940..2d0d4541b4 100644
--- a/activerecord/test/cases/associations/callbacks_test.rb
+++ b/activerecord/test/cases/associations/callbacks_test.rb
@@ -3,6 +3,7 @@ require 'models/post'
require 'models/author'
require 'models/project'
require 'models/developer'
+require 'models/company'
class AssociationCallbacksTest < ActiveRecord::TestCase
fixtures :posts, :authors, :projects, :developers
@@ -72,7 +73,7 @@ class AssociationCallbacksTest < ActiveRecord::TestCase
def test_has_many_callbacks_for_save_on_parent
jack = Author.new :name => "Jack"
- post = jack.posts_with_callbacks.build :title => "Call me back!", :body => "Before you wake up and after you sleep"
+ 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
@@ -81,6 +82,14 @@ class AssociationCallbacksTest < ActiveRecord::TestCase
assert_equal callback_log, jack.post_log
end
+ def test_has_many_callbacks_for_destroy_on_parent
+ firm = Firm.create! :name => "Firm"
+ client = firm.clients.create! :name => "Client"
+ firm.destroy
+
+ assert_equal ["before_remove#{client.id}", "after_remove#{client.id}"], firm.log
+ end
+
def test_has_and_belongs_to_many_add_callback
david = developers(:david)
ar = projects(:active_record)
@@ -149,7 +158,7 @@ class AssociationCallbacksTest < ActiveRecord::TestCase
assert !@david.unchangable_posts.include?(@authorless)
begin
@david.unchangable_posts << @authorless
- rescue Exception => e
+ rescue Exception
end
assert @david.post_log.empty?
assert !@david.unchangable_posts.include?(@authorless)
diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
index b93e49613d..39e8a7960a 100644
--- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
+++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
@@ -3,28 +3,30 @@ 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'
class CascadedEagerLoadingTest < ActiveRecord::TestCase
- fixtures :authors, :mixins, :companies, :posts, :topics, :accounts, :comments, :categorizations, :people
+ fixtures :authors, :mixins, :companies, :posts, :topics, :accounts, :comments,
+ :categorizations, :people, :categories
def test_eager_association_loading_with_cascaded_two_levels
authors = Author.find(:all, :include=>{:posts=>:comments}, :order=>"authors.id")
- assert_equal 2, authors.size
+ assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
- assert_equal 1, authors[1].posts.size
- assert_equal 9, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ 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.find(:all, :include=>[{:posts=>:comments}, :categorizations], :order=>"authors.id")
- assert_equal 2, authors.size
+ assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
- assert_equal 1, authors[1].posts.size
- assert_equal 9, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ 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
@@ -35,7 +37,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).all
assert_equal 1, assert_no_queries { authors.size }
- assert_equal 9, assert_no_queries { authors[0].comments.size }
+ assert_equal 10, assert_no_queries { authors[0].comments.size }
end
def test_eager_association_loading_grafts_stashed_associations_to_correct_parent
@@ -45,6 +47,31 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
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 3, categories.count
+ assert_equal 3, categories.all.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")
+ assert_nothing_raised do
+ assert_equal 3, categories.count
+ assert_equal 3, categories.all.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")
+ assert_nothing_raised do
+ assert_equal 3, categories.count
+ assert_equal 3, categories.all.size
+ end
+ end
+
def test_eager_association_loading_with_join_for_count
authors = Author.joins(:special_posts).includes([:posts, :categorizations])
@@ -54,15 +81,15 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations
authors = Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id")
- assert_equal 2, authors.size
+ assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
- assert_equal 1, authors[1].posts.size
- assert_equal 9, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ 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.find(:all, :include=>{:posts=>[:comments, :author]}, :order=>"authors.id")
- assert_equal 2, authors.size
+ 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
@@ -111,7 +138,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_multiple_stis_and_order
- author = Author.find(:first, :include => { :posts => [ :special_comments , :very_special_comment ] }, :order => 'authors.name, comments.body, very_special_comments_posts.body', :conditions => 'posts.id = 4')
+ author = Author.find(:first, :include => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :conditions => 'posts.id = 4')
assert_equal authors(:david), author
assert_no_queries do
author.posts.first.special_comments
@@ -130,9 +157,9 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
def test_eager_association_loading_where_first_level_returns_nil
authors = Author.find(:all, :include => {:post_about_thinking => :comments}, :order => 'authors.id DESC')
- assert_equal [authors(:mary), authors(:david)], authors
+ assert_equal [authors(:bob), authors(:mary), authors(:david)], authors
assert_no_queries do
- authors[1].post_about_thinking.comments.first
+ authors[2].post_about_thinking.comments.first
end
end
end
diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
index b124a2bfc3..d75791cab9 100644
--- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
+++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
@@ -17,7 +17,7 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase
def generate_test_objects
post = Namespaced::Post.create( :title => 'Great stuff', :body => 'This is not', :author_id => 1 )
- tagging = Tagging.create( :taggable => post )
+ Tagging.create( :taggable => post )
end
def test_class_names
@@ -27,6 +27,7 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase
post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging )
assert_nil post.tagging
+ ActiveRecord::IdentityMap.clear
ActiveRecord::Base.store_full_sti_class = true
post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging )
assert_instance_of Tagging, post.tagging
diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
index c7671a8c22..2cf9f89c3c 100644
--- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb
+++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -1,9 +1,11 @@
require 'cases/helper'
require 'models/post'
+require 'models/tag'
require 'models/author'
require 'models/comment'
require 'models/category'
require 'models/categorization'
+require 'models/tagging'
require 'active_support/core_ext/array/random_access'
module Remembered
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 40859d425f..40c82f2fb8 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -17,12 +17,27 @@ require 'models/subscription'
require 'models/book'
require 'models/developer'
require 'models/project'
+require 'models/member'
+require 'models/membership'
+require 'models/club'
+require 'models/categorization'
+require 'models/sponsor'
class EagerAssociationTest < ActiveRecord::TestCase
fixtures :posts, :comments, :authors, :author_addresses, :categories, :categories_posts,
- :companies, :accounts, :tags, :taggings, :people, :readers,
+ :companies, :accounts, :tags, :taggings, :people, :readers, :categorizations,
:owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books,
- :developers, :projects, :developers_projects
+ :developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors
+
+ def setup
+ # preheat table existence caches
+ Comment.find_by_id(1)
+ end
+
+ def test_eager_with_has_one_through_join_model_with_conditions_on_the_through
+ member = Member.find(members(:some_other_guy).id, :include => :favourite_club)
+ assert_nil member.favourite_club
+ end
def test_loading_with_one_association
posts = Post.find(:all, :include => :comments)
@@ -53,8 +68,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_with_ordering
list = Post.find(:all, :include => :comments, :order => "posts.id DESC")
- [:eager_other, :sti_habtm, :sti_post_and_comments, :sti_comments,
- :authorless, :thinking, :welcome
+ [: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
@@ -79,6 +94,57 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
end
+ def test_preloading_has_many_in_multiple_queries_with_more_ids_than_database_can_handle
+ Post.connection.expects(:in_clause_length).at_least_once.returns(5)
+ posts = Post.find(:all, :include=>:comments)
+ assert_equal 11, posts.size
+ end
+
+ def test_preloading_has_many_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
+ Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
+ posts = Post.find(:all, :include=>:comments)
+ assert_equal 11, posts.size
+ end
+
+ def test_preloading_habtm_in_multiple_queries_with_more_ids_than_database_can_handle
+ Post.connection.expects(:in_clause_length).at_least_once.returns(5)
+ posts = Post.find(:all, :include=>:categories)
+ assert_equal 11, posts.size
+ end
+
+ def test_preloading_habtm_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
+ Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
+ posts = Post.find(:all, :include=>:categories)
+ assert_equal 11, posts.size
+ end
+
+ def test_load_associated_records_in_one_query_when_adapter_has_no_limit
+ Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
+
+ post = 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
+ Post.connection.expects(:in_clause_length).at_least_once.returns(1)
+
+ post1, post2 = posts(:welcome), posts(:thinking)
+ assert_queries(3) do
+ Post.includes(:comments).where(:id => [post1.id, post2.id]).to_a
+ end
+ end
+
+ def test_load_associated_records_in_one_query_when_a_few_ids_passed
+ Post.connection.expects(:in_clause_length).at_least_once.returns(3)
+
+ post = posts(:welcome)
+ assert_queries(2) do
+ Post.includes(:comments).where(:id => post.id).to_a
+ end
+ 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")
@@ -118,7 +184,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
author = authors(:david)
post = author.post_about_thinking_with_last_comment
last_comment = post.last_comment
- author = assert_queries(3) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments
+ author = assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments
assert_no_queries do
assert_equal post, author.post_about_thinking_with_last_comment
assert_equal last_comment, author.post_about_thinking_with_last_comment.last_comment
@@ -129,7 +195,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
post = posts(:welcome)
author = post.author
author_address = author.author_address
- post = assert_queries(3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address
+ post = assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address
assert_no_queries do
assert_equal author, post.author_with_address
assert_equal author_address, post.author_with_address.author_address
@@ -145,6 +211,15 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
end
+ def test_finding_with_includes_on_null_belongs_to_polymorphic_association
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ sponsor.update_attributes!(:sponsorable => nil)
+ sponsor = assert_queries(1) { Sponsor.find(sponsor.id, :include => :sponsorable) }
+ assert_no_queries do
+ assert_equal nil, sponsor.sponsorable
+ end
+ end
+
def test_loading_from_an_association
posts = authors(:david).posts.find(:all, :include => :comments, :order => "posts.id")
assert_equal 2, posts.first.comments.size
@@ -174,7 +249,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to
comments = Comment.find(:all, :include => :post)
- assert_equal 10, comments.length
+ 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)
@@ -323,7 +398,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_through_a_belongs_to_association
author = authors(:mary)
- post = Post.create!(:author => author, :title => "TITLE", :body => "BODY")
+ 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.find(:all, :include => :author_favorites)
@@ -450,6 +525,22 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert posts[1].categories.include?(categories(:general))
end
+ # This is only really relevant when the identity map is off. 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 == posts(:welcome) }
+ post2 = technology.posts.to_a.find { |p| p == posts(: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.find(:all,
:include => :comments,
@@ -521,7 +612,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_inheritance
- posts = SpecialPost.find(:all, :include => [ :comments ])
+ SpecialPost.find(:all, :include => [ :comments ])
end
def test_eager_has_one_with_association_inheritance
@@ -532,7 +623,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_has_many_with_association_inheritance
post = Post.find(4, :include => [ :special_comments ])
post.special_comments.each do |special_comment|
- assert_equal "SpecialComment", special_comment.class.to_s
+ assert special_comment.is_a?(SpecialComment)
end
end
@@ -561,16 +652,16 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_invalid_association_reference
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=> :monkeys )
+ Post.find(6, :include=> :monkeys )
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=>[ :monkeys ])
+ Post.find(6, :include=>[ :monkeys ])
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=>[ 'monkeys' ])
+ Post.find(6, :include=>[ 'monkeys' ])
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
- post = Post.find(6, :include=>[ :monkeys, :elephants ])
+ Post.find(6, :include=>[ :monkeys, :elephants ])
}
end
@@ -584,8 +675,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_limited_eager_with_multiple_order_columns
- assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title), posts.id', :limit => 2, :offset => 1)
- assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC, posts.id', :limit => 2, :offset => 1)
+ assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1)
+ assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1)
end
def test_limited_eager_with_numeric_in_association
@@ -593,7 +684,11 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_preload_with_interpolation
- assert_equal [comments(:greetings)], Post.find(posts(:welcome).id, :include => :comments_with_interpolated_conditions).comments_with_interpolated_conditions
+ post = Post.includes(:comments_with_interpolated_conditions).find(posts(:welcome).id)
+ assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions
+
+ post = Post.joins(:comments_with_interpolated_conditions).find(posts(:welcome).id)
+ assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions
end
def test_polymorphic_type_condition
@@ -726,8 +821,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
posts = assert_queries(2) do
Post.find(:all, :joins => :comments, :include => :author, :order => 'comments.id DESC')
end
- assert_equal posts(:eager_other), posts[0]
- assert_equal authors(:mary), assert_no_queries { posts[0].author}
+ 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
@@ -737,18 +832,18 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id')
end
assert_equal posts(:welcome, :thinking), posts
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id')
end
assert_equal posts(:welcome, :thinking), posts
@@ -762,7 +857,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
end
assert_equal [posts(:welcome)], posts
@@ -779,6 +874,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_loading_with_conditions_on_join_model_preloads
+ Author.columns
+
authors = assert_queries(2) do
Author.find(:all, :include => :author_address, :joins => :comments, :conditions => "posts.title like 'Welcome%'")
end
@@ -824,25 +921,55 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_preload_has_one_using_primary_key
- expected = Firm.find(:first).account_using_primary_key
- firm = Firm.find :first, :include => :account_using_primary_key
+ expected = accounts(:signals37)
+ firm = Firm.find :first, :include => :account_using_primary_key, :order => 'companies.id'
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
end
def test_include_has_one_using_primary_key
- expected = Firm.find(1).account_using_primary_key
+ expected = accounts(:signals37)
firm = Firm.find(:all, :include => :account_using_primary_key, :order => 'accounts.id').detect {|f| f.id == 1}
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
end
- def test_preloading_empty_polymorphic_parent
+ def test_preloading_empty_belongs_to
+ c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1)
+
+ client = assert_queries(2) { Client.preload(:firm).find(c.id) }
+ assert_no_queries { assert_nil client.firm }
+ end
+
+ def test_preloading_empty_belongs_to_polymorphic
t = Tagging.create!(:taggable_type => 'Post', :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general))
- assert_queries(2) { @tagging = Tagging.preload(:taggable).find(t.id) }
- assert_no_queries { assert ! @tagging.taggable }
+ tagging = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) { Tagging.preload(:taggable).find(t.id) }
+ assert_no_queries { assert_nil tagging.taggable }
+ end
+
+ def test_preloading_through_empty_belongs_to
+ c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1)
+
+ client = assert_queries(2) { Client.preload(:accounts).find(c.id) }
+ assert_no_queries { assert client.accounts.empty? }
+ end
+
+ def test_preloading_has_many_through_with_uniq
+ mary = Author.includes(:unique_categorized_posts).where(:id => authors(:mary).id).first
+ assert_equal 1, mary.unique_categorized_posts.length
+ assert_equal 1, mary.unique_categorized_post_ids.length
+ end
+
+ def test_preloading_polymorphic_with_custom_foreign_type
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ groucho = members(:groucho)
+
+ sponsor = assert_queries(2) {
+ Sponsor.includes(:thing).where(:id => sponsor.id).first
+ }
+ assert_no_queries { assert_equal groucho, sponsor.thing }
end
end
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
index 9390633d5b..24830a661a 100644
--- a/activerecord/test/cases/associations/extension_test.rb
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -30,6 +30,11 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
assert_equal projects(:active_record), developers(:david).projects_extended_by_name_and_block.find_least_recent
end
+ def test_extension_with_scopes
+ assert_equal comments(:greetings), posts(:welcome).comments.offset(1).find_most_recent
+ assert_equal comments(:greetings), posts(:welcome).comments.not_again.find_most_recent
+ end
+
def test_marshalling_extensions
david = developers(:david)
assert_equal projects(:action_controller), david.projects.find_most_recent
@@ -46,17 +51,17 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent
end
-
- def test_extension_name
- extension = Proc.new {}
- name = :association_name
-
- assert_equal 'DeveloperAssociationNameAssociationExtension', Developer.send(:create_extension_modules, name, extension, []).first.name
- assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension',
-MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name
- assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name
- assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name
+ 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
+ private
+ def extension_name(model)
+ builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, {}) { }
+ builder.send(:wrap_block_extension)
+ builder.options[:extend].first.name
+ end
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index ed7d9a782c..73d02c9676 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -72,7 +72,7 @@ class DeveloperWithCounterSQL < ActiveRecord::Base
:join_table => "developers_projects",
:association_foreign_key => "project_id",
:foreign_key => "developer_id",
- :counter_sql => 'SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}'
+ :counter_sql => proc { "SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}" }
end
class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
@@ -101,38 +101,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal 't1', record[1]
end
- def test_should_record_timestamp_for_join_table
- setup_data_for_habtm_case
-
- con = ActiveRecord::Base.connection
- sql = 'select * from countries_treaties'
- record = con.select_rows(sql).last
- assert_not_nil record[2]
- assert_not_nil record[3]
- if current_adapter?(:Mysql2Adapter)
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[2].to_s(:db)
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[3].to_s(:db)
- else
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[2]
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[3]
- end
- end
-
- def test_should_record_timestamp_for_join_table_only_if_timestamp_should_be_recorded
- begin
- Treaty.record_timestamps = false
- setup_data_for_habtm_case
-
- con = ActiveRecord::Base.connection
- sql = 'select * from countries_treaties'
- record = con.select_rows(sql).last
- assert_nil record[2]
- assert_nil record[3]
- ensure
- Treaty.record_timestamps = true
- end
- end
-
def test_has_and_belongs_to_many
david = Developer.find(1)
@@ -218,43 +186,15 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal 2, aredridel.projects(true).size
end
- def test_adding_uses_default_values_on_join_table
- ac = projects(:action_controller)
- assert !developers(:jamis).projects.include?(ac)
- developers(:jamis).projects << ac
-
- assert developers(:jamis, :reload).projects.include?(ac)
- project = developers(:jamis).projects.detect { |p| p == ac }
- assert_equal 1, project.access_level.to_i
- end
-
- def test_habtm_attribute_access_and_respond_to
- project = developers(:jamis).projects[0]
- assert project.has_attribute?("name")
- assert project.has_attribute?("joined_on")
- assert project.has_attribute?("access_level")
- assert project.respond_to?("name")
- assert project.respond_to?("name=")
- assert project.respond_to?("name?")
- assert project.respond_to?("joined_on")
- # given that the 'join attribute' won't be persisted, I don't
- # think we should define the mutators
- #assert project.respond_to?("joined_on=")
- assert project.respond_to?("joined_on?")
- assert project.respond_to?("access_level")
- #assert project.respond_to?("access_level=")
- assert project.respond_to?("access_level?")
- end
-
def test_habtm_adding_before_save
no_of_devels = Developer.count
no_of_projects = Project.count
aredridel = Developer.new("name" => "Aredridel")
aredridel.projects.concat([Project.find(1), p = Project.new("name" => "Projekt")])
- assert aredridel.new_record?
- assert p.new_record?
+ assert !aredridel.persisted?
+ assert !p.persisted?
assert aredridel.save
- assert !aredridel.new_record?
+ 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
@@ -288,22 +228,22 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal devel.projects.last, proj
assert devel.projects.loaded?
- assert proj.new_record?
+ assert !proj.persisted?
devel.save
- assert !proj.new_record?
+ 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)
- proj1 = devel.projects.build(:name => "Make bed")
+ devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
assert_equal devel.projects.last, proj2
- assert proj2.new_record?
+ assert !proj2.persisted?
devel.save
- assert !devel.new_record?
- assert !proj2.new_record?
+ 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
@@ -316,19 +256,19 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal devel.projects.last, proj
assert !devel.projects.loaded?
- assert !proj.new_record?
+ 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)
- proj1 = devel.projects.build(:name => "Make bed")
+ devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
assert_equal devel.projects.last, proj2
- assert proj2.new_record?
+ assert !proj2.persisted?
devel.save
- assert !devel.new_record?
- assert !proj2.new_record?
+ 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
@@ -343,7 +283,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
# 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.new_record?
+ assert another_post.persisted?
assert_equal 'Yet Another Testing Title', another_post.title
end
@@ -425,38 +365,41 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_removing_associations_on_destroy
david = DeveloperWithBeforeDestroyRaise.find(1)
assert !david.projects.empty?
- assert_nothing_raised { david.destroy }
+ david.destroy
assert david.projects.empty?
assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty?
end
- def test_additional_columns_from_join_table
- assert_date_from_db Date.new(2004, 10, 10), Developer.find(1).projects.first.joined_on.to_date
- end
-
def test_destroying
david = Developer.find(1)
- active_record = Project.find(1)
+ project = Project.find(1)
david.projects.reload
assert_equal 2, david.projects.size
- assert_equal 3, active_record.developers.size
+ assert_equal 3, project.developers.size
- assert_difference "Project.count", -1 do
- david.projects.destroy(active_record)
+ assert_no_difference "Project.count" do
+ david.projects.destroy(project)
end
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id} AND project_id = #{project.id}")
+ assert join_records.empty?
+
assert_equal 1, david.reload.projects.size
assert_equal 1, david.projects(true).size
end
- def test_destroying_array
+ def test_destroying_many
david = Developer.find(1)
david.projects.reload
+ projects = Project.all
- assert_difference "Project.count", -Project.count do
- david.projects.destroy(Project.find(:all))
+ assert_no_difference "Project.count" do
+ david.projects.destroy(*projects)
end
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
+ assert join_records.empty?
+
assert_equal 0, david.reload.projects.size
assert_equal 0, david.projects(true).size
end
@@ -465,7 +408,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
david = Developer.find(1)
david.projects.reload
assert !david.projects.empty?
- david.projects.destroy_all
+
+ assert_no_difference "Project.count" do
+ david.projects.destroy_all
+ end
+
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
+ assert join_records.empty?
+
assert david.projects.empty?
assert david.projects(true).empty?
end
@@ -559,24 +509,12 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_dynamic_find_should_respect_association_order
# Developers are ordered 'name DESC, id DESC'
- low_id_jamis = developers(:jamis)
- middle_id_jamis = developers(:poor_jamis)
high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
assert_equal high_id_jamis, projects(:active_record).developers.find(:first, :conditions => "name = 'Jamis'")
assert_equal high_id_jamis, projects(:active_record).developers.find_by_name('Jamis')
end
- def test_dynamic_find_order_should_override_association_order
- # Developers are ordered 'name DESC, id DESC'
- low_id_jamis = developers(:jamis)
- middle_id_jamis = developers(:poor_jamis)
- high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
-
- assert_equal low_id_jamis, projects(:active_record).developers.find(:first, :conditions => "name = 'Jamis'", :order => 'id')
- assert_equal low_id_jamis, projects(:active_record).developers.find_by_name('Jamis', :order => 'id')
- end
-
def test_dynamic_find_all_should_respect_association_order
# Developers are ordered 'name DESC, id DESC'
low_id_jamis = developers(:jamis)
@@ -587,14 +525,9 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal [high_id_jamis, middle_id_jamis, low_id_jamis], projects(:active_record).developers.find_all_by_name('Jamis')
end
- def test_dynamic_find_all_order_should_override_association_order
- # Developers are ordered 'name DESC, id DESC'
- low_id_jamis = developers(:jamis)
- middle_id_jamis = developers(:poor_jamis)
- high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
-
- assert_equal [low_id_jamis, middle_id_jamis, high_id_jamis], projects(:active_record).developers.find(:all, :conditions => "name = 'Jamis'", :order => 'id')
- assert_equal [low_id_jamis, middle_id_jamis, high_id_jamis], projects(:active_record).developers.find_all_by_name('Jamis', :order => 'id')
+ def test_find_should_append_to_association_order
+ ordered_developers = projects(:active_record).developers.order('projects.id')
+ assert_equal ['developers.name desc, developers.id desc', 'projects.id'], ordered_developers.order_values
end
def test_dynamic_find_all_should_respect_association_limit
@@ -625,11 +558,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_in_association_with_options
- developers = projects(:active_record).developers.find(:all)
+ developers = projects(:active_record).developers.all
assert_equal 3, developers.size
- assert_equal developers(:poor_jamis), projects(:active_record).developers.find(:first, :conditions => "salary < 10000")
- assert_equal developers(:jamis), projects(:active_record).developers.find(:first, :order => "salary DESC")
+ assert_equal developers(:poor_jamis), projects(:active_record).developers.where("salary < 10000").first
end
def test_replace_with_less
@@ -693,25 +625,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_respond_to categories(:technology).select_testing_posts.find(:first), :correctness_marker
end
- def test_updating_attributes_on_rich_associations
- david = projects(:action_controller).developers.first
- david.name = "DHH"
- assert_raise(ActiveRecord::ReadOnlyRecord) { david.save! }
- end
-
- def test_updating_attributes_on_rich_associations_with_limited_find_from_reflection
- david = projects(:action_controller).selected_developers.first
- david.name = "DHH"
- assert_nothing_raised { david.save! }
- end
-
-
- def test_updating_attributes_on_rich_associations_with_limited_find
- david = projects(:action_controller).developers.find(:all, :select => "developers.*").first
- david.name = "DHH"
- assert david.save!
- end
-
def test_join_table_alias
assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size
end
@@ -729,12 +642,12 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_find_grouped
all_posts_from_category1 = Post.find(:all, :conditions => "category_id = 1", :joins => :categories)
grouped_posts_of_category1 = Post.find(:all, :conditions => "category_id = 1", :group => "author_id", :select => 'count(posts.id) as posts_count', :joins => :categories)
- assert_equal 4, all_posts_from_category1.size
- assert_equal 1, grouped_posts_of_category1.size
+ assert_equal 5, all_posts_from_category1.size
+ assert_equal 2, grouped_posts_of_category1.size
end
def test_find_scoped_grouped
- assert_equal 4, categories(:general).posts_grouped_by_title.size
+ assert_equal 5, categories(:general).posts_grouped_by_title.size
assert_equal 1, categories(:technology).posts_grouped_by_title.size
end
@@ -858,10 +771,29 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
david = Developer.find(1)
# clear cache possibly created by other tests
david.projects.reset_column_information
- assert_queries(0) { david.projects.columns; david.projects.columns }
- # and again to verify that reset_column_information clears the cache correctly
+
+ # One query for columns, one for primary key
+ assert_queries(2) { david.projects.columns; david.projects.columns }
+
+ ## and again to verify that reset_column_information clears the cache correctly
david.projects.reset_column_information
- assert_queries(0) { david.projects.columns; david.projects.columns }
+ assert_queries(2) { david.projects.columns; david.projects.columns }
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause
+ 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
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index ac2021c369..ad774eb9ce 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -13,6 +13,8 @@ require 'models/reader'
require 'models/tagging'
require 'models/invoice'
require 'models/line_item'
+require 'models/car'
+require 'models/bulb'
class HasManyAssociationsTestForCountWithFinderSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
@@ -41,12 +43,61 @@ end
class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
:developers_projects, :topics, :authors, :comments,
- :people, :posts, :readers, :taggings
+ :people, :posts, :readers, :taggings, :cars
def setup
Client.destroyed_client_ids.clear
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
+
+ # When creating objects on the association, we must not do it within a scope (even though it
+ # would be convenient), because this would cause that scope to be applied to any callbacks etc.
+ def test_build_and_create_should_not_happen_within_scope
+ car = cars(:honda)
+ original_scoped_methods = Bulb.scoped_methods
+
+ bulb = car.bulbs.build
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = car.bulbs.create
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = car.bulbs.create!
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+ end
+
+ def test_no_sql_should_be_fired_if_association_already_loaded
+ Car.create(:name => 'honda')
+ bulbs = Car.first.bulbs
+ bulbs.inspect # to load all instances of bulbs
+
+ assert_no_queries do
+ bulbs.first()
+ bulbs.first({})
+ end
+
+ assert_no_queries do
+ bulbs.last()
+ bulbs.last({})
+ end
+ end
+
def test_create_resets_cached_counters
person = Person.create!(:first_name => 'tenderlove')
post = Post.first
@@ -54,7 +105,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
- reader = person.readers.create(:post_id => post.id)
+ person.readers.create(:post_id => post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
@@ -69,7 +120,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
- reader = person.readers.find_or_create_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
@@ -128,6 +179,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 2, companies(:first_firm).limited_clients.find(:all, :limit => nil).size
end
+ def test_find_should_append_to_association_order
+ ordered_clients = companies(:first_firm).clients_sorted_desc.order('companies.id')
+ assert_equal ['id DESC', 'companies.id'], ordered_clients.order_values
+ 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
@@ -137,21 +193,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
end
- def test_dynamic_find_order_should_override_association_order
- assert_equal companies(:first_client), companies(:first_firm).clients_sorted_desc.find(:first, :conditions => "type = 'Client'", :order => 'id')
- assert_equal companies(:first_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client', :order => 'id')
- end
-
def test_dynamic_find_all_should_respect_association_order
assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.find(:all, :conditions => "type = 'Client'")
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_order_should_override_association_order
- assert_equal [companies(:first_client), companies(:second_client)], companies(:first_firm).clients_sorted_desc.find(:all, :conditions => "type = 'Client'", :order => 'id')
- assert_equal [companies(:first_client), companies(:second_client)], companies(:first_firm).clients_sorted_desc.find_all_by_type('Client', :order => 'id')
- end
-
def test_dynamic_find_all_should_respect_association_limit
assert_equal 1, companies(:first_firm).limited_clients.find(:all, :conditions => "type = 'Client'").length
assert_equal 1, companies(:first_firm).limited_clients.find_all_by_type('Client').length
@@ -173,7 +219,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
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.new_record?
+ assert another.persisted?
end
def test_cant_save_has_many_readonly_association
@@ -233,7 +279,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_counting_using_finder_sql
assert_equal 2, Firm.find(4).clients_using_sql.count
- assert_equal 2, Firm.find(4).clients_using_multiline_sql.count
end
def test_belongs_to_sanity
@@ -388,7 +433,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_adding_using_create
first_firm = companies(:first_firm)
assert_equal 2, first_firm.plain_clients.size
- natural = first_firm.plain_clients.create(:name => "Natural Company")
+ 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
@@ -439,7 +484,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
@@ -469,7 +514,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_build_followed_by_save_does_not_load_target
- new_client = companies(:first_firm).clients_of_firm.build("name" => "Another Client")
+ companies(:first_firm).clients_of_firm.build("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
@@ -494,7 +539,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
@@ -529,7 +574,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
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.new_record?
+ 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
@@ -540,7 +585,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_create_followed_by_save_does_not_load_target
- new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
@@ -549,7 +594,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
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.new_record?
+ assert !the_client.persisted?
end
def test_find_or_create_updates_size
@@ -584,7 +629,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal topic.replies.to_a.size, topic.replies_count
end
- def test_deleting_updates_counter_cache_without_dependent_destroy
+ def test_deleting_updates_counter_cache_without_dependent_option
post = posts(:welcome)
assert_difference "post.reload.taggings_count", -1 do
@@ -592,6 +637,24 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_deleting_updates_counter_cache_with_dependent_delete_all
+ post = posts(:welcome)
+ post.update_attribute(:taggings_with_delete_all_count, post.taggings_count)
+
+ assert_difference "post.reload.taggings_with_delete_all_count", -1 do
+ post.taggings_with_delete_all.delete(post.taggings_with_delete_all.first)
+ end
+ end
+
+ def test_deleting_updates_counter_cache_with_dependent_destroy
+ post = posts(:welcome)
+ post.update_attribute(:taggings_with_destroy_count, post.taggings_count)
+
+ assert_difference "post.reload.taggings_with_destroy_count", -1 do
+ post.taggings_with_destroy.delete(post.taggings_with_destroy.first)
+ end
+ end
+
def test_deleting_a_collection
force_signal37_to_load_all_clients_of_firm
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
@@ -604,8 +667,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_delete_all
force_signal37_to_load_all_clients_of_firm
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
- assert_equal 2, companies(:first_firm).clients_of_firm.size
- companies(:first_firm).clients_of_firm.delete_all
+ clients = companies(:first_firm).clients_of_firm.to_a
+ assert_equal 2, clients.count
+ deleted = companies(:first_firm).clients_of_firm.delete_all
+ assert_equal clients.sort_by(&:id), deleted.sort_by(&:id)
assert_equal 0, companies(:first_firm).clients_of_firm.size
assert_equal 0, companies(:first_firm).clients_of_firm(true).size
end
@@ -625,24 +690,25 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
client_id = firm.clients_of_firm.first.id
assert_equal 1, firm.clients_of_firm.size
- firm.clients_of_firm.clear
+ cleared = firm.clients_of_firm.clear
assert_equal 0, firm.clients_of_firm.size
assert_equal 0, firm.clients_of_firm(true).size
assert_equal [], Client.destroyed_client_ids[firm.id]
+ assert_equal firm.clients_of_firm.object_id, cleared.object_id
# Should not be destroyed since the association is not dependent.
assert_nothing_raised do
- assert Client.find(client_id).firm.nil?
+ assert_nil Client.find(client_id).firm
end
end
def test_clearing_updates_counter_cache
topic = Topic.first
- topic.replies.clear
- topic.reload
- assert_equal 0, topic.replies_count
+ assert_difference 'topic.reload.replies_count', -1 do
+ topic.replies.clear
+ end
end
def test_clearing_a_dependent_association_collection
@@ -658,7 +724,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [client_id], Client.destroyed_client_ids[firm.id]
# Should be destroyed since the association is dependent.
- assert Client.find_by_id(client_id).nil?
+ assert_nil Client.find_by_id(client_id)
end
def test_clearing_an_exclusively_dependent_association_collection
@@ -738,7 +804,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
- assert !another_ms_client.new_record?
+ assert another_ms_client.persisted?
assert_equal 'Microsoft', another_ms_client.name
end
@@ -838,7 +904,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_dependence_for_associations_with_hash_condition
david = authors(:david)
- post = posts(:thinking).id
assert_difference('Post.count', -1) { assert david.destroy }
end
@@ -858,7 +923,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
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"
- silly_reply = reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
+ reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
assert_nothing_raised { topic.destroy }
end
@@ -883,7 +948,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_depends_and_nullify
num_accounts = Account.count
- num_companies = Company.count
core = companies(:rails_core)
assert_equal accounts(:rails_core_account), core.account
@@ -900,7 +964,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_restrict
firm = RestrictedFirm.new(:name => 'restrict')
firm.save!
- child_firm = firm.companies.create(:name => 'child')
+ firm.companies.create(:name => 'child')
assert !firm.companies.empty?
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
end
@@ -941,6 +1005,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !firm.clients.include?(:first_client)
end
+ def test_replace_failure
+ firm = companies(:first_firm)
+ account = Account.new
+ orig_accounts = firm.accounts.to_a
+
+ assert !account.valid?
+ assert !orig_accounts.empty?
+ assert_raise ActiveRecord::RecordNotSaved do
+ firm.accounts = [account]
+ end
+ assert_equal orig_accounts, firm.accounts
+ end
+
def test_get_ids
assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids
end
@@ -999,21 +1076,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment')
end
- def test_dynamic_find_order_should_override_association_order_for_through
- assert_equal Comment.find(3), authors(:david).comments_desc.find(:first, :conditions => "comments.type = 'SpecialComment'", :order => 'comments.id')
- assert_equal Comment.find(3), authors(:david).comments_desc.find_by_type('SpecialComment', :order => 'comments.id')
- 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.find(:all, :conditions => "comments.type = 'SpecialComment'")
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_order_should_override_association_order_for_through
- assert_equal [Comment.find(3), Comment.find(6), Comment.find(7), Comment.find(10)], authors(:david).comments_desc.find(:all, :conditions => "comments.type = 'SpecialComment'", :order => 'comments.id')
- assert_equal [Comment.find(3), Comment.find(6), Comment.find(7), Comment.find(10)], authors(:david).comments_desc.find_all_by_type('SpecialComment', :order => 'comments.id')
- end
-
def test_dynamic_find_all_should_respect_association_limit_for_through
assert_equal 1, authors(:david).limited_comments.find(:all, :conditions => "comments.type = 'SpecialComment'").length
assert_equal 1, authors(:david).limited_comments.find_all_by_type('SpecialComment').length
@@ -1251,4 +1318,50 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
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
end
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 0eaadac5ae..9adaebe924 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -17,11 +17,18 @@ require 'models/developer'
require 'models/subscriber'
require 'models/book'
require 'models/subscription'
+require 'models/essay'
+require 'models/category'
+require 'models/owner'
+require 'models/categorization'
+require 'models/member'
+require 'models/membership'
+require 'models/club'
class HasManyThroughAssociationsTest < ActiveRecord::TestCase
- fixtures :posts, :readers, :people, :comments, :authors,
- :owners, :pets, :toys, :jobs, :references, :companies,
- :subscribers, :books, :subscriptions, :developers
+ 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
@@ -29,6 +36,13 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
Reader.create :person_id => 0, :post_id => 0
end
+ def test_include?
+ person = Person.new
+ post = Post.new
+ person.posts << post
+ assert person.posts.include?(post)
+ end
+
def test_associate_existing
assert_queries(2) { posts(:thinking); people(:david) }
@@ -43,6 +57,16 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert posts(:thinking).reload.people(true).include?(people(:david))
end
+ def test_associate_existing_record_twice_should_add_to_target_twice
+ post = posts(:thinking)
+ person = people(:david)
+
+ assert_difference 'post.people.to_a.count', 2 do
+ post.people << person
+ post.people << person
+ end
+ end
+
def test_associating_new
assert_queries(1) { posts(:thinking) }
new_person = nil # so block binding catches it
@@ -90,6 +114,24 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert posts(:thinking).reload.people(true).collect(&:first_name).include?("Ted")
end
+ def test_build_then_save_with_has_many_inverse
+ post = posts(:thinking)
+ person = post.people.build(:first_name => "Bob")
+ person.save
+ post.reload
+
+ assert post.people.include?(person)
+ end
+
+ def test_build_then_save_with_has_one_inverse
+ post = posts(:thinking)
+ person = post.single_people.build(:first_name => "Bob")
+ person.save
+ post.reload
+
+ assert post.single_people.include?(person)
+ end
+
def test_delete_association
assert_queries(2){posts(:welcome);people(:michael); }
@@ -105,8 +147,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_destroy_association
- assert_difference ["Person.count", "Reader.count"], -1 do
- posts(:welcome).people.destroy(people(:michael))
+ assert_no_difference "Person.count" do
+ assert_difference "Reader.count", -1 do
+ posts(:welcome).people.destroy(people(:michael))
+ end
end
assert posts(:welcome).reload.people.empty?
@@ -114,8 +158,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_destroy_all
- assert_difference ["Person.count", "Reader.count"], -1 do
- posts(:welcome).people.destroy_all
+ assert_no_difference "Person.count" do
+ assert_difference "Reader.count", -1 do
+ posts(:welcome).people.destroy_all
+ end
end
assert posts(:welcome).reload.people.empty?
@@ -128,6 +174,137 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_delete_through_belongs_to_with_dependent_nullify
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+ reference = Reference.where(:job_id => job.id, :person_id => person.id).first
+
+ assert_no_difference ['Job.count', 'Reference.count'] do
+ assert_difference 'person.jobs.count', -1 do
+ person.jobs_with_dependent_nullify.delete(job)
+ end
+ end
+
+ assert_equal nil, reference.reload.job_id
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_delete_through_belongs_to_with_dependent_delete_all
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+
+ # Make sure we're not deleting everything
+ assert person.jobs.count >= 2
+
+ assert_no_difference 'Job.count' do
+ assert_difference ['person.jobs.count', 'Reference.count'], -1 do
+ person.jobs_with_dependent_delete_all.delete(job)
+ end
+ end
+
+ # Check that the destroy callback on Reference did not run
+ assert_equal nil, person.reload.comments
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_delete_through_belongs_to_with_dependent_destroy
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+
+ # Make sure we're not deleting everything
+ assert person.jobs.count >= 2
+
+ assert_no_difference 'Job.count' do
+ assert_difference ['person.jobs.count', 'Reference.count'], -1 do
+ person.jobs_with_dependent_destroy.delete(job)
+ end
+ end
+
+ # Check that the destroy callback on Reference ran
+ assert_equal "Reference destroyed", person.reload.comments
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_belongs_to_with_dependent_destroy
+ person = PersonWithDependentDestroyJobs.find(1)
+
+ # Create a reference which is not linked to a job. This should not be destroyed.
+ person.references.create!
+
+ assert_no_difference 'Job.count' do
+ assert_difference 'Reference.count', -person.jobs.count do
+ person.destroy
+ end
+ end
+ end
+
+ def test_belongs_to_with_dependent_delete_all
+ person = PersonWithDependentDeleteAllJobs.find(1)
+
+ # Create a reference which is not linked to a job. This should not be destroyed.
+ person.references.create!
+
+ assert_no_difference 'Job.count' do
+ assert_difference 'Reference.count', -person.jobs.count do
+ person.destroy
+ end
+ end
+ end
+
+ def test_belongs_to_with_dependent_nullify
+ person = PersonWithDependentNullifyJobs.find(1)
+
+ references = person.references.to_a
+
+ assert_no_difference ['Reference.count', 'Job.count'] do
+ person.destroy
+ end
+
+ references.each do |reference|
+ assert_equal nil, reference.reload.job_id
+ end
+ end
+
+ def test_update_counter_caches_on_delete
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+
+ assert_difference ['post.reload.taggings_count', 'post.reload.tags_count'], -1 do
+ posts(:welcome).tags.delete(tag)
+ end
+ end
+
+ def test_update_counter_caches_on_delete_with_dependent_destroy
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ post.update_attribute(:tags_with_destroy_count, post.tags.count)
+
+ assert_difference ['post.reload.taggings_count', 'post.reload.tags_with_destroy_count'], -1 do
+ posts(:welcome).tags_with_destroy.delete(tag)
+ end
+ end
+
+ def test_update_counter_caches_on_delete_with_dependent_nullify
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ post.update_attribute(:tags_with_nullify_count, post.tags.count)
+
+ assert_no_difference 'post.reload.taggings_count' do
+ assert_difference 'post.reload.tags_with_nullify_count', -1 do
+ posts(:welcome).tags_with_nullify.delete(tag)
+ end
+ end
+ end
+
def test_replace_association
assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)}
@@ -322,12 +499,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert_equal 2, people(:michael).jobs.size
end
- def test_get_ids_for_belongs_to_source
- assert_sql(/DISTINCT/) { assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort }
- end
-
- def test_get_ids_for_has_many_source
- assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids
+ def test_get_ids
+ assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort
end
def test_get_ids_for_loaded_associations
@@ -354,7 +527,6 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_has_many_association_through_a_belongs_to_association_where_the_association_doesnt_exist
- author = authors(:mary)
post = Post.create!(:title => "TITLE", :body => "BODY")
assert_equal [], post.author_favorites
end
@@ -389,6 +561,41 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
+ def test_has_many_association_through_a_has_many_association_to_self
+ sarah = Person.create!(:first_name => 'Sarah', :primary_contact_id => people(:susan).id, :gender => 'F', :number1_fan_id => 1)
+ john = Person.create!(:first_name => 'John', :primary_contact_id => sarah.id, :gender => 'M', :number1_fan_id => 1)
+ assert_equal sarah.agents, [john]
+ assert_equal people(:susan).agents.map(&:agents).flatten, people(:susan).agents_of_agents
+ end
+
+ def test_associate_existing_with_nonstandard_primary_key_on_belongs_to
+ Categorization.create(:author => authors(:mary), :named_category_name => categories(:general).name)
+ assert_equal categories(:general), authors(:mary).named_categories.first
+ end
+
+ def test_collection_build_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.build(:name => "Primary")
+ author.save
+ assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).include?(category)
+ end
+
+ def test_collection_create_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.create(:name => "Primary")
+ assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).include?(category)
+ end
+
+ def test_collection_delete_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.create(:name => "Primary")
+ author.named_categories.delete(category)
+ assert !Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).empty?
+ end
+
def test_collection_singular_ids_getter_with_string_primary_keys
book = books(:awdr)
assert_equal 2, book.subscriber_ids.size
@@ -421,4 +628,142 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
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_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').all, authors(:david).comments_on_first_posts
+ end
+
+ def test_create_has_many_through_with_default_scope_on_join_model
+ category = authors(:david).special_categories.create(:name => "Foo")
+ assert_equal 1, category.categorizations.where(:special => true).count
+ end
+
+ def test_joining_has_many_through_with_uniq
+ mary = Author.joins(:unique_categorized_posts).where(:id => authors(:mary).id).first
+ assert_equal 1, mary.unique_categorized_posts.length
+ assert_equal 1, mary.unique_categorized_post_ids.length
+ end
+
+ def test_joining_has_many_through_belongs_to
+ posts = Post.joins(:author_categorizations).order('posts.id').
+ where('categorizations.id' => categorizations(:mary_thinking_sti).id)
+
+ assert_equal [posts(:eager_other), posts(:misc_by_mary), posts(:other_by_mary)], posts
+ end
+
+ def test_select_chosen_fields_only
+ author = authors(:david)
+ assert_equal ['body'], author.comments.select('comments.body').first.attributes.keys
+ end
+
+ def test_get_has_many_through_belongs_to_ids_with_conditions
+ assert_equal [categories(:general).id], authors(:mary).categories_like_general_ids
+ end
+
+ def test_count_has_many_through_with_named_scope
+ assert_equal 2, authors(:mary).categories.count
+ assert_equal 1, authors(:mary).categories.general.count
+ end
+
+ def test_has_many_through_belongs_to_should_update_when_the_through_foreign_key_changes
+ post = posts(:eager_other)
+
+ post.author_categorizations
+ proxy = post.send(:association_instance_get, :author_categorizations)
+
+ assert !proxy.stale_target?
+ assert_equal authors(:mary).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
+
+ post.author_id = authors(:david).id
+
+ assert proxy.stale_target?
+ assert_equal authors(:david).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
+ end
+
+ def test_create_with_conditions_hash_on_through_association
+ member = members(:groucho)
+ club = member.clubs.create!
+
+ assert_equal true, club.reload.membership.favourite
+ end
+
+ def test_deleting_from_has_many_through_a_belongs_to_should_not_try_to_update_counter
+ post = posts(:welcome)
+ address = author_addresses(:david_address)
+
+ assert post.author_addresses.include?(address)
+ post.author_addresses.delete(address)
+ assert post[:author_count].nil?
+ end
+
+ def test_interpolated_conditions
+ post = posts(:welcome)
+ assert !post.tags.empty?
+ assert_equal post.tags, post.interpolated_tags
+ assert_equal post.tags, post.interpolated_tags_2
+ end
+
+ def test_primary_key_option_on_source
+ post = posts(:welcome)
+ category = categories(:general)
+ categorization = Categorization.create!(:post_id => post.id, :named_category_name => category.name)
+
+ assert_equal [category], post.named_categories
+ assert_equal [category.name], post.named_category_ids # checks when target loaded
+ assert_equal [category.name], post.reload.named_category_ids # checks when target no loaded
+ end
end
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index 469a21b9bf..c1dad5e246 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -2,9 +2,13 @@ require "cases/helper"
require 'models/developer'
require 'models/project'
require 'models/company'
+require 'models/ship'
+require 'models/pirate'
+require 'models/bulb'
class HasOneAssociationsTest < ActiveRecord::TestCase
- fixtures :accounts, :companies, :developers, :projects, :developers_projects
+ self.use_transactional_fixtures = false unless supports_savepoints?
+ fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates
def setup
Account.destroyed_account_ids.clear
@@ -62,11 +66,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised { company.account = company.account }
end
- def test_triple_equality
- assert Account === companies(:first_firm).account
- assert companies(:first_firm).account === Account
- end
-
def test_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 }
assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) }
@@ -91,18 +90,18 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_nullification_on_association_change
firm = companies(:rails_core)
old_account_id = firm.account.id
- firm.account = Account.new
+ firm.account = Account.new(:credit_limit => 5)
# account is dependent with nullify, therefore its firm_id should be nil
assert_nil Account.find(old_account_id).firm_id
end
def test_association_change_calls_delete
- companies(:first_firm).deletable_account = Account.new
+ companies(:first_firm).deletable_account = Account.new(:credit_limit => 5)
assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id]
end
def test_association_change_calls_destroy
- companies(:first_firm).account = Account.new
+ companies(:first_firm).account = Account.new(:credit_limit => 5)
assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id]
end
@@ -116,35 +115,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal company.account, account
end
- def test_assignment_without_replacement
- apple = Firm.create("name" => "Apple")
- citibank = Account.create("credit_limit" => 10)
- apple.account = citibank
- assert_equal apple.id, citibank.firm_id
-
- hsbc = apple.build_account({ :credit_limit => 20}, false)
- assert_equal apple.id, hsbc.firm_id
- hsbc.save
- assert_equal apple.id, citibank.firm_id
-
- nykredit = apple.create_account({ :credit_limit => 30}, false)
- assert_equal apple.id, nykredit.firm_id
- assert_equal apple.id, citibank.firm_id
- assert_equal apple.id, hsbc.firm_id
- end
-
- def test_assignment_without_replacement_on_create
- apple = Firm.create("name" => "Apple")
- citibank = Account.create("credit_limit" => 10)
- apple.account = citibank
- assert_equal apple.id, citibank.firm_id
-
- hsbc = apple.create_account({:credit_limit => 10}, false)
- assert_equal apple.id, hsbc.firm_id
- hsbc.save
- assert_equal apple.id, citibank.firm_id
- end
-
def test_dependence
num_accounts = Account.count
@@ -163,7 +133,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
firm = ExclusivelyDependentFirm.find(9)
assert_not_nil firm.account
- account_id = firm.account.id
assert_equal [], Account.destroyed_account_ids[firm.id]
firm.destroy
@@ -180,7 +149,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_dependence_with_restrict
firm = RestrictedFirm.new(:name => 'restrict')
firm.save!
- account = firm.create_account(:credit_limit => 10)
+ firm.create_account(:credit_limit => 10)
assert_not_nil firm.account
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
end
@@ -194,13 +163,18 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal account, firm.account
end
- def test_build_association_twice_without_saving_affects_nothing
- count_of_account = Account.count
- firm = Firm.find(:first)
- account1 = firm.build_account("credit_limit" => 1000)
- account2 = firm.build_account("credit_limit" => 2000)
+ def test_build_and_create_should_not_happen_within_scope
+ pirate = pirates(:blackbeard)
+ original_scoped_methods = Bulb.scoped_methods.dup
- assert_equal count_of_account, Account.count
+ bulb = pirate.build_bulb
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = pirate.create_bulb
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = pirate.create_bulb!
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
end
def test_create_association
@@ -209,25 +183,32 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal account, firm.reload.account
end
- def test_build
- firm = Firm.new("name" => "GlobalMegaCorp")
- firm.save
+ def test_create_association_with_bang
+ firm = Firm.create(:name => "GlobalMegaCorp")
+ account = firm.create_account!(:credit_limit => 1000)
+ assert_equal account, firm.reload.account
+ end
- firm.account = account = Account.new("credit_limit" => 1000)
- assert_equal account, firm.account
- assert account.save
- assert_equal account, firm.account
+ def test_create_association_with_bang_failing
+ firm = Firm.create(:name => "GlobalMegaCorp")
+ assert_raise ActiveRecord::RecordInvalid do
+ firm.create_account!
+ end
+ account = firm.account
+ assert_not_nil account
+ account.credit_limit = 5
+ account.save
+ assert_equal account, firm.reload.account
end
- def test_failing_build_association
+ def test_build
firm = Firm.new("name" => "GlobalMegaCorp")
firm.save
- firm.account = account = Account.new
+ firm.account = account = Account.new("credit_limit" => 1000)
assert_equal account, firm.account
- assert !account.save
+ assert account.save
assert_equal account, firm.account
- assert_equal ["can't be empty"], account.errors["credit_limit"]
end
def test_create
@@ -253,7 +234,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_dependence_with_missing_association_and_nullify
Account.destroy_all
firm = DependentFirm.find(:first)
- assert firm.account.nil?
+ assert_nil firm.account
firm.destroy
end
@@ -268,7 +249,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_assignment_before_child_saved
firm = Firm.find(1)
firm.account = a = Account.new("credit_limit" => 1000)
- assert !a.new_record?
+ assert a.persisted?
assert_equal a, firm.account
assert_equal a, firm.account
assert_equal a, firm.account(true)
@@ -323,7 +304,59 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_create_respects_hash_condition
account = companies(:first_firm).create_account_limit_500_with_hash_conditions
- assert !account.new_record?
+ 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_replacement_failure_due_to_existing_record_should_raise_error
+ pirate = pirates(:blackbeard)
+ pirate.ship.name = nil
+
+ assert !pirate.ship.valid?
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ pirate.ship = ships(:interceptor)
+ end
+ assert_equal ships(:black_pearl), pirate.ship
+ assert_equal pirate.id, pirate.ship.pirate_id
+ end
+
+ def test_replacement_failure_due_to_new_record_should_raise_error
+ pirate = pirates(:blackbeard)
+ new_ship = Ship.new
+
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ pirate.ship = new_ship
+ end
+ assert_equal ships(:black_pearl), pirate.ship
+ assert_equal pirate.id, pirate.ship.pirate_id
+ assert_equal pirate.id, ships(:black_pearl).reload.pirate_id
+ assert_nil new_ship.pirate_id
+ end
end
diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb
index 3fcd150422..9ba5549277 100644
--- a/activerecord/test/cases/associations/has_one_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -9,10 +9,17 @@ 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
-
+ fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans,
+ :dashboards, :speedometers, :authors, :posts, :comments, :categories, :essays, :owners
+
def setup
@member = members(:groucho)
end
@@ -21,10 +28,6 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
assert_equal clubs(:boring_club), @member.club
end
- def test_has_one_through_with_has_many
- assert_equal clubs(:moustache_club), @member.favourite_club
- end
-
def test_creating_association_creates_through_record
new_member = Member.create(:name => "Chris")
new_member.club = Club.create(:name => "LRUG")
@@ -41,19 +44,19 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
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
+ @member.reload
end
end
@@ -81,7 +84,19 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
Member.find(:all, :include => :sponsor_club, :conditions => ["name = ?", "Groucho Marx"])
end
assert_equal 1, members.size
- assert_not_nil assert_no_queries {members[0].sponsor_club}
+ assert_not_nil assert_no_queries {members[0].sponsor_club}
+ end
+
+ def test_has_one_through_with_conditions_eager_loading
+ # conditions on the through table
+ assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :favourite_club).favourite_club
+ memberships(:membership_of_favourite_club).update_attribute(:favourite, false)
+ assert_equal nil, Member.find(@member.id, :include => :favourite_club).reload.favourite_club
+
+ # conditions on the source table
+ assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :hairy_club).hairy_club
+ clubs(:moustache_club).update_attribute(:name, "Association of Clean-Shaven Persons")
+ assert_equal nil, Member.find(@member.id, :include => :hairy_club).reload.hairy_club
end
def test_has_one_through_polymorphic_with_source_type
@@ -127,7 +142,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_assigning_association_correctly_assigns_target
new_member = Member.create(:name => "Chris")
new_member.club = new_club = Club.create(:name => "LRUG")
- assert_equal new_club, new_member.club.target
+ assert_equal new_club, new_member.association(:club).target
end
def test_has_one_through_proxy_should_not_respond_to_private_methods
@@ -185,7 +200,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
MemberDetail.find(:all, :include => :member_type)
end
@new_detail = @member_details[0]
- assert @new_detail.loaded_member_type?
+ assert @new_detail.send(:association, :member_type).loaded?
assert_not_nil assert_no_queries { @new_detail.member_type }
end
@@ -205,11 +220,94 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
Club.find(@club.id, :include => :sponsored_member).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
end
diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb
new file mode 100644
index 0000000000..9b8635774c
--- /dev/null
+++ b/activerecord/test/cases/associations/identity_map_test.rb
@@ -0,0 +1,137 @@
+require "cases/helper"
+require 'models/author'
+require 'models/post'
+
+if ActiveRecord::IdentityMap.enabled?
+class InverseHasManyIdentityMapTest < ActiveRecord::TestCase
+ fixtures :authors, :posts
+
+ def test_parent_instance_should_be_shared_with_every_child_on_find
+ m = Author.first
+ is = m.posts
+ is.each do |i|
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance"
+ end
+ end
+
+ def test_parent_instance_should_be_shared_with_eager_loaded_children
+ m = Author.find(:first, :include => :posts)
+ is = m.posts
+ is.each do |i|
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance"
+ end
+
+ m = Author.find(:first, :include => :posts, :order => 'posts.id')
+ is = m.posts
+ is.each do |i|
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance"
+ end
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_built_child
+ m = Author.first
+ i = m.posts.build(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to just-built-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_block_style_built_child
+ m = Author.first
+ i = m.posts.build {|ii| ii.title = 'Industrial Revolution Re-enactment'; ii.body = 'Lorem ipsum'}
+ assert_not_nil i.title, "Child attributes supplied to build via blocks should be populated"
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to just-built-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_child
+ m = Author.first
+ i = m.posts.create(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child
+ m = Author.first
+ i = m.posts.create!(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_block_style_created_child
+ m = Author.first
+ i = m.posts.create {|ii| ii.title = 'Industrial Revolution Re-enactment'; ii.body = 'Lorem ipsum'}
+ assert_not_nil i.title, "Child attributes supplied to create via blocks should be populated"
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_poked_in_child
+ m = Author.first
+ i = Post.create(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ m.posts << i
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_replaced_via_accessor_children
+ m = Author.first
+ i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ m.posts = [i]
+ assert_same m, i.author
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_replaced_via_method_children
+ m = Author.first
+ i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ m.posts = [i]
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+end
+end
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index 4ba867dc7c..e2228228a3 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -4,15 +4,26 @@ require 'models/comment'
require 'models/author'
require 'models/category'
require 'models/categorization'
+require 'models/person'
+require 'models/tagging'
+require 'models/tag'
class InnerJoinAssociationTest < ActiveRecord::TestCase
- fixtures :authors, :posts, :comments, :categories, :categories_posts, :categorizations
+ fixtures :authors, :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)
@@ -62,4 +73,23 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
authors_with_welcoming_post_titles = Author.calculate(:count, 'authors.id', :joins => :posts, :distinct => true, :conditions => "posts.title like 'Welcome%'")
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
+
+ def test_find_with_sti_join
+ scope = Post.joins(:special_comments).where(:id => posts(:sti_comments).id)
+
+ # The join should match SpecialComment and its subclasses only
+ assert scope.where("comments.type" => "Comment").empty?
+ assert !scope.where("comments.type" => "SpecialComment").empty?
+ assert !scope.where("comments.type" => "SubSpecialComment").empty?
+ end
+
+ def test_find_with_conditions_on_reflection
+ assert !posts(:welcome).comments.empty?
+ assert Post.joins(:nonexistant_comments).where(:id => posts(:welcome).id).empty? # [sic!]
+ end
+
+ def test_find_with_conditions_on_through_reflection
+ assert !posts(:welcome).tags.empty?
+ assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty?
+ end
end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index fa5c2e49df..76282213d8 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -114,7 +114,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_newly_built_child
- m = men(:gordon)
+ m = Man.find(:first)
f = m.build_face(:description => 'haunted')
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
@@ -125,7 +125,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_newly_created_child
- m = men(:gordon)
+ m = Man.find(:first)
f = m.create_face(:description => 'haunted')
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
@@ -137,40 +137,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method
m = Man.find(:first)
- f = m.face.create!(:description => 'haunted')
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
- end
-
- def test_parent_instance_should_be_shared_with_newly_built_child_when_we_dont_replace_existing
- m = Man.find(:first)
- f = m.build_face({:description => 'haunted'}, false)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
- end
-
- def test_parent_instance_should_be_shared_with_newly_created_child_when_we_dont_replace_existing
- m = Man.find(:first)
- f = m.create_face({:description => 'haunted'}, false)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
- end
-
- def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method_when_we_dont_replace_existing
- m = Man.find(:first)
- f = m.face.create!({:description => 'haunted'}, false)
+ f = m.create_face!(:description => 'haunted')
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -191,30 +158,6 @@ class InverseHasOneTests < ActiveRecord::TestCase
assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
end
- def test_parent_instance_should_be_shared_with_replaced_via_method_child
- m = Man.find(:first)
- f = Face.new(:description => 'haunted')
- m.face.replace(f)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
- end
-
- def test_parent_instance_should_be_shared_with_replaced_via_method_child_when_we_dont_replace_existing
- m = Man.find(:first)
- f = Face.new(:description => 'haunted')
- m.face.replace(f, false)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
- end
-
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.find(:first).dirty_face }
end
@@ -257,17 +200,6 @@ class InverseHasManyTests < ActiveRecord::TestCase
end
end
- def test_parent_instance_should_be_shared_with_newly_built_child
- m = men(:gordon)
- i = m.interests.build(:topic => 'Industrial Revolution Re-enactment')
- assert_not_nil i.man
- assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
- i.man.name = 'Mungo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
- end
-
def test_parent_instance_should_be_shared_with_newly_block_style_built_child
m = Man.find(:first)
i = m.interests.build {|ii| ii.topic = 'Industrial Revolution Re-enactment'}
@@ -280,17 +212,6 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
end
- def test_parent_instance_should_be_shared_with_newly_created_child
- m = men(:gordon)
- i = m.interests.create(:topic => 'Industrial Revolution Re-enactment')
- assert_not_nil i.man
- assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
- i.man.name = 'Mungo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
- end
-
def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child
m = Man.find(:first)
i = m.interests.create!(:topic => 'Industrial Revolution Re-enactment')
@@ -338,18 +259,6 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
end
- def test_parent_instance_should_be_shared_with_replaced_via_method_children
- m = Man.find(:first)
- i = Interest.new(:topic => 'Industrial Revolution Re-enactment')
- m.interests.replace([i])
- assert_not_nil i.man
- assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
- i.man.name = 'Mungo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
- end
-
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.find(:first).secret_interests }
end
@@ -433,19 +342,6 @@ class InverseBelongsToTests < ActiveRecord::TestCase
assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
end
- def test_child_instance_should_be_shared_with_replaced_via_method_parent
- f = faces(:trusting)
- assert_not_nil f.man
- m = Man.new(:name => 'Charles')
- f.man.replace(m)
- assert_not_nil m.face
- assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
- f.description = 'gormless'
- assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
- m.face.description = 'pleasing'
- assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
- end
-
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.find(:first).horrible_man }
end
@@ -484,7 +380,6 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
face = faces(:confused)
- old_man = face.polymorphic_man
new_man = Man.new
assert_not_nil face.polymorphic_man
@@ -499,11 +394,10 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
def test_child_instance_should_be_shared_with_replaced_via_method_parent
face = faces(:confused)
- old_man = face.polymorphic_man
new_man = Man.new
assert_not_nil face.polymorphic_man
- face.polymorphic_man.replace(new_man)
+ face.polymorphic_man = new_man
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
face.description = 'Bongo'
@@ -551,8 +445,8 @@ class InverseMultipleHasManyInversesForSameModel < ActiveRecord::TestCase
def test_that_we_can_load_associations_that_have_the_same_reciprocal_name_from_different_models
assert_nothing_raised(ActiveRecord::AssociationTypeMismatch) do
i = Interest.find(:first)
- z = i.zine
- m = i.man
+ i.zine
+ i.man
end
end
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 447fe4d275..1f95b31497 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -2,6 +2,7 @@ require "cases/helper"
require 'models/tag'
require 'models/tagging'
require 'models/post'
+require 'models/rating'
require 'models/item'
require 'models/comment'
require 'models/author'
@@ -13,7 +14,8 @@ require 'models/book'
require 'models/citation'
class AssociationsJoinModelTest < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books,
# Reload edges table from fixtures as otherwise repeated test was failing
:edges
@@ -43,11 +45,11 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert_queries(1) { assert_equal 0, author.unique_categorized_posts.count(:title, :conditions => "title is NULL") }
assert !authors(:mary).unique_categorized_posts.loaded?
end
-
+
def test_has_many_uniq_through_find
assert_equal 1, authors(:mary).unique_categorized_posts.find(:all).size
end
-
+
def test_has_many_uniq_through_dynamic_find
assert_equal 1, authors(:mary).unique_categorized_posts.find_all_by_title("So I was thinking").size
end
@@ -85,16 +87,9 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
end
- def test_polymorphic_has_many_going_through_join_model_with_disabled_include
- assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
- assert_queries 1 do
- tag.tagging
- end
- end
-
def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
- tag.author_id
+ assert_nothing_raised(NoMethodError) { tag.author_id }
end
def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key
@@ -159,7 +154,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_create_polymorphic_has_one_with_scope
old_count = Tagging.count
- tagging = posts(:welcome).tagging.create(:tag => tags(:misc))
+ tagging = posts(:welcome).create_tagging(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, Tagging.count
end
@@ -220,7 +215,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_with_piggyback
- assert_equal "2", categories(:sti_test).authors.first.post_id.to_s
+ assert_equal "2", categories(:sti_test).authors_with_select.first.post_id.to_s
end
def test_include_has_many_through
@@ -294,10 +289,26 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_going_through_join_model_with_custom_foreign_key
- assert_equal [], posts(:thinking).authors
+ 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_both_scoped_and_explicit_joins_should_be_respected
assert_nothing_raised do
Post.send(:with_scope, :find => {:joins => "left outer join comments on comments.id = posts.id"}) do
@@ -324,11 +335,16 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_polymorphic
- assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicError do
- assert_equal posts(:welcome, :thinking), tags(:general).taggables
+ assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicSourceError do
+ tags(:general).taggables
+ end
+
+ assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicThroughError do
+ taggings(:welcome_general).things
end
+
assert_raise ActiveRecord::EagerLoadPolymorphicError do
- assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1')
+ tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1')
end
end
@@ -384,19 +400,11 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
end
- def test_has_many_through_has_many_through
- assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).tags }
- end
-
- def test_has_many_through_habtm
- assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).post_categories }
- end
-
def test_eager_load_has_many_through_has_many
author = Author.find :first, :conditions => ['name = ?', 'David'], :include => :comments, :order => 'comments.id'
SpecialComment.new; VerySpecialComment.new
assert_no_queries do
- assert_equal [1,2,3,5,6,7,8,9,10], author.comments.collect(&:id)
+ assert_equal [1,2,3,5,6,7,8,9,10,12], author.comments.collect(&:id)
end
end
@@ -427,8 +435,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_has_many_through_uses_conditions_specified_on_the_has_many_association
author = Author.find(:first)
- assert !author.comments.blank?
- assert author.nonexistant_comments.blank?
+ assert_present author.comments
+ assert_blank author.nonexistant_comments
end
def test_has_many_through_uses_correct_attributes
@@ -440,11 +448,11 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
new_tag = Tag.new(:name => "new")
saved_post.tags << new_tag
- assert !new_tag.new_record? #consistent with habtm!
- assert !saved_post.new_record?
+ assert new_tag.persisted? #consistent with habtm!
+ assert saved_post.persisted?
assert saved_post.tags.include?(new_tag)
- assert !new_tag.new_record?
+ assert new_tag.persisted?
assert saved_post.reload.tags(true).include?(new_tag)
@@ -452,16 +460,16 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
saved_tag = tags(:general)
new_post.tags << saved_tag
- assert new_post.new_record?
- assert !saved_tag.new_record?
+ assert !new_post.persisted?
+ assert saved_tag.persisted?
assert new_post.tags.include?(saved_tag)
new_post.save!
- assert !new_post.new_record?
+ assert new_post.persisted?
assert new_post.reload.tags(true).include?(saved_tag)
- assert posts(:thinking).tags.build.new_record?
- assert posts(:thinking).tags.new.new_record?
+ assert !posts(:thinking).tags.build.persisted?
+ assert !posts(:thinking).tags.new.persisted?
end
def test_create_associate_when_adding_to_has_many_through
@@ -496,15 +504,19 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
end
+ def test_add_to_join_table_with_no_id
+ assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
+ end
+
def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
author = authors(:david)
- assert_equal 9, author.comments.size
+ assert_equal 10, author.comments.size
assert !author.comments.loaded?
end
def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
author = authors(:david)
- author.stubs(:read_attribute).with('comments_count').returns(100)
+ author.stubs(:_read_attribute).with('comments_count').returns(100)
assert_equal 100, author.comments.size
assert !author.comments.loaded?
end
@@ -575,7 +587,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
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
@@ -632,7 +644,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_preload_nil_polymorphic_belongs_to
assert_nothing_raised do
- taggings = Tagging.find(:all, :include => :taggable, :conditions => ['taggable_type IS NULL'])
+ Tagging.find(:all, :include => :taggable, :conditions => ['taggable_type IS NULL'])
end
end
@@ -675,7 +687,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
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')
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 0000000000..dd450a2a8e
--- /dev/null
+++ b/activerecord/test/cases/associations/nested_through_associations_test.rb
@@ -0,0 +1,546 @@
+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
+ 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
+ assert_includes_and_joins_equal(
+ Category.where('comments.id' => comments(:more_greetings).id).order('comments.id'),
+ [categories(:general), categories(:technology)], :post_comments
+ )
+ end
+
+ # has_many through
+ # Source: has_many through a habtm
+ # Through: has_many through
+ 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
+ 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_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.uniq.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'),
+ [authors(:bob)], :misc_post_first_blue_tags
+ )
+ end
+
+ def test_nested_has_many_through_with_conditions_on_source_associations
+ assert_equal [tags(:blue)], authors(:bob).misc_post_first_blue_tags_2
+ end
+
+ def test_nested_has_many_through_with_conditions_on_source_associations_preload
+ authors = assert_queries(4) { Author.includes(:misc_post_first_blue_tags_2).to_a.sort_by(&:id) }
+ blue = tags(:blue)
+
+ assert_no_queries do
+ assert_equal [blue], authors[2].misc_post_first_blue_tags_2
+ end
+ end
+
+ def test_nested_has_many_through_with_conditions_on_source_associations_preload_via_joins
+ # Pointless condition to force single-query loading
+ assert_includes_and_joins_equal(
+ Author.where('tags.id = tags.id'),
+ [authors(:bob)], :misc_post_first_blue_tags_2
+ )
+ end
+
+ def test_nested_has_many_through_with_foreign_key_option_on_the_source_reflection_through_reflection
+ assert_equal [categories(:general)], organizations(:nsa).author_essay_categories
+
+ 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
+
+ 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
index b31611e27a..47b8e48582 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -70,7 +70,7 @@ class AssociationsTest < ActiveRecord::TestCase
ship.parts.send(:load_target)
assert_equal 'Deck', ship.parts[0].name
end
-
+
def test_include_with_order_works
assert_nothing_raised {Account.find(:first, :order => 'id', :include => :firm)}
@@ -107,7 +107,7 @@ class AssociationsTest < ActiveRecord::TestCase
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.scoped.send :using_limitable_reflections?, reflections }
belongs_to_reflections = [Tagging.reflect_on_association(:tag), Tagging.reflect_on_association(:super_tag)]
@@ -117,10 +117,10 @@ class AssociationsTest < ActiveRecord::TestCase
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 = Client.create!("name" => "TheClient.com", :firm => firm)
+ Client.create!("name" => "TheClient.com", :firm => firm)
ActiveRecord::Base.cache do
firm.clients.each {}
assert_queries(0) { assert_not_nil firm.clients.each {} }
@@ -133,25 +133,6 @@ end
class AssociationProxyTest < ActiveRecord::TestCase
fixtures :authors, :posts, :categorizations, :categories, :developers, :projects, :developers_projects
- def test_proxy_accessors
- welcome = posts(:welcome)
- assert_equal welcome, welcome.author.proxy_owner
- assert_equal welcome.class.reflect_on_association(:author), welcome.author.proxy_reflection
- welcome.author.class # force load target
- assert_equal welcome.author, welcome.author.proxy_target
-
- david = authors(:david)
- assert_equal david, david.posts.proxy_owner
- assert_equal david.class.reflect_on_association(:posts), david.posts.proxy_reflection
- david.posts.class # force load target
- assert_equal david.posts, david.posts.proxy_target
-
- assert_equal david, david.posts_with_extension.testing_proxy_owner
- assert_equal david.class.reflect_on_association(:posts_with_extension), david.posts_with_extension.testing_proxy_reflection
- david.posts_with_extension.class # force load target
- assert_equal david.posts_with_extension, david.posts_with_extension.testing_proxy_target
- end
-
def test_push_does_not_load_target
david = authors(:david)
@@ -216,37 +197,12 @@ class AssociationProxyTest < ActiveRecord::TestCase
assert_equal post.body, "More cool stuff!"
end
- def test_failed_reload_returns_nil
- p = setup_dangling_association
- assert_nil p.author.reload
- end
-
- def test_failed_reset_returns_nil
- p = setup_dangling_association
- assert_nil p.author.reset
- end
-
def test_reload_returns_assocition
david = developers(:david)
assert_nothing_raised do
assert_equal david.projects, david.projects.reload.reload
end
end
-
- if RUBY_VERSION < '1.9'
- def test_splat_does_not_invoke_to_a_on_singular_targets
- author = posts(:welcome).author
- author.reload.target.expects(:to_a).never
- [*author]
- end
- end
-
- def setup_dangling_association
- josh = Author.create(:name => "Josh")
- p = Post.create(:title => "New on Edge", :body => "More cool stuff!", :author => josh)
- josh.destroy
- p
- end
end
class OverridingAssociationsTest < ActiveRecord::TestCase
@@ -270,17 +226,17 @@ class OverridingAssociationsTest < ActiveRecord::TestCase
def test_habtm_association_redefinition_callbacks_should_differ_and_not_inherited
# redeclared association on AR descendant should not inherit callbacks from superclass
- callbacks = PeopleList.read_inheritable_attribute(:before_add_for_has_and_belongs_to_many)
+ callbacks = PeopleList.before_add_for_has_and_belongs_to_many
assert_equal([:enlist], callbacks)
- callbacks = DifferentPeopleList.read_inheritable_attribute(:before_add_for_has_and_belongs_to_many)
+ 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.read_inheritable_attribute(:before_add_for_has_many)
+ callbacks = PeopleList.before_add_for_has_many
assert_equal([:enlist], callbacks)
- callbacks = DifferentPeopleList.read_inheritable_attribute(:before_add_for_has_many)
+ callbacks = DifferentPeopleList.before_add_for_has_many
assert_equal([], callbacks)
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 0000000000..d0a9028264
--- /dev/null
+++ b/activerecord/test/cases/attribute_methods/read_test.rb
@@ -0,0 +1,61 @@
+require "cases/helper"
+
+module ActiveRecord
+ module AttributeMethods
+ class ReadTest < ActiveRecord::TestCase
+ class FakeColumn < Struct.new(:name)
+ def type_cast_code(var)
+ var
+ end
+
+ def type; :integer; end
+ end
+
+ def setup
+ @klass = Class.new do
+ include ActiveRecord::AttributeMethods
+ include ActiveRecord::AttributeMethods::Read
+
+ def self.column_names
+ %w{ one two three }
+ end
+
+ def self.primary_key
+ end
+
+ def self.columns
+ column_names.map { FakeColumn.new(name) }
+ end
+
+ def self.columns_hash
+ Hash[column_names.map { |name|
+ [name, FakeColumn.new(name)]
+ }]
+ end
+
+ def self.serialized_attributes; {}; end
+ end
+ end
+
+ def test_define_attribute_methods
+ instance = @klass.new
+
+ @klass.column_names.each do |name|
+ assert ! instance.methods.map(&:to_s).include?(name)
+ end
+
+ @klass.define_attribute_methods
+
+ @klass.column_names.each do |name|
+ assert(instance.methods.map(&:to_s).include?(name), "#{name} is not defined")
+ end
+ end
+
+ def test_attribute_methods_generated?
+ assert(!@klass.attribute_methods_generated?, 'attribute_methods_generated?')
+ @klass.define_attribute_methods
+ assert(@klass.attribute_methods_generated?, 'attribute_methods_generated?')
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index 2c069cd8a5..d8638ee776 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -2,15 +2,17 @@ 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'
class AttributeMethodsTest < ActiveRecord::TestCase
fixtures :topics, :developers, :companies, :computers
-
+
def setup
@old_matchers = ActiveRecord::Base.send(:attribute_method_matchers).dup
@target = Class.new(ActiveRecord::Base)
@@ -85,6 +87,15 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert !topic.respond_to?(:nothingness)
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
+
def test_array_content
topic = Topic.new
topic.content = %w( one two three )
@@ -95,34 +106,29 @@ class AttributeMethodsTest < ActiveRecord::TestCase
def test_read_attributes_before_type_cast
category = Category.new({:name=>"Test categoty", :type => nil})
- category_attrs = {"name"=>"Test categoty", "type" => nil, "categorizations_count" => nil}
+ category_attrs = {"name"=>"Test categoty", "id" => nil, "type" => nil, "categorizations_count" => nil}
assert_equal category_attrs , category.attributes_before_type_cast
end
if current_adapter?(:MysqlAdapter)
def test_read_attributes_before_type_cast_on_boolean
- bool = Booleantest.create({ "value" => false })
- assert_equal "0", bool.reload.attributes_before_type_cast["value"]
+ bool = Boolean.create({ "value" => false })
+ assert_equal 0, bool.reload.attributes_before_type_cast["value"]
end
end
- unless current_adapter?(:Mysql2Adapter)
- def test_read_attributes_before_type_cast_on_datetime
- developer = Developer.find(:first)
- # Oracle adapter returns Time before type cast
- unless current_adapter?(:OracleAdapter)
- assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"]
- else
- assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db)
-
- developer.created_at = "345643456"
- assert_equal developer.created_at_before_type_cast, "345643456"
- assert_equal developer.created_at, nil
-
- developer.created_at = "2010-03-21T21:23:32+01:00"
- assert_equal developer.created_at_before_type_cast, "2010-03-21T21:23:32+01:00"
- assert_equal developer.created_at, Time.parse("2010-03-21T21:23:32+01:00")
- 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
@@ -237,6 +243,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase
# puts ""
end
+ def test_read_overridden_attribute
+ topic = Topic.new(:title => 'a')
+ def topic.title() 'b' end
+ assert_equal 'a', topic[:title]
+ end
+
def test_query_attribute_string
[nil, "", " "].each do |value|
assert_equal false, Topic.new(:author_name => value).author_name?
@@ -418,12 +430,8 @@ class AttributeMethodsTest < ActiveRecord::TestCase
Topic.instance_variable_set "@cached_attributes", nil
end
- def test_time_related_columns_are_actually_cached
- column_types = %w(datetime timestamp time date).map(&:to_sym)
- column_names = Topic.columns.select{|c| column_types.include?(c.type) }.map(&:name)
-
- assert_equal column_names.sort, Topic.cached_attributes.sort
- assert_equal time_related_columns_on_topic.sort, Topic.cached_attributes.sort
+ 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
@@ -434,8 +442,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert cache.empty?
all_columns = Topic.columns.map(&:name)
- cached_columns = time_related_columns_on_topic
- uncached_columns = all_columns - cached_columns
+ uncached_columns = all_columns - cached_columns
all_columns.each do |attr_name|
attribute_gets_cached = Topic.cache_attribute?(attr_name)
@@ -450,6 +457,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
end
+ def test_write_nil_to_time_attributes
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.written_on = nil
+ assert_nil record.written_on
+ end
+ end
+
def test_time_attributes_are_retrieved_in_current_time_zone
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
@@ -534,9 +549,9 @@ class AttributeMethodsTest < ActiveRecord::TestCase
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
+
+ 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
@@ -545,7 +560,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
topic = @target.new(:title => "The pros and cons of programming naked.")
assert !topic.respond_to?(:title)
exception = assert_raise(NoMethodError) { topic.title }
- assert_equal "Attempt to call private method", exception.message
+ assert_match %r(^Attempt to call private method), exception.message
assert_equal "I'm private", topic.send(:title)
end
@@ -555,7 +570,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
topic = @target.new
assert !topic.respond_to?(:title=)
exception = assert_raise(NoMethodError) { topic.title = "Pants"}
- assert_equal "Attempt to call private method", exception.message
+ assert_match %r(^Attempt to call private method), exception.message
topic.send(:title=, "Very large pants")
end
@@ -565,14 +580,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase
topic = @target.new(:title => "Isaac Newton's pants")
assert !topic.respond_to?(:title?)
exception = assert_raise(NoMethodError) { topic.title? }
- assert_equal "Attempt to call private method", exception.message
+ assert_match %r(^Attempt to call private method), exception.message
assert topic.send(:title?)
end
def test_bulk_update_respects_access_control
privatize("title=(value)")
- assert_raise(ActiveRecord::UnknownAttributeError) { topic = @target.new(:title => "Rants about pants") }
+ assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(:title => "Rants about pants") }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } }
end
@@ -591,10 +606,22 @@ class AttributeMethodsTest < ActiveRecord::TestCase
Object.send(:undef_method, :title) # remove test method from object
end
+ def test_list_of_serialized_attributes
+ assert_equal %w(content), Topic.serialized_attributes.keys
+ assert_equal %w(preferences), Contact.serialized_attributes.keys
+ end
private
+ def cached_columns
+ @cached_columns ||= (time_related_columns_on_topic + serialized_columns_on_topic).map(&:name)
+ end
+
def time_related_columns_on_topic
- Topic.columns.select{|c| [:time, :date, :datetime, :timestamp].include?(c.type)}.map(&:name)
+ Topic.columns.select { |c| [:time, :date, :datetime, :timestamp].include?(c.type) }
+ end
+
+ def serialized_columns_on_topic
+ Topic.columns.select { |c| Topic.serialized_attributes.include?(c.name) }
end
def in_time_zone(zone)
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 49e7147773..8f55b7ebe6 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -17,22 +17,23 @@ require 'models/tag'
require 'models/tagging'
require 'models/treasure'
require 'models/company'
+require 'models/eye'
class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
def test_autosave_should_be_a_valid_option_for_has_one
- assert base.valid_keys_for_has_one_association.include?(:autosave)
+ assert ActiveRecord::Associations::Builder::HasOne.valid_options.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_belongs_to
- assert base.valid_keys_for_belongs_to_association.include?(:autosave)
+ assert ActiveRecord::Associations::Builder::BelongsTo.valid_options.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_has_many
- assert base.valid_keys_for_has_many_association.include?(:autosave)
+ assert ActiveRecord::Associations::Builder::HasMany.valid_options.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_has_and_belongs_to_many
- assert base.valid_keys_for_has_and_belongs_to_many_association.include?(:autosave)
+ assert ActiveRecord::Associations::Builder::HasAndBelongsToMany.valid_options.include?(:autosave)
end
def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
@@ -82,14 +83,14 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
assert !firm.build_account_using_primary_key.valid?
assert firm.save
- assert firm.account_using_primary_key.new_record?
+ assert !firm.account_using_primary_key.persisted?
end
def test_save_fails_for_invalid_has_one
firm = Firm.find(:first)
assert firm.valid?
- firm.account = Account.new
+ firm.build_account
assert !firm.account.valid?
assert !firm.valid?
@@ -101,7 +102,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
firm = Firm.find(:first)
assert firm.valid?
- firm.unvalidated_account = Account.new
+ firm.build_unvalidated_account
assert !firm.unvalidated_account.valid?
assert firm.valid?
@@ -111,12 +112,12 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
def test_build_before_child_saved
firm = Firm.find(1)
- account = firm.account.build("credit_limit" => 1000)
+ account = firm.build_account("credit_limit" => 1000)
assert_equal account, firm.account
- assert account.new_record?
+ assert !account.persisted?
assert firm.save
assert_equal account, firm.account
- assert !account.new_record?
+ assert account.persisted?
end
def test_build_before_either_saved
@@ -124,16 +125,16 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
firm.account = account = Account.new("credit_limit" => 1000)
assert_equal account, firm.account
- assert account.new_record?
+ assert !account.persisted?
assert firm.save
assert_equal account, firm.account
- assert !account.new_record?
+ assert account.persisted?
end
def test_assignment_before_parent_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.find(1)
- assert firm.new_record?
+ assert !firm.persisted?
assert_equal a, firm.account
assert firm.save
assert_equal a, firm.account
@@ -143,12 +144,12 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
def test_assignment_before_either_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.new("credit_limit" => 1000)
- assert firm.new_record?
- assert a.new_record?
+ assert !firm.persisted?
+ assert !a.persisted?
assert_equal a, firm.account
assert firm.save
- assert !firm.new_record?
- assert !a.new_record?
+ assert firm.persisted?
+ assert a.persisted?
assert_equal a, firm.account
assert_equal a, firm.account(true)
end
@@ -162,14 +163,33 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
firm.account = Account.find(:first)
assert_queries(Firm.partial_updates? ? 0 : 1) { firm.save! }
- firm = Firm.find(:first).clone
+ firm = Firm.find(:first).dup
firm.account = Account.find(:first)
assert_queries(2) { firm.save! }
- firm = Firm.find(:first).clone
- firm.account = Account.find(:first).clone
+ firm = Firm.find(:first).dup
+ firm.account = Account.find(: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_attributes(: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_attributes(:iris_attributes => {:color => 'blue'})
+ assert_equal [false, false, false, false], eye.after_save_callbacks_stack
+ end
end
class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
@@ -183,7 +203,7 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
assert !client.firm.valid?
assert client.save
- assert client.firm.new_record?
+ assert !client.firm.persisted?
end
def test_save_fails_for_invalid_belongs_to
@@ -212,10 +232,10 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
apple = Firm.new("name" => "Apple")
client.firm = apple
assert_equal apple, client.firm
- assert apple.new_record?
+ assert !apple.persisted?
assert client.save
assert apple.save
- assert !apple.new_record?
+ assert apple.persisted?
assert_equal apple, client.firm
assert_equal apple, client.firm(true)
end
@@ -224,11 +244,11 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
final_cut = Client.new("name" => "Final Cut")
apple = Firm.new("name" => "Apple")
final_cut.firm = apple
- assert final_cut.new_record?
- assert apple.new_record?
+ assert !final_cut.persisted?
+ assert !apple.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !apple.new_record?
+ assert final_cut.persisted?
+ assert apple.persisted?
assert_equal apple, final_cut.firm
assert_equal apple, final_cut.firm(true)
end
@@ -249,8 +269,8 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
assert_equal customer1, order.billing
assert_equal customer2, order.shipping
- assert_equal num_orders +1, Order.count
- assert_equal num_customers +2, Customer.count
+ 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
@@ -268,8 +288,8 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
assert_equal customer, order.billing
assert_equal customer, order.shipping
- assert_equal num_orders +1, Order.count
- assert_equal num_customers +1, Customer.count
+ 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
@@ -287,8 +307,8 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
assert_equal customer, order.billing
assert_equal customer, order.shipping
- assert_equal num_orders +1, Order.count
- assert_equal num_customers +1, Customer.count
+ 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
@@ -311,14 +331,21 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
assert_equal customer, order.billing
assert_equal customer, order.shipping
- assert_equal num_orders +1, Order.count
- assert_equal num_customers +2, Customer.count
+ 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
+ assert_equal num_tagging + 1, Tagging.count
+ end
+
+ def test_build_and_then_save_parent_should_not_reload_target
+ client = Client.find(:first)
+ apple = client.build_firm(:name => "Apple")
+ client.save!
+ assert_no_queries { assert_equal apple, client.firm }
end
end
@@ -328,23 +355,21 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
def test_invalid_adding
firm = Firm.find(1)
assert !(firm.clients_of_firm << c = Client.new)
- assert c.new_record?
+ assert !c.persisted?
assert !firm.valid?
assert !firm.save
- assert c.new_record?
+ assert !c.persisted?
end
def test_invalid_adding_before_save
- no_of_firms = Firm.count
- no_of_clients = Client.count
new_firm = Firm.new("name" => "A New Firm, Inc")
new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
- assert c.new_record?
+ assert !c.persisted?
assert !c.valid?
assert !new_firm.valid?
assert !new_firm.save
- assert c.new_record?
- assert new_firm.new_record?
+ assert !c.persisted?
+ assert !new_firm.persisted?
end
def test_invalid_adding_with_validate_false
@@ -355,7 +380,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert firm.valid?
assert !client.valid?
assert firm.save
- assert client.new_record?
+ assert !client.persisted?
end
def test_valid_adding_with_validate_false
@@ -366,22 +391,22 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert firm.valid?
assert client.valid?
- assert client.new_record?
+ assert !client.persisted?
firm.unvalidated_clients_of_firm << client
assert firm.save
- assert !client.new_record?
- assert_equal no_of_clients+1, Client.count
+ 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.new_record?
+ 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.new_record?
+ assert !new_client.persisted?
assert_equal 1, companies(:first_firm).clients_of_firm(true).size
end
@@ -400,11 +425,11 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
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.new_record?
- assert !c.new_record?
+ 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 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
@@ -435,13 +460,13 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
company.name += '-changed'
assert_queries(2) { assert company.save }
- assert !new_client.new_record?
+ assert new_client.persisted?
assert_equal 2, company.clients_of_firm(true).size
end
def test_build_many_before_save
company = companies(:first_firm)
- new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
+ assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
company.name += '-changed'
assert_queries(3) { assert company.save }
@@ -455,13 +480,13 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
company.name += '-changed'
assert_queries(2) { assert company.save }
- assert !new_client.new_record?
+ 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)
- new_clients = assert_no_queries do
+ assert_no_queries do
company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
client.name = "changed"
end
@@ -487,67 +512,67 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase
new_account = Account.new("credit_limit" => 1000)
new_firm = Firm.new("name" => "some firm")
- assert new_firm.new_record?
+ assert !new_firm.persisted?
new_account.firm = new_firm
new_account.save!
- assert !new_firm.new_record?
+ assert new_firm.persisted?
new_account = Account.new("credit_limit" => 1000)
new_autosaved_firm = Firm.new("name" => "some firm")
- assert new_autosaved_firm.new_record?
+ assert !new_autosaved_firm.persisted?
new_account.unautosaved_firm = new_autosaved_firm
new_account.save!
- assert new_autosaved_firm.new_record?
+ 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.new_record?
+ assert !account.persisted?
firm.account = account
firm.save!
- assert !account.new_record?
+ assert account.persisted?
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
firm.unautosaved_account = account
- assert account.new_record?
+ assert !account.persisted?
firm.unautosaved_account = account
firm.save!
- assert account.new_record?
+ 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.new_record?
+ assert !account.persisted?
firm.accounts << account
firm.save!
- assert !account.new_record?
+ assert account.persisted?
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
- assert account.new_record?
+ assert !account.persisted?
firm.unautosaved_accounts << account
firm.save!
- assert account.new_record?
+ assert !account.persisted?
end
end
class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -560,7 +585,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
@pirate.ship.mark_for_destruction
assert !@pirate.reload.marked_for_destruction?
- assert !@pirate.ship.marked_for_destruction?
+ assert !@pirate.ship.reload.marked_for_destruction?
end
# has_one
@@ -649,119 +674,227 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
end
end
+ @ship.pirate.catchphrase = "Changed Catchphrase"
+
assert_raise(RuntimeError) { assert !@ship.save }
assert_not_nil @ship.reload.pirate
end
- # has_many & has_and_belongs_to
- %w{ parrots birds }.each do |association_name|
- define_method("test_should_destroy_#{association_name}_as_part_of_the_save_transaction_if_they_were_marked_for_destroyal") do
- 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
+ def test_should_save_changed_child_objects_if_parent_is_saved
+ @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @parrot = @pirate.parrots.create!(:name => 'Posideons Killer')
+ @parrot.name = "NewName"
+ @ship.save
+
+ assert_equal 'NewName', @parrot.reload.name
+ end
- assert !@pirate.send(association_name).any? { |child| child.marked_for_destruction? }
+ 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}") }
- @pirate.send(association_name).each { |child| child.mark_for_destruction }
- klass = @pirate.send(association_name).first.class
- ids = @pirate.send(association_name).map(&:id)
+ assert !@pirate.birds.any? { |child| child.marked_for_destruction? }
- assert @pirate.send(association_name).all? { |child| child.marked_for_destruction? }
- ids.each { |id| assert klass.find_by_id(id) }
+ @pirate.birds.each { |child| child.mark_for_destruction }
+ klass = @pirate.birds.first.class
+ ids = @pirate.birds.map(&:id)
- @pirate.save
- assert @pirate.reload.send(association_name).empty?
- ids.each { |id| assert_nil klass.find_by_id(id) }
+ assert @pirate.birds.all? { |child| child.marked_for_destruction? }
+ ids.each { |id| assert klass.find_by_id(id) }
+
+ @pirate.save
+ assert @pirate.reload.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
- define_method("test_should_skip_validation_on_the_#{association_name}_association_if_marked_for_destruction") do
- 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
- children = @pirate.send(association_name)
+ @pirate.birds.each { |bird| bird.expects(:destroy).never }
+ assert @pirate.save
+ end
- children.each { |child| child.name = '' }
- assert !@pirate.valid?
+ 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 }
- children.each do |child|
- child.mark_for_destruction
- child.expects(:valid?).never
+ # Stub the destroy method of the second child to raise an exception
+ class << before.last
+ def destroy(*args)
+ super
+ raise 'Oh noes!'
end
- assert_difference("#{association_name.classify}.count", -2) { @pirate.save! }
end
-
- define_method("test_should_skip_validation_on_the_#{association_name}_association_if_destroyed") do
- @pirate.send(association_name).create!(:name => "#{association_name}_1")
- children = @pirate.send(association_name)
- children.each { |child| child.name = '' }
- assert !@pirate.valid?
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, @pirate.reload.birds
+ end
+
+ # Add and remove callbacks tests for association collections.
+ %w{ method proc }.each do |callback_type|
+ define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do
+ association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
+
+ pirate = Pirate.new(:catchphrase => "Arr")
+ pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
- children.each { |child| child.destroy }
- assert @pirate.valid?
+ expected = [
+ "before_adding_#{callback_type}_bird_<new>",
+ "after_adding_#{callback_type}_bird_<new>"
+ ]
+
+ assert_equal expected, pirate.ship_log
end
- define_method("test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_#{association_name}") do
- @pirate.send(association_name).create!(:name => "#{association_name}_1")
- children = @pirate.send(association_name)
+ define_method("test_should_run_remove_callback_#{callback_type}s_for_has_many") do
+ association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
- children.each { |child| child.mark_for_destruction }
- assert @pirate.save
- children.each { |child| child.expects(:destroy).never }
- assert @pirate.save
+ @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
+ @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ child_id = @pirate.send(association_name_with_callbacks).first.id
+
+ @pirate.ship_log.clear
+ @pirate.save
+
+ expected = [
+ "before_removing_#{callback_type}_bird_#{child_id}",
+ "after_removing_#{callback_type}_bird_#{child_id}"
+ ]
+
+ assert_equal expected, @pirate.ship_log
end
+ end
- define_method("test_should_rollback_destructions_if_an_exception_occurred_while_saving_#{association_name}") do
- 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
- before = @pirate.send(association_name).map { |c| c.mark_for_destruction ; c }
+ def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
- # Stub the destroy method of the the second child to raise an exception
- class << before.last
- def destroy(*args)
- super
- raise 'Oh noes!'
- end
- end
+ assert !@pirate.parrots.any? { |parrot| parrot.marked_for_destruction? }
+ @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
- assert_raise(RuntimeError) { assert !@pirate.save }
- assert_equal before, @pirate.reload.send(association_name)
+ assert_no_difference "Parrot.count" do
+ @pirate.save
end
- # Add and remove callbacks tests for association collections.
- %w{ method proc }.each do |callback_type|
- define_method("test_should_run_add_callback_#{callback_type}s_for_#{association_name}") do
- association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks"
+ assert @pirate.reload.parrots.empty?
- pirate = Pirate.new(:catchphrase => "Arr")
- pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
+ join_records = Pirate.connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}")
+ assert join_records.empty?
+ end
- expected = [
- "before_adding_#{callback_type}_#{association_name.singularize}_<new>",
- "after_adding_#{callback_type}_#{association_name.singularize}_<new>"
- ]
+ def test_should_skip_validation_on_habtm_if_marked_for_destruction
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
- assert_equal expected, pirate.ship_log
- end
+ @pirate.parrots.each { |parrot| parrot.name = '' }
+ assert !@pirate.valid?
- define_method("test_should_run_remove_callback_#{callback_type}s_for_#{association_name}") do
- association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks"
+ @pirate.parrots.each 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.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
- @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
- child_id = @pirate.send(association_name_with_callbacks).first.id
+ @pirate.parrots.each { |parrot| parrot.destroy }
+ assert @pirate.valid?
+ end
- @pirate.ship_log.clear
- @pirate.save
+ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm
+ @pirate.parrots.create!(:name => "parrots_1")
- expected = [
- "before_removing_#{callback_type}_#{association_name.singularize}_#{child_id}",
- "after_removing_#{callback_type}_#{association_name.singularize}_#{child_id}"
- ]
+ @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
+ assert @pirate.save
- assert_equal expected, @pirate.ship_log
+ assert_no_queries 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.parrots
+ def destroy(*args)
+ super
+ raise 'Oh noes!'
end
end
+
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, @pirate.reload.parrots
+ end
+
+ # Add and remove callbacks tests for association collections.
+ %w{ method proc }.each do |callback_type|
+ define_method("test_should_run_add_callback_#{callback_type}s_for_habtm") do
+ association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
+
+ pirate = Pirate.new(:catchphrase => "Arr")
+ pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
+
+ expected = [
+ "before_adding_#{callback_type}_parrot_<new>",
+ "after_adding_#{callback_type}_parrot_<new>"
+ ]
+
+ assert_equal expected, pirate.ship_log
+ end
+
+ define_method("test_should_run_remove_callback_#{callback_type}s_for_habtm") do
+ association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
+
+ @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
+ @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ child_id = @pirate.send(association_name_with_callbacks).first.id
+
+ @pirate.ship_log.clear
+ @pirate.save
+
+ expected = [
+ "before_removing_#{callback_type}_parrot_#{child_id}",
+ "after_removing_#{callback_type}_parrot_#{child_id}"
+ ]
+
+ assert_equal expected, @pirate.ship_log
+ end
end
end
class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -832,7 +965,10 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)]
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
- assert_equal [nil, nil, nil, nil], values
+ expected = ActiveRecord::IdentityMap.enabled? ?
+ [nil, nil, '', ''] :
+ [nil, nil, nil, nil]
+ assert_equal expected, values
else
assert_equal ['', '', '', ''], values
end
@@ -881,7 +1017,7 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
end
class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@ship = Ship.create(:name => 'Nights Dirty Lightning')
@@ -927,7 +1063,8 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
@ship.save(:validate => false)
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
- assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase]
+ expected = ActiveRecord::IdentityMap.enabled? ? [nil, ''] : [nil, nil]
+ assert_equal expected, [@ship.reload.name, @ship.pirate.catchphrase]
else
assert_equal ['', ''], [@ship.reload.name, @ship.pirate.catchphrase]
end
@@ -1061,7 +1198,7 @@ module AutosaveAssociationOnACollectionAssociationTests
end
def test_should_allow_to_bypass_validations_on_the_associated_models_on_create
- assert_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count", +2) do
+ assert_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count", 2) do
2.times { @pirate.send(@association_name).build }
@pirate.save(:validate => false)
end
@@ -1128,7 +1265,7 @@ module AutosaveAssociationOnACollectionAssociationTests
end
class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@association_name = :birds
@@ -1142,7 +1279,7 @@ class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
end
class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@association_name = :parrots
@@ -1157,7 +1294,7 @@ class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::T
end
class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -1173,11 +1310,12 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te
end
class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate.create_ship(:name => 'titanic')
+ super
end
test "should automatically validate associations with :validate => true" do
@@ -1186,7 +1324,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes
assert !@pirate.valid?
end
- test "should not automatically validate associations without :validate => true" do
+ test "should not automatically asd validate associations without :validate => true" do
assert @pirate.valid?
@pirate.non_validated_ship.name = ''
assert @pirate.valid?
@@ -1194,7 +1332,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes
end
class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -1214,7 +1352,7 @@ class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::
end
class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -1236,7 +1374,7 @@ class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::Test
end
class TestAutosaveAssociationValidationMethodsGeneration < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.new
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index ca397d3847..fba7af741d 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -10,6 +10,7 @@ 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'
@@ -18,6 +19,8 @@ require 'models/minimalistic'
require 'models/warehouse_thing'
require 'models/parrot'
require 'models/loose_person'
+require 'models/edge'
+require 'models/joke'
require 'rexml/document'
require 'active_support/core_ext/exception'
@@ -42,11 +45,69 @@ class ReadonlyTitlePost < Post
attr_readonly :title
end
-class Booleantest < ActiveRecord::Base; end
+class Weird < ActiveRecord::Base; end
+
+class Boolean < ActiveRecord::Base; end
class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
+ def test_columns_should_obey_set_primary_key
+ pk = Subscriber.columns.find { |x| x.name == 'nick' }
+ assert pk.primary, 'nick should be primary key'
+ end
+
+ def test_primary_key_with_no_id
+ assert_nil Edge.primary_key
+ end
+
+ unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
+ def test_limit_with_comma
+ assert_nothing_raised do
+ Topic.limit("1,2").all
+ end
+ end
+ end
+
+ def test_limit_without_comma
+ assert_nothing_raised do
+ assert_equal 1, Topic.limit("1").all.length
+ end
+
+ assert_nothing_raised do
+ assert_equal 1, Topic.limit(1).all.length
+ end
+ end
+
+ def test_invalid_limit
+ assert_raises(ArgumentError) do
+ Topic.limit("asdfadf").all
+ end
+ end
+
+ def test_limit_should_sanitize_sql_injection_for_limit_without_comas
+ assert_raises(ArgumentError) do
+ Topic.limit("1 select * from schema").all
+ end
+ end
+
+ def test_limit_should_sanitize_sql_injection_for_limit_with_comas
+ assert_raises(ArgumentError) do
+ Topic.limit("1, 7 procedure help()").all
+ end
+ end
+
+ unless current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
+ def test_limit_should_allow_sql_literal
+ assert_equal 1, Topic.limit(Arel.sql('2-1')).all.length
+ end
+ end
+
+ def test_select_symbol
+ topic_ids = Topic.select(:id).map(&:id).sort
+ assert_equal Topic.find(:all).map(&:id).sort, topic_ids
+ end
+
def test_table_exists
assert !NonExistentTable.table_exists?
assert Topic.table_exists?
@@ -68,6 +129,25 @@ class BasicsTest < ActiveRecord::TestCase
end
end
+ def test_use_table_engine_for_quoting_where
+ relation = Topic.where(Topic.arel_table[:id].eq(1))
+ engine = relation.table.engine
+
+ fakepool = Class.new(Struct.new(:spec)) {
+ def with_connection; yield self; end
+ def connection_pool; self; end
+ def table_exists?(name); false; end
+ def quote_table_name(*args); raise "lol quote_table_name"; end
+ }
+
+ relation.table.engine = fakepool.new(engine.connection_pool.spec)
+
+ error = assert_raises(RuntimeError) { relation.to_a }
+ assert_match('lol', error.message)
+ ensure
+ relation.table.engine = engine
+ end
+
def test_preserving_time_objects
assert_kind_of(
Time, Topic.find(1).bonus_time,
@@ -158,7 +238,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_initialize_with_invalid_attribute
begin
- topic = Topic.new({ "title" => "test",
+ 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)
@@ -365,10 +445,23 @@ class BasicsTest < ActiveRecord::TestCase
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
@@ -386,6 +479,16 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "changed", post.body
end
+ def test_non_valid_identifier_column_name
+ weird = Weird.create('a$b' => 'value')
+ weird.reload
+ assert_equal 'value', weird.send('a$b')
+
+ weird.update_attribute('a$b', 'value2')
+ weird.reload
+ assert_equal 'value2', weird.send('a$b')
+ end
+
def test_multiparameter_attributes_on_date
attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
topic = Topic.find(1)
@@ -596,96 +699,101 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_boolean
- b_nil = Booleantest.create({ "value" => nil })
+ b_nil = Boolean.create({ "value" => nil })
nil_id = b_nil.id
- b_false = Booleantest.create({ "value" => false })
+ b_false = Boolean.create({ "value" => false })
false_id = b_false.id
- b_true = Booleantest.create({ "value" => true })
+ b_true = Boolean.create({ "value" => true })
true_id = b_true.id
- b_nil = Booleantest.find(nil_id)
+ b_nil = Boolean.find(nil_id)
assert_nil b_nil.value
- b_false = Booleantest.find(false_id)
+ b_false = Boolean.find(false_id)
assert !b_false.value?
- b_true = Booleantest.find(true_id)
+ b_true = Boolean.find(true_id)
assert b_true.value?
end
def test_boolean_cast_from_string
- b_blank = Booleantest.create({ "value" => "" })
+ b_blank = Boolean.create({ "value" => "" })
blank_id = b_blank.id
- b_false = Booleantest.create({ "value" => "0" })
+ b_false = Boolean.create({ "value" => "0" })
false_id = b_false.id
- b_true = Booleantest.create({ "value" => "1" })
+ b_true = Boolean.create({ "value" => "1" })
true_id = b_true.id
- b_blank = Booleantest.find(blank_id)
+ b_blank = Boolean.find(blank_id)
assert_nil b_blank.value
- b_false = Booleantest.find(false_id)
+ b_false = Boolean.find(false_id)
assert !b_false.value?
- b_true = Booleantest.find(true_id)
+ b_true = Boolean.find(true_id)
assert b_true.value?
end
def test_new_record_returns_boolean
- assert_equal true, Topic.new.new_record?
- assert_equal false, Topic.find(1).new_record?
+ assert_equal false, Topic.new.persisted?
+ assert_equal true, Topic.find(1).persisted?
end
- def test_clone
+ def test_dup
topic = Topic.find(1)
- cloned_topic = nil
- assert_nothing_raised { cloned_topic = topic.clone }
- assert_equal topic.title, cloned_topic.title
- assert cloned_topic.new_record?
+ 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 cloned
+ # test if the attributes have been duped
topic.title = "a"
- cloned_topic.title = "b"
+ duped_topic.title = "b"
assert_equal "a", topic.title
- assert_equal "b", cloned_topic.title
+ assert_equal "b", duped_topic.title
- # test if the attribute values have been cloned
+ # test if the attribute values have been duped
topic.title = {"a" => "b"}
- cloned_topic = topic.clone
- cloned_topic.title["a"] = "c"
+ duped_topic = topic.dup
+ duped_topic.title["a"] = "c"
assert_equal "b", topic.title["a"]
- # test if attributes set as part of after_initialize are cloned correctly
- assert_equal topic.author_email_address, cloned_topic.author_email_address
+ # 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
- cloned_topic.save
- assert !cloned_topic.new_record?
- assert_not_equal cloned_topic.id, topic.id
+ duped_topic.save
+ assert duped_topic.persisted?
+ assert_not_equal duped_topic.id, topic.id
+
+ duped_topic.reload
+ # FIXME: I think this is poor behavior, and will fix it with #5686
+ assert_equal({'a' => 'c'}.to_yaml, duped_topic.title)
end
- def test_clone_with_aggregate_of_same_name_as_attribute
+ def test_dup_with_aggregate_of_same_name_as_attribute
dev = DeveloperWithAggregate.find(1)
assert_kind_of DeveloperSalary, dev.salary
- clone = nil
- assert_nothing_raised { clone = dev.clone }
- assert_kind_of DeveloperSalary, clone.salary
- assert_equal dev.salary.amount, clone.salary.amount
- assert clone.new_record?
+ 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 cloned
- original_amount = clone.salary.amount
+ # test if the attributes have been dupd
+ original_amount = dup.salary.amount
dev.salary.amount = 1
- assert_equal original_amount, clone.salary.amount
+ assert_equal original_amount, dup.salary.amount
- assert clone.save
- assert !clone.new_record?
- assert_not_equal clone.id, dev.id
+ assert dup.save
+ assert dup.persisted?
+ assert_not_equal dup.id, dev.id
end
- def test_clone_does_not_clone_associations
+ def test_dup_does_not_copy_associations
author = authors(:david)
assert_not_equal [], author.posts
+ author.send(:clear_association_cache)
- author_clone = author.clone
- assert_equal [], author_clone.posts
+ author_dup = author.dup
+ assert_equal [], author_dup.posts
end
def test_clone_preserves_subtype
@@ -724,24 +832,24 @@ class BasicsTest < ActiveRecord::TestCase
assert !cloned_developer.salary_changed? # ... and cloned instance should behave same
end
- def test_clone_of_saved_object_marks_attributes_as_dirty
+ 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.clone
+ cloned_developer = developer.dup
assert cloned_developer.name_changed? # both attributes differ from defaults
assert cloned_developer.salary_changed?
end
- def test_clone_of_saved_object_marks_as_dirty_only_changed_attributes
+ 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 threated as not changed
+ assert !developer.name_changed? # both attributes of saved object should be treated as not changed
assert !developer.salary_changed?
- cloned_developer = developer.clone
+ 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 threated as not changed on cloned instance
+ 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
@@ -908,9 +1016,13 @@ class BasicsTest < ActiveRecord::TestCase
MyObject = Struct.new :attribute1, :attribute2
def test_serialized_attribute
+ Topic.serialize("content", MyObject)
+
myobj = MyObject.new('value1', 'value2')
topic = Topic.create("content" => myobj)
- Topic.serialize("content", MyObject)
+ assert_equal(myobj, topic.content)
+
+ topic.reload
assert_equal(myobj, topic.content)
end
@@ -927,7 +1039,6 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_nil_serialized_attribute_with_class_constraint
- myobj = MyObject.new('value1', 'value2')
topic = Topic.new
assert_nil topic.content
end
@@ -952,6 +1063,87 @@ class BasicsTest < ActiveRecord::TestCase
Topic.serialize(:content)
end
+ def test_serialized_default_class
+ Topic.serialize(:content, Hash)
+ topic = Topic.new
+ assert_equal Hash, topic.content.class
+ assert_equal Hash, topic.read_attribute(:content).class
+ topic.content["beer"] = "MadridRb"
+ assert topic.save
+ topic.reload
+ assert_equal Hash, topic.content.class
+ assert_equal "MadridRb", topic.content["beer"]
+ ensure
+ Topic.serialize(:content)
+ end
+
+ def test_serialized_no_default_class_for_object
+ topic = Topic.new
+ assert_nil topic.content
+ end
+
+ def test_serialized_boolean_value_true
+ Topic.serialize(:content)
+ topic = Topic.new(:content => true)
+ assert topic.save
+ topic = topic.reload
+ assert_equal topic.content, true
+ end
+
+ def test_serialized_boolean_value_false
+ Topic.serialize(:content)
+ topic = Topic.new(:content => false)
+ assert topic.save
+ topic = topic.reload
+ assert_equal topic.content, false
+ end
+
+ def test_serialize_with_coder
+ coder = Class.new {
+ # Identity
+ def load(thing)
+ thing
+ end
+
+ # base 64
+ def dump(thing)
+ [thing].pack('m')
+ end
+ }.new
+
+ Topic.serialize(:content, coder)
+ s = 'hello world'
+ topic = Topic.new(:content => s)
+ assert topic.save
+ topic = topic.reload
+ assert_equal [s].pack('m'), topic.content
+ ensure
+ Topic.serialize(:content)
+ end
+
+ def test_serialize_with_bcrypt_coder
+ crypt_coder = Class.new {
+ def load(thing)
+ return unless thing
+ BCrypt::Password.new thing
+ end
+
+ def dump(thing)
+ BCrypt::Password.create(thing).to_s
+ end
+ }.new
+
+ Topic.serialize(:content, crypt_coder)
+ password = 'password'
+ topic = Topic.new(:content => password)
+ assert topic.save
+ topic = topic.reload
+ assert_kind_of BCrypt::Password, topic.content
+ assert_equal(true, topic.content == password, 'password should equal')
+ ensure
+ Topic.serialize(:content)
+ end
+
def test_quote
author_name = "\\ \001 ' \n \\n \""
topic = Topic.create('author_name' => author_name)
@@ -1007,9 +1199,14 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_define_attr_method_with_block
- k = Class.new( ActiveRecord::Base )
- k.send(:define_attr_method, :primary_key) { "sys_" + original_primary_key }
- assert_equal "sys_id", k.primary_key
+ k = Class.new( ActiveRecord::Base ) do
+ class << self
+ attr_accessor :foo_key
+ end
+ end
+ k.foo_key = "id"
+ k.send(:define_attr_method, :foo_key) { "sys_" + original_foo_key }
+ assert_equal "sys_id", k.foo_key
end
def test_set_table_name_with_value
@@ -1020,6 +1217,16 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "bar", k.table_name
end
+ def test_switching_between_table_name
+ assert_difference("GoodJoke.count") do
+ Joke.set_table_name "cold_jokes"
+ Joke.create
+
+ Joke.set_table_name "funny_jokes"
+ Joke.create
+ end
+ end
+
def test_quoted_table_name_after_set_table_name
klass = Class.new(ActiveRecord::Base)
@@ -1048,6 +1255,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_set_primary_key_with_block
k = Class.new( ActiveRecord::Base )
+ k.primary_key = 'id'
k.set_primary_key { "sys_" + original_primary_key }
assert_equal "sys_id", k.primary_key
end
@@ -1100,12 +1308,6 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal res6, res7
end
- def test_interpolate_sql
- assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo@bar') }
- assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar) baz') }
- assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar} baz') }
- end
-
def test_scoped_find_conditions
scoped_developers = Developer.send(:with_scope, :find => { :conditions => 'salary > 90000' }) do
Developer.find(:all, :conditions => 'id < 5')
@@ -1114,6 +1316,12 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal 3, scoped_developers.size
end
+ def test_no_limit_offset
+ assert_nothing_raised do
+ Developer.find(:all, :offset => 2)
+ end
+ end
+
def test_scoped_find_limit_offset
scoped_developers = Developer.send(:with_scope, :find => { :limit => 3, :offset => 2 }) do
Developer.find(:all, :order => 'id')
@@ -1138,18 +1346,18 @@ class BasicsTest < ActiveRecord::TestCase
scoped_developers = Developer.send(:with_scope, :find => { :limit => 1 }) do
Developer.find(:all, :order => 'salary DESC')
end
- # Test scope order + find order, find has priority
+ # Test scope order + find order, order has priority
scoped_developers = Developer.send(:with_scope, :find => { :limit => 3, :order => 'id DESC' }) do
Developer.find(:all, :order => 'salary ASC')
end
assert scoped_developers.include?(developers(:poor_jamis))
- assert scoped_developers.include?(developers(:david))
+ assert ! scoped_developers.include?(developers(:david))
assert ! scoped_developers.include?(developers(:jamis))
assert_equal 3, scoped_developers.size
# Test without scoped find conditions to ensure we get the right thing
- developers = Developer.find(:all, :order => 'id', :limit => 1)
- assert scoped_developers.include?(developers(:david))
+ assert ! scoped_developers.include?(Developer.find(1))
+ assert scoped_developers.include?(Developer.find(11))
end
def test_scoped_find_limit_offset_including_has_many_association
@@ -1311,7 +1519,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_inspect_instance
topic = topics(:first)
- assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@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", approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil, group: nil>), topic.inspect
+ assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@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", 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)}">), topic.inspect
end
def test_inspect_new_instance
@@ -1393,10 +1601,6 @@ class BasicsTest < ActiveRecord::TestCase
ActiveRecord::Base.logger = original_logger
end
- def test_dup
- assert !Minimalistic.new.freeze.dup.frozen?
- end
-
def test_compute_type_success
assert_equal Author, ActiveRecord::Base.send(:compute_type, 'Author')
end
@@ -1408,24 +1612,40 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_compute_type_no_method_error
- String.any_instance.stubs(:constantize).raises(NoMethodError)
+ ActiveSupport::Dependencies.stubs(:constantize).raises(NoMethodError)
assert_raises NoMethodError do
ActiveRecord::Base.send :compute_type, 'InvalidModel'
end
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 test_clear_cache!
+ # preheat cache
+ c1 = Post.columns
+ ActiveRecord::Base.clear_cache!
+ c2 = Post.columns
+ assert_not_equal c1, c2
+ 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
+ def test_default_scope_is_reset
+ Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base)
+ UnloadablePost.table_name = 'posts'
+ UnloadablePost.class_eval do
+ default_scope order('posts.comments_count ASC')
end
+ UnloadablePost.scoped_methods # make Thread.current[:UnloadablePost_scoped_methods] not nil
+
+ UnloadablePost.unloadable
+ assert_not_nil Thread.current[:UnloadablePost_scoped_methods]
+ ActiveSupport::Dependencies.remove_unloadable_constants!
+ assert_nil Thread.current[:UnloadablePost_scoped_methods]
+ ensure
+ Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost)
+ end
+
+ def test_marshal_round_trip
+ expected = posts(:welcome)
+ actual = Marshal.load(Marshal.dump(expected))
+
+ assert_equal expected.attributes, actual.attributes
+ end
end
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index dcc49e12ca..dc0e0da4c5 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -7,6 +7,7 @@ class EachTest < ActiveRecord::TestCase
def setup
@posts = Post.order("id asc")
@total = Post.count
+ Post.count('id') # preheat arel's table cache
end
def test_each_should_excecute_one_query_per_batch
@@ -24,7 +25,7 @@ class EachTest < ActiveRecord::TestCase
end
def test_each_should_execute_if_id_is_in_select
- assert_queries(4) do
+ assert_queries(6) do
Post.find_each(:select => "id, title, type", :batch_size => 2) do |post|
assert_kind_of Post, post
end
diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb
new file mode 100644
index 0000000000..19383bb06b
--- /dev/null
+++ b/activerecord/test/cases/bind_parameter_test.rb
@@ -0,0 +1,90 @@
+require 'cases/helper'
+require 'models/topic'
+
+module ActiveRecord
+ class BindParameterTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ class LogListener
+ attr_accessor :calls
+
+ def initialize
+ @calls = []
+ end
+
+ def call(*args)
+ calls << args
+ end
+ end
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @listener = LogListener.new
+ @pk = Topic.columns.find { |c| c.primary }
+ ActiveSupport::Notifications.subscribe('sql.active_record', @listener)
+ end
+
+ def teardown
+ ActiveSupport::Notifications.unsubscribe(@listener)
+ end
+
+ def test_binds_are_logged
+ # FIXME: use skip with minitest
+ return unless @connection.supports_statement_cache?
+
+ sub = @connection.substitute_for(@pk, [])
+ binds = [[@pk, 1]]
+ sql = "select * from topics where id = #{sub}"
+
+ @connection.exec_query(sql, 'SQL', binds)
+
+ message = @listener.calls.find { |args| args[4][:sql] == sql }
+ assert_equal binds, message[4][:binds]
+ end
+
+ def test_find_one_uses_binds
+ # FIXME: use skip with minitest
+ return unless @connection.supports_statement_cache?
+
+ Topic.find(1)
+ binds = [[@pk, 1]]
+ message = @listener.calls.find { |args| args[4][:binds] == binds }
+ assert message, 'expected a message with binds'
+ end
+
+ def test_logs_bind_vars
+ # FIXME: use skip with minitest
+ return unless @connection.supports_statement_cache?
+
+ pk = Topic.columns.find { |x| x.primary }
+
+ payload = {
+ :name => 'SQL',
+ :sql => 'select * from topics where id = ?',
+ :binds => [[pk, 10]]
+ }
+ event = ActiveSupport::Notifications::Event.new(
+ 'foo',
+ Time.now,
+ Time.now,
+ 123,
+ payload)
+
+ logger = Class.new(ActiveRecord::LogSubscriber) {
+ attr_reader :debugs
+ def initialize
+ super
+ @debugs = []
+ end
+
+ def debug str
+ @debugs << str
+ end
+ }.new
+
+ logger.sql event
+ assert_match([[pk.name, 10]].inspect, logger.debugs.first)
+ end
+ end
+end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index afef31396e..caf07a7357 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -23,6 +23,17 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 53.0, value
end
+ def test_should_return_decimal_average_of_integer_field
+ value = Account.average(:id)
+ assert_equal 3.5, value
+ end
+
+ def test_should_return_integer_average_if_db_returns_such
+ Account.connection.stubs :select_value => 3
+ value = Account.average(:id)
+ assert_equal 3, value
+ end
+
def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
@@ -54,6 +65,19 @@ class CalculationsTest < ActiveRecord::TestCase
c = Account.sum(:credit_limit, :group => :firm_id)
[1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
end
+
+ def test_should_group_by_multiple_fields
+ c = Account.count(:all, :group => ['firm_id', :credit_limit])
+ [ [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.sum(:credit_limit, :group => :firm_id)
@@ -85,6 +109,36 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal [2, 6], c.keys.compact
end
+ def test_limit_with_offset_is_kept
+ return if current_adapter?(:OracleAdapter)
+
+ queries = assert_sql { Account.limit(1).offset(1).count }
+ assert_equal 1, queries.length
+ assert_match(/LIMIT/, queries.first)
+ assert_match(/OFFSET/, queries.first)
+ end
+
+ def test_offset_without_limit_removes_offset
+ queries = assert_sql { Account.offset(1).count }
+ assert_equal 1, queries.length
+ assert_no_match(/LIMIT/, queries.first)
+ assert_no_match(/OFFSET/, queries.first)
+ end
+
+ def test_limit_without_offset_removes_limit
+ queries = assert_sql { Account.limit(1).count }
+ assert_equal 1, queries.length
+ assert_no_match(/LIMIT/, queries.first)
+ assert_no_match(/OFFSET/, queries.first)
+ end
+
+ def test_no_limit_no_offset
+ queries = assert_sql { Account.count }
+ assert_equal 1, queries.length
+ assert_no_match(/LIMIT/, queries.first)
+ assert_no_match(/OFFSET/, queries.first)
+ end
+
def test_should_group_by_summed_field_having_condition
c = Account.sum(:credit_limit, :group => :firm_id,
:having => 'sum(credit_limit) > 50')
@@ -275,6 +329,17 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 2, Account.count(:firm_id, :conditions => "credit_limit = 50 AND firm_id IS NOT NULL")
end
+ def test_should_count_field_in_joined_table
+ assert_equal 5, Account.count('companies.id', :joins => :firm)
+ assert_equal 4, Account.count('companies.id', :joins => :firm, :distinct => true)
+ end
+
+ def test_should_count_field_in_joined_table_with_group_by
+ c = Account.count('companies.id', :group => 'accounts.firm_id', :joins => :firm)
+
+ [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
@@ -336,4 +401,12 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal Account.count(:all), Company.count(:all, :from => 'accounts')
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).count(:author_name, :distinct => true)[true]
+ assert_equal distinct_authors_for_approved_count, 2
+ end
end
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
index dc7f82b001..7f4d25790b 100644
--- a/activerecord/test/cases/callbacks_test.rb
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -16,6 +16,7 @@ class CallbackDeveloper < ActiveRecord::Base
define_method(callback_method) do
self.history << [callback_method, :method]
end
+ send(callback_method, :"#{callback_method}")
end
def callback_object(callback_method)
@@ -27,15 +28,13 @@ class CallbackDeveloper < ActiveRecord::Base
end
end
- ActiveSupport::Deprecation.silence do
- 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
+ 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
@@ -461,7 +460,12 @@ class CallbacksTest < ActiveRecord::TestCase
[ :before_validation, :proc ],
[ :before_validation, :object ],
[ :before_validation, :block ],
- [ :before_validation, :returning_false ]
+ [ :before_validation, :returning_false ],
+ [ :after_rollback, :block ],
+ [ :after_rollback, :object ],
+ [ :after_rollback, :proc ],
+ [ :after_rollback, :string ],
+ [ :after_rollback, :method ],
], david.history
end
diff --git a/activerecord/test/cases/clone_test.rb b/activerecord/test/cases/clone_test.rb
new file mode 100644
index 0000000000..d91646efca
--- /dev/null
+++ b/activerecord/test/cases/clone_test.rb
@@ -0,0 +1,33 @@
+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
+ 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 0000000000..c7dcc21809
--- /dev/null
+++ b/activerecord/test/cases/coders/yaml_column_test.rb
@@ -0,0 +1,46 @@
+
+require "cases/helper"
+
+module ActiveRecord
+ module Coders
+ class YAMLColumnTest < ActiveRecord::TestCase
+ def test_initialize_takes_class
+ coder = YAMLColumn.new(Object)
+ assert_equal Object, coder.object_class
+ end
+
+ def test_type_mismatch_on_different_classes
+ coder = YAMLColumn.new(Array)
+ assert_raises(SerializationTypeMismatch) do
+ coder.load "--- foo"
+ end
+ end
+
+ def test_nil_is_ok
+ coder = YAMLColumn.new
+ assert_nil coder.load "--- "
+ end
+
+ def test_returns_new_with_different_class
+ coder = YAMLColumn.new SerializationTypeMismatch
+ assert_equal SerializationTypeMismatch, coder.load("--- ").class
+ end
+
+ def test_returns_string_unless_starts_with_dash
+ coder = YAMLColumn.new
+ assert_equal 'foo', coder.load("foo")
+ end
+
+ def test_load_handles_other_classes
+ coder = YAMLColumn.new
+ assert_equal [], coder.load([])
+ end
+
+ def test_load_swallows_yaml_exceptions
+ coder = YAMLColumn.new
+ bad_yaml = '--- {'
+ assert_equal bad_yaml, coder.load(bad_yaml)
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb
index cc6a6b44f2..d1dddd4c2c 100644
--- a/activerecord/test/cases/column_definition_test.rb
+++ b/activerecord/test/cases/column_definition_test.rb
@@ -1,121 +1,145 @@
require "cases/helper"
-class ColumnDefinitionTest < ActiveRecord::TestCase
- def setup
- @adapter = ActiveRecord::ConnectionAdapters::AbstractAdapter.new(nil)
- def @adapter.native_database_types
- {:string => "varchar"}
- end
- end
+module ActiveRecord
+ module ConnectionAdapters
+ class ColumnDefinitionTest < ActiveRecord::TestCase
+ def setup
+ @adapter = AbstractAdapter.new(nil)
+ def @adapter.native_database_types
+ {:string => "varchar"}
+ end
+ end
- # Avoid column definitions in create table statements like:
- # `title` varchar(255) DEFAULT NULL
- def test_should_not_include_default_clause_when_default_is_null
- column = ActiveRecord::ConnectionAdapters::Column.new("title", nil, "varchar(20)")
- column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
- @adapter, column.name, "string",
- column.limit, column.precision, column.scale, column.default, column.null)
- assert_equal "title varchar(20)", column_def.to_sql
- end
+ def test_can_set_coder
+ column = Column.new("title", nil, "varchar(20)")
+ column.coder = YAML
+ assert_equal YAML, column.coder
+ end
- def test_should_include_default_clause_when_default_is_present
- column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)")
- column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
- @adapter, column.name, "string",
- column.limit, column.precision, column.scale, column.default, column.null)
- assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, column_def.to_sql
- end
+ def test_encoded?
+ column = Column.new("title", nil, "varchar(20)")
+ assert !column.encoded?
- def test_should_specify_not_null_if_null_option_is_false
- column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)", false)
- column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
- @adapter, column.name, "string",
- column.limit, column.precision, column.scale, column.default, column.null)
- assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, column_def.to_sql
- end
+ column.coder = YAML
+ assert column.encoded?
+ end
- if current_adapter?(:MysqlAdapter)
- def test_should_set_default_for_mysql_binary_data_types
- binary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "binary(1)")
- assert_equal "a", binary_column.default
+ def test_type_case_coded_column
+ column = Column.new("title", nil, "varchar(20)")
+ column.coder = YAML
+ assert_equal "hello", column.type_cast("--- hello")
+ end
- varbinary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "varbinary(1)")
- assert_equal "a", varbinary_column.default
- end
+ # Avoid column definitions in create table statements like:
+ # `title` varchar(255) DEFAULT NULL
+ def test_should_not_include_default_clause_when_default_is_null
+ column = Column.new("title", nil, "varchar(20)")
+ column_def = ColumnDefinition.new(
+ @adapter, column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal "title varchar(20)", column_def.to_sql
+ end
- def test_should_not_set_default_for_blob_and_text_data_types
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "blob")
+ def test_should_include_default_clause_when_default_is_present
+ column = Column.new("title", "Hello", "varchar(20)")
+ column_def = ColumnDefinition.new(
+ @adapter, column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, column_def.to_sql
end
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "Hello", "text")
+ def test_should_specify_not_null_if_null_option_is_false
+ column = Column.new("title", "Hello", "varchar(20)", false)
+ column_def = ColumnDefinition.new(
+ @adapter, column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, column_def.to_sql
end
- text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text")
- assert_equal nil, text_column.default
+ if current_adapter?(:MysqlAdapter)
+ def test_should_set_default_for_mysql_binary_data_types
+ binary_column = MysqlColumn.new("title", "a", "binary(1)")
+ assert_equal "a", binary_column.default
- not_null_text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text", false)
- assert_equal "", not_null_text_column.default
- end
+ varbinary_column = MysqlColumn.new("title", "a", "varbinary(1)")
+ assert_equal "a", varbinary_column.default
+ end
- def test_has_default_should_return_false_for_blog_and_test_data_types
- blob_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "blob")
- assert !blob_column.has_default?
+ def test_should_not_set_default_for_blob_and_text_data_types
+ assert_raise ArgumentError do
+ MysqlColumn.new("title", "a", "blob")
+ end
- text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text")
- assert !text_column.has_default?
- end
- end
+ assert_raise ArgumentError do
+ MysqlColumn.new("title", "Hello", "text")
+ end
- if current_adapter?(:Mysql2Adapter)
- def test_should_set_default_for_mysql_binary_data_types
- binary_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "binary(1)")
- assert_equal "a", binary_column.default
+ text_column = MysqlColumn.new("title", nil, "text")
+ assert_equal nil, text_column.default
- varbinary_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "varbinary(1)")
- assert_equal "a", varbinary_column.default
- end
+ not_null_text_column = MysqlColumn.new("title", nil, "text", false)
+ assert_equal "", not_null_text_column.default
+ end
- def test_should_not_set_default_for_blob_and_text_data_types
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "blob")
- end
+ def test_has_default_should_return_false_for_blog_and_test_data_types
+ blob_column = MysqlColumn.new("title", nil, "blob")
+ assert !blob_column.has_default?
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "Hello", "text")
+ text_column = MysqlColumn.new("title", nil, "text")
+ assert !text_column.has_default?
+ end
end
- text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text")
- assert_equal nil, text_column.default
+ if current_adapter?(:Mysql2Adapter)
+ def test_should_set_default_for_mysql_binary_data_types
+ binary_column = Mysql2Column.new("title", "a", "binary(1)")
+ assert_equal "a", binary_column.default
- not_null_text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text", false)
- assert_equal "", not_null_text_column.default
- end
+ varbinary_column = Mysql2Column.new("title", "a", "varbinary(1)")
+ assert_equal "a", varbinary_column.default
+ end
- def test_has_default_should_return_false_for_blog_and_test_data_types
- blob_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "blob")
- assert !blob_column.has_default?
+ def test_should_not_set_default_for_blob_and_text_data_types
+ assert_raise ArgumentError do
+ Mysql2Column.new("title", "a", "blob")
+ end
- text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text")
- assert !text_column.has_default?
- end
- end
+ assert_raise ArgumentError do
+ Mysql2Column.new("title", "Hello", "text")
+ end
- if current_adapter?(:PostgreSQLAdapter)
- def test_bigint_column_should_map_to_integer
- bigint_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('number', nil, "bigint")
- assert_equal :integer, bigint_column.type
- end
+ text_column = Mysql2Column.new("title", nil, "text")
+ assert_equal nil, text_column.default
- def test_smallint_column_should_map_to_integer
- smallint_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('number', nil, "smallint")
- assert_equal :integer, smallint_column.type
- end
+ not_null_text_column = Mysql2Column.new("title", nil, "text", false)
+ assert_equal "", not_null_text_column.default
+ end
+
+ def test_has_default_should_return_false_for_blog_and_test_data_types
+ blob_column = Mysql2Column.new("title", nil, "blob")
+ assert !blob_column.has_default?
- def test_uuid_column_should_map_to_string
- uuid_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('unique_id', nil, "uuid")
- assert_equal :string, uuid_column.type
+ text_column = Mysql2Column.new("title", nil, "text")
+ assert !text_column.has_default?
+ end
+ end
+
+ if current_adapter?(:PostgreSQLAdapter)
+ def test_bigint_column_should_map_to_integer
+ bigint_column = PostgreSQLColumn.new('number', nil, "bigint")
+ assert_equal :integer, bigint_column.type
+ end
+
+ def test_smallint_column_should_map_to_integer
+ smallint_column = PostgreSQLColumn.new('number', nil, "smallint")
+ assert_equal :integer, smallint_column.type
+ end
+
+ def test_uuid_column_should_map_to_string
+ uuid_column = PostgreSQLColumn.new('unique_id', nil, "uuid")
+ assert_equal :string, uuid_column.type
+ end
+ end
end
end
end
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index 82b3c36ed2..7ac14fa8d6 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -3,6 +3,58 @@ require "cases/helper"
module ActiveRecord
module ConnectionAdapters
class ConnectionPoolTest < ActiveRecord::TestCase
+ def setup
+ # Keep a duplicate pool so we do not bother others
+ @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+
+ if in_memory_db?
+ # Separate connections to an in-memory database create an entirely new database,
+ # with an empty schema etc, so we just stub out this schema on the fly.
+ @pool.with_connection do |connection|
+ connection.create_table :posts do |t|
+ t.integer :cololumn
+ end
+ end
+ end
+ end
+
+ def test_pool_caches_columns
+ columns = @pool.columns['posts']
+ assert_equal columns, @pool.columns['posts']
+ end
+
+ def test_pool_caches_columns_hash
+ columns_hash = @pool.columns_hash['posts']
+ assert_equal columns_hash, @pool.columns_hash['posts']
+ end
+
+ def test_clearing_column_cache
+ @pool.columns['posts']
+ @pool.columns_hash['posts']
+
+ @pool.clear_cache!
+
+ assert_equal 0, @pool.columns.size
+ assert_equal 0, @pool.columns_hash.size
+ end
+
+ def test_primary_key
+ assert_equal 'id', @pool.primary_keys['posts']
+ end
+
+ def test_primary_key_for_non_existent_table
+ assert_equal 'id', @pool.primary_keys['omgponies']
+ end
+
+ def test_primary_key_is_set_on_columns
+ posts_columns = @pool.columns_hash['posts']
+ assert posts_columns['id'].primary
+
+ (posts_columns.keys - ['id']).each do |key|
+ assert !posts_columns[key].primary
+ end
+ end
+
def test_clear_stale_cached_connections!
pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
@@ -26,6 +78,55 @@ module ActiveRecord
"threads should have been removed")
assert_equal pool.checkins.length, threads.length
end
+
+ def test_checkout_behaviour
+ pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ connection = pool.connection
+ assert_not_nil connection
+ threads = []
+ 4.times do |i|
+ threads << Thread.new(i) do |pool_count|
+ connection = pool.connection
+ assert_not_nil connection
+ end
+ end
+
+ threads.each {|t| t.join}
+
+ Thread.new do
+ threads.each do |t|
+ thread_ids = pool.instance_variable_get(:@reserved_connections).keys
+ assert thread_ids.include?(t.object_id)
+ end
+
+ pool.connection
+ threads.each do |t|
+ thread_ids = pool.instance_variable_get(:@reserved_connections).keys
+ assert !thread_ids.include?(t.object_id)
+ end
+ end.join()
+
+ end
+
+ def test_automatic_reconnect=
+ pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ assert pool.automatic_reconnect
+ assert pool.connection
+
+ pool.disconnect!
+ assert pool.connection
+
+ pool.disconnect!
+ pool.automatic_reconnect = false
+
+ assert_raises(ConnectionNotEstablished) do
+ pool.connection
+ end
+
+ assert_raises(ConnectionNotEstablished) do
+ pool.with_connection
+ end
+ end
end
end
end
diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb
index 137236255d..3ed96a3ec8 100644
--- a/activerecord/test/cases/counter_cache_test.rb
+++ b/activerecord/test/cases/counter_cache_test.rb
@@ -43,7 +43,7 @@ class CounterCacheTest < ActiveRecord::TestCase
Topic.reset_counters(@topic.id, :replies)
end
end
-
+
test "reset counters with string argument" do
Topic.increment_counter('replies_count', @topic.id)
diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb
new file mode 100644
index 0000000000..d63ecdbcc5
--- /dev/null
+++ b/activerecord/test/cases/custom_locking_test.rb
@@ -0,0 +1,17 @@
+require "cases/helper"
+require 'models/person'
+
+module ActiveRecord
+ class CustomLockingTest < ActiveRecord::TestCase
+ fixtures :people
+
+ def test_custom_lock
+ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ assert_match 'SHARE MODE', Person.lock('LOCK IN SHARE MODE').to_sql
+ assert_sql(/LOCK IN SHARE MODE/) do
+ Person.find(1, :lock => 'LOCK IN SHARE MODE')
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/date_time_test.rb b/activerecord/test/cases/date_time_test.rb
index a8b4b7a096..3deb0dac99 100644
--- a/activerecord/test/cases/date_time_test.rb
+++ b/activerecord/test/cases/date_time_test.rb
@@ -4,17 +4,21 @@ require 'models/task'
class DateTimeTest < ActiveRecord::TestCase
def test_saves_both_date_and_time
- time_values = [1807, 2, 10, 15, 30, 45]
- # create DateTime value with local time zone offset
- local_offset = Rational(Time.local_time(*time_values).utc_offset, 86400)
- now = DateTime.civil(*(time_values + [local_offset]))
+ 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(*time_values).utc_offset, 86400)
+ now = DateTime.civil(*(time_values + [local_offset]))
- task = Task.new
- task.starting = now
- task.save!
+ task = Task.new
+ task.starting = now
+ task.save!
- # check against Time.local_time, since some platforms will return a Time instead of a DateTime
- assert_equal Time.local_time(*time_values), Task.find(task.id).starting
+ # check against Time.local_time, since some platforms will return a Time instead of a DateTime
+ assert_equal Time.local_time(*time_values), Task.find(task.id).starting
+ end
+ end
end
def test_assign_empty_date_time
diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb
index 0e90128907..deaf5252db 100644
--- a/activerecord/test/cases/defaults_test.rb
+++ b/activerecord/test/cases/defaults_test.rb
@@ -29,7 +29,7 @@ class DefaultTest < ActiveRecord::TestCase
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)
@@ -50,7 +50,7 @@ if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
#
# We don't want that to happen, so we disable transactional fixtures here.
self.use_transactional_fixtures = false
-
+
# MySQL 5 and higher is quirky with not null text/blob columns.
# With MySQL Text/blob columns cannot have defaults. If the column is not
# null MySQL will report that the column has a null default
@@ -80,7 +80,7 @@ if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
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
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
index 837386ed24..a6738fb654 100644
--- a/activerecord/test/cases/dirty_test.rb
+++ b/activerecord/test/cases/dirty_test.rb
@@ -338,13 +338,13 @@ class DirtyTest < ActiveRecord::TestCase
assert !pirate.changed?
end
- def test_cloned_objects_should_not_copy_dirty_flag_from_creator
+ def test_dup_objects_should_not_copy_dirty_flag_from_creator
pirate = Pirate.create!(:catchphrase => "shiver me timbers")
- pirate_clone = pirate.clone
- pirate_clone.reset_catchphrase!
+ pirate_dup = pirate.dup
+ pirate_dup.reset_catchphrase!
pirate.catchphrase = "I love Rum"
assert pirate.catchphrase_changed?
- assert !pirate_clone.catchphrase_changed?
+ assert !pirate_dup.catchphrase_changed?
end
def test_reverted_changes_are_not_dirty
@@ -395,6 +395,20 @@ class DirtyTest < ActiveRecord::TestCase
end
end
+ def test_save_always_should_update_timestamps_when_serialized_attributes_are_present
+ with_partial_updates(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_updates_if_not_present
with_partial_updates(Topic) do
Topic.create!(:author_name => 'Bill', :content => {:a => "a"})
@@ -408,11 +422,11 @@ class DirtyTest < ActiveRecord::TestCase
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']
@@ -421,21 +435,21 @@ class DirtyTest < ActiveRecord::TestCase
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
@@ -475,11 +489,12 @@ class DirtyTest < ActiveRecord::TestCase
pirate = Pirate.find_by_catchphrase("Ahoy!")
pirate.update_attribute(:catchphrase, "Ninjas suck!")
- assert_equal 0, pirate.previous_changes.size
- assert_nil pirate.previous_changes['catchphrase']
- assert_nil pirate.previous_changes['updated_on']
+ 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')
+ assert !pirate.previous_changes.key?('created_on')
end
private
diff --git a/activerecord/test/cases/dup_test.rb b/activerecord/test/cases/dup_test.rb
new file mode 100644
index 0000000000..0236f9b0a1
--- /dev/null
+++ b/activerecord/test/cases/dup_test.rb
@@ -0,0 +1,103 @@
+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
+
+ #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
+
+ end
+end
diff --git a/activerecord/test/cases/dynamic_finder_match_test.rb b/activerecord/test/cases/dynamic_finder_match_test.rb
new file mode 100644
index 0000000000..e576870317
--- /dev/null
+++ b/activerecord/test/cases/dynamic_finder_match_test.rb
@@ -0,0 +1,98 @@
+require "cases/helper"
+
+module ActiveRecord
+ class DynamicFinderMatchTest < ActiveRecord::TestCase
+ def test_find_or_create_by
+ match = DynamicFinderMatch.match("find_or_create_by_age_and_sex_and_location")
+ assert_not_nil match
+ assert !match.finder?
+ assert match.instantiator?
+ assert_equal :first, match.finder
+ assert_equal :create, match.instantiator
+ assert_equal %w(age sex location), match.attribute_names
+ end
+
+ def test_find_or_initialize_by
+ match = DynamicFinderMatch.match("find_or_initialize_by_age_and_sex_and_location")
+ assert_not_nil match
+ assert !match.finder?
+ assert match.instantiator?
+ assert_equal :first, match.finder
+ assert_equal :new, match.instantiator
+ assert_equal %w(age sex location), match.attribute_names
+ end
+
+ def test_find_no_match
+ assert_nil DynamicFinderMatch.match("not_a_finder")
+ end
+
+ def find_by_bang
+ match = DynamicFinderMatch.match("find_by_age_and_sex_and_location!")
+ assert_not_nil match
+ assert match.finder?
+ assert match.bang?
+ assert_equal :first, match.finder
+ assert_equal %w(age sex location), match.attribute_names
+ end
+
+ def test_find_by
+ match = DynamicFinderMatch.match("find_by_age_and_sex_and_location")
+ assert_not_nil match
+ assert match.finder?
+ assert_equal :first, match.finder
+ assert_equal %w(age sex location), match.attribute_names
+ end
+
+ def test_find_by_with_symbol
+ m = DynamicFinderMatch.match(:find_by_foo)
+ assert_equal :first, m.finder
+ assert_equal %w{ foo }, m.attribute_names
+ end
+
+ def test_find_all_by_with_symbol
+ m = DynamicFinderMatch.match(:find_all_by_foo)
+ assert_equal :all, m.finder
+ assert_equal %w{ foo }, m.attribute_names
+ end
+
+ def test_find_all_by
+ match = DynamicFinderMatch.match("find_all_by_age_and_sex_and_location")
+ assert_not_nil match
+ assert match.finder?
+ assert_equal :all, match.finder
+ assert_equal %w(age sex location), match.attribute_names
+ end
+
+ def test_find_last_by
+ m = DynamicFinderMatch.match(:find_last_by_foo)
+ assert_equal :last, m.finder
+ assert_equal %w{ foo }, m.attribute_names
+ end
+
+ def test_find_by!
+ m = DynamicFinderMatch.match(:find_by_foo!)
+ assert_equal :first, m.finder
+ assert m.bang?, 'should be banging'
+ assert_equal %w{ foo }, m.attribute_names
+ end
+
+ def test_find_or_create
+ m = DynamicFinderMatch.match(:find_or_create_by_foo)
+ assert_equal :first, m.finder
+ assert_equal %w{ foo }, m.attribute_names
+ assert_equal :create, m.instantiator
+ end
+
+ def test_find_or_initialize
+ m = DynamicFinderMatch.match(:find_or_initialize_by_foo)
+ assert_equal :first, m.finder
+ assert_equal %w{ foo }, m.attribute_names
+ assert_equal :new, m.instantiator
+ end
+
+ def test_garbage
+ assert !DynamicFinderMatch.match(:fooo), 'should be false'
+ assert !DynamicFinderMatch.match(:find_by), 'should be false'
+ end
+ end
+end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 4f3e43d77d..543981b4a0 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -10,57 +10,7 @@ require 'models/entrant'
require 'models/project'
require 'models/developer'
require 'models/customer'
-
-class DynamicFinderMatchTest < ActiveRecord::TestCase
- def test_find_no_match
- assert_nil ActiveRecord::DynamicFinderMatch.match("not_a_finder")
- end
-
- def test_find_by
- match = ActiveRecord::DynamicFinderMatch.match("find_by_age_and_sex_and_location")
- assert_not_nil match
- assert match.finder?
- assert_equal :first, match.finder
- assert_equal %w(age sex location), match.attribute_names
- end
-
- def find_by_bang
- match = ActiveRecord::DynamicFinderMatch.match("find_by_age_and_sex_and_location!")
- assert_not_nil match
- assert match.finder?
- assert match.bang?
- assert_equal :first, match.finder
- assert_equal %w(age sex location), match.attribute_names
- end
-
- def test_find_all_by
- match = ActiveRecord::DynamicFinderMatch.match("find_all_by_age_and_sex_and_location")
- assert_not_nil match
- assert match.finder?
- assert_equal :all, match.finder
- assert_equal %w(age sex location), match.attribute_names
- end
-
- def test_find_or_initialize_by
- match = ActiveRecord::DynamicFinderMatch.match("find_or_initialize_by_age_and_sex_and_location")
- assert_not_nil match
- assert !match.finder?
- assert match.instantiator?
- assert_equal :first, match.finder
- assert_equal :new, match.instantiator
- assert_equal %w(age sex location), match.attribute_names
- end
-
- def test_find_or_create_by
- match = ActiveRecord::DynamicFinderMatch.match("find_or_create_by_age_and_sex_and_location")
- assert_not_nil match
- assert !match.finder?
- assert match.instantiator?
- assert_equal :first, match.finder
- assert_equal :create, match.instantiator
- assert_equal %w(age sex location), match.attribute_names
- end
-end
+require 'models/toy'
class FinderTest < ActiveRecord::TestCase
fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :customers, :categories, :categorizations
@@ -174,11 +124,13 @@ class FinderTest < ActiveRecord::TestCase
def test_find_all_with_limit_and_offset_and_multiple_order_clauses
first_three_posts = Post.find :all, :order => 'author_id, id', :limit => 3, :offset => 0
second_three_posts = Post.find :all, :order => ' author_id,id ', :limit => 3, :offset => 3
- last_posts = Post.find :all, :order => ' author_id, id ', :limit => 3, :offset => 6
+ third_three_posts = Post.find :all, :order => ' author_id, id ', :limit => 3, :offset => 6
+ last_posts = Post.find :all, :order => ' author_id, id ', :limit => 3, :offset => 9
assert_equal [[0,3],[1,1],[1,2]], first_three_posts.map { |p| [p.author_id, p.id] }
assert_equal [[1,4],[1,5],[1,6]], second_three_posts.map { |p| [p.author_id, p.id] }
- assert_equal [[2,7]], last_posts.map { |p| [p.author_id, p.id] }
+ assert_equal [[2,7],[2,9],[2,11]], third_three_posts.map { |p| [p.author_id, p.id] }
+ assert_equal [[3,8],[3,10]], last_posts.map { |p| [p.author_id, p.id] }
end
@@ -239,6 +191,30 @@ class FinderTest < ActiveRecord::TestCase
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_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_unexisting_record_exception_handling
assert_raise(ActiveRecord::RecordNotFound) {
Topic.find(1).parent
@@ -310,7 +286,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_on_association_proxy_conditions
- assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10], Comment.find_all_by_post_id(authors(:david).posts).map(&:id).sort
+ assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10, 12], Comment.find_all_by_post_id(authors(:david).posts).map(&:id).sort
end
def test_find_on_hash_conditions_with_range
@@ -777,7 +753,7 @@ class FinderTest < ActiveRecord::TestCase
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.new_record?
+ assert sig38.persisted?
end
def test_find_or_create_from_two_attributes
@@ -785,7 +761,7 @@ class FinderTest < ActiveRecord::TestCase
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.new_record?
+ assert another.persisted?
end
def test_find_or_create_from_two_attributes_with_one_being_an_aggregate
@@ -793,7 +769,7 @@ class FinderTest < ActiveRecord::TestCase
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.new_record?
+ assert created_customer.persisted?
end
def test_find_or_create_from_one_attribute_and_hash
@@ -801,7 +777,7 @@ class FinderTest < ActiveRecord::TestCase
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.new_record?
+ assert sig38.persisted?
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
@@ -812,7 +788,7 @@ class FinderTest < ActiveRecord::TestCase
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.new_record?
+ assert created_customer.persisted?
end
def test_find_or_create_from_one_aggregate_attribute_and_hash
@@ -822,7 +798,7 @@ class FinderTest < ActiveRecord::TestCase
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.new_record?
+ assert created_customer.persisted?
assert_equal balance, created_customer.balance
assert_equal name, created_customer.name
end
@@ -830,13 +806,13 @@ class FinderTest < ActiveRecord::TestCase
def test_find_or_initialize_from_one_attribute
sig38 = Company.find_or_initialize_by_name("38signals")
assert_equal "38signals", sig38.name
- assert sig38.new_record?
+ 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.new_record?
+ assert !new_customer.persisted?
end
def test_find_or_initialize_from_one_attribute_should_not_set_attribute_even_when_protected
@@ -844,7 +820,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_not_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_not_set_attribute_even_when_protected
@@ -852,7 +828,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_not_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected
@@ -860,7 +836,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected
@@ -868,7 +844,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected_and_also_set_the_hash
@@ -876,7 +852,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected_and_also_set_the_hash
@@ -884,7 +860,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_should_set_protected_attributes_if_given_as_block
@@ -892,7 +868,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_should_set_protected_attributes_if_given_as_block
@@ -900,7 +876,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_create_should_work_with_block_on_first_call
@@ -911,21 +887,21 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert !c.new_record?
+ 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.new_record?
+ assert !another.persisted?
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.new_record?
+ assert !new_customer.persisted?
end
def test_find_or_initialize_from_one_attribute_and_hash
@@ -933,7 +909,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
- assert sig38.new_record?
+ assert !sig38.persisted?
end
def test_find_or_initialize_from_one_aggregate_attribute_and_hash
@@ -942,7 +918,7 @@ class FinderTest < ActiveRecord::TestCase
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.new_record?
+ assert !new_customer.persisted?
end
def test_find_with_bad_sql
@@ -999,7 +975,7 @@ class FinderTest < ActiveRecord::TestCase
# http://dev.rubyonrails.org/ticket/6778
def test_find_ignores_previously_inserted_record
- post = Post.create!(:title => 'test', :body => 'it out')
+ Post.create!(:title => 'test', :body => 'it out')
assert_equal [], Post.find_all_by_id(nil)
end
@@ -1032,7 +1008,7 @@ class FinderTest < ActiveRecord::TestCase
def test_select_rows
assert_equal(
- [["1", nil, nil, "37signals"],
+ [["1", "1", nil, "37signals"],
["2", "1", "2", "Summit"],
["3", "1", "1", "Microsoft"]],
Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}})
@@ -1061,6 +1037,15 @@ class FinderTest < ActiveRecord::TestCase
end
end
+ def test_find_one_message_with_custom_primary_key
+ Toy.set_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
+ end
+
protected
def bind(statement, *vars)
if vars.first.is_a?(Hash)
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index 93f8749255..fa40fad56d 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -13,6 +13,7 @@ require 'models/category'
require 'models/parrot'
require 'models/pirate'
require 'models/treasure'
+require 'models/traffic_light'
require 'models/matey'
require 'models/ship'
require 'models/book'
@@ -24,7 +25,7 @@ class FixturesTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
- fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries
+ fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights
FIXTURES = %w( accounts binaries companies customers
developers developers_projects entrants
@@ -34,7 +35,7 @@ class FixturesTest < ActiveRecord::TestCase
def test_clean_fixtures
FIXTURES.each do |name|
fixtures = nil
- assert_nothing_raised { fixtures = create_fixtures(name) }
+ assert_nothing_raised { fixtures = create_fixtures(name).first }
assert_kind_of(Fixtures, fixtures)
fixtures.each { |_name, fixture|
fixture.each { |key, value|
@@ -52,13 +53,13 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_attributes
- topics = create_fixtures("topics")
+ topics = create_fixtures("topics").first
assert_equal("The First Topic", topics["first"]["title"])
assert_nil(topics["second"]["author_email_address"])
end
def test_inserts
- topics = create_fixtures("topics")
+ 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"])
@@ -101,7 +102,7 @@ class FixturesTest < ActiveRecord::TestCase
second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'Mary'")
assert_nil(second_row["author_email_address"])
- # This checks for a caching problem which causes a bug in the fixtures
+ # 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"
ensure
@@ -114,7 +115,7 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_insert_with_datetime
- topics = create_fixtures("tasks")
+ create_fixtures("tasks")
first = Task.find(1)
assert first
end
@@ -126,12 +127,11 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_instantiation
- topics = create_fixtures("topics")
+ topics = create_fixtures("topics").first
assert_kind_of Topic, topics["first"].find
end
def test_complete_instantiation
- assert_equal 4, @topics.size
assert_equal "The First Topic", @first.title
end
@@ -141,7 +141,6 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_erb_in_fixtures
- assert_equal 11, @developers.size
assert_equal "fixture_5", @dev_5.name
end
@@ -153,6 +152,17 @@ class FixturesTest < ActiveRecord::TestCase
assert_not_nil Fixtures.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(FixturesFileNotFound) do
+ Fixtures.new( Account.connection, "companies", 'Company', nonexistent_fixture_path)
+ end
+ end
+
def test_dirty_dirty_yaml_file
assert_raise(Fixture::FormatError) do
Fixtures.new( Account.connection, "courses", 'Course', FIXTURES_ROOT + "/naked/yml/courses")
@@ -187,12 +197,15 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_binary_in_fixtures
- assert_equal 1, @binaries.size
data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read }
data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding)
data.freeze
assert_equal data, @flowers.data
end
+
+ def test_serialized_fixtures
+ assert_equal ["Green", "Red", "Orange"], traffic_lights(:uk).state
+ end
end
if Account.connection.respond_to?(:reset_pk_sequence!)
@@ -229,7 +242,7 @@ if Account.connection.respond_to?(:reset_pk_sequence!)
def test_create_fixtures_resets_sequences_when_not_cached
@instances.each do |instance|
- max_id = create_fixtures(instance.class.table_name).inject(0) do |_max_id, (name, fixture)|
+ max_id = create_fixtures(instance.class.table_name).first.fixtures.inject(0) do |_max_id, (_, fixture)|
fixture_id = fixture['id'].to_i
fixture_id > _max_id ? fixture_id : _max_id
end
@@ -256,7 +269,7 @@ class FixturesWithoutInstantiationTest < ActiveRecord::TestCase
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"
@@ -288,9 +301,6 @@ class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase
def test_without_instance_instantiation
assert !defined?(@first), "@first is not defined"
- assert_not_nil @topics
- assert_not_nil @developers
- assert_not_nil @accounts
end
end
@@ -368,10 +378,25 @@ class ForeignKeyFixturesTest < ActiveRecord::TestCase
end
end
+class OverRideFixtureMethodTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def topics(name)
+ topic = super
+ topic.title = 'omg'
+ topic
+ end
+
+ def test_fixture_methods_can_be_overridden
+ x = topics :first
+ assert_equal 'omg', x.title
+ end
+end
+
class CheckSetTableNameFixturesTest < ActiveRecord::TestCase
set_fixture_class :funny_jokes => 'Joke'
fixtures :funny_jokes
- # Set to false to blow away fixtures cache and ensure our fixtures are loaded
+ # 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
@@ -383,7 +408,7 @@ 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
+ # 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
@@ -395,7 +420,7 @@ 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
+ # 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
@@ -411,7 +436,7 @@ end
class CustomConnectionFixturesTest < ActiveRecord::TestCase
set_fixture_class :courses => Course
fixtures :courses
- # Set to false to blow away fixtures cache and ensure our fixtures are loaded
+ # 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
@@ -423,7 +448,7 @@ end
class InvalidTableNameFixturesTest < ActiveRecord::TestCase
fixtures :funny_jokes
- # Set to false to blow away fixtures cache and ensure our fixtures are loaded
+ # 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
@@ -437,7 +462,7 @@ 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
+ # 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
@@ -493,7 +518,7 @@ class FasterFixturesTest < ActiveRecord::TestCase
fixtures :categories, :authors
def load_extra_fixture(name)
- fixture = create_fixtures(name)
+ fixture = create_fixtures(name).first
assert fixture.is_a?(Fixtures)
@loaded_fixtures[fixture.table_name] = fixture
end
diff --git a/activerecord/test/cases/habtm_destroy_order_test.rb b/activerecord/test/cases/habtm_destroy_order_test.rb
new file mode 100644
index 0000000000..f2b91d977e
--- /dev/null
+++ b/activerecord/test/cases/habtm_destroy_order_test.rb
@@ -0,0 +1,51 @@
+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 "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
index 1fb59d3589..fd20f1b120 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -11,11 +11,13 @@ require 'mocha'
require 'active_record'
require 'active_support/dependencies'
-require 'connection'
-
begin
- require 'ruby-debug'
+ require 'connection'
rescue LoadError
+ # If we cannot load connection we assume that driver was not loaded for this test case, so we load sqlite3 as default one.
+ # This allows for running separate test cases by simply running test file.
+ connection_type = defined?(JRUBY_VERSION) ? 'jdbc' : 'native'
+ require "test/connections/#{connection_type}_sqlite3/connection"
end
# Show backtraces for deprecated behavior for quicker cleanup.
@@ -24,6 +26,9 @@ ActiveSupport::Deprecation.debug = true
# Quote "type" if it's a reserved word for the current connection.
QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type')
+# Enable Identity Map for testing
+ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "false" ? false : true)
+
def current_adapter?(*types)
types.any? do |type|
ActiveRecord::ConnectionAdapters.const_defined?(type) &&
@@ -31,16 +36,52 @@ def current_adapter?(*types)
end
end
-ActiveRecord::Base.connection.class.class_eval do
- IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /SHOW FIELDS/]
+def in_memory_db?
+ current_adapter?(:SQLiteAdapter) &&
+ ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:"
+end
- def execute_with_query_record(sql, name = nil, &block)
- $queries_executed ||= []
- $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r }
- execute_without_query_record(sql, name, &block)
- end
+def 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
- alias_method_chain :execute, :query_record
+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
+
+module ActiveRecord
+ class SQLCounter
+ IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/]
+
+ # FIXME: this needs to be refactored so specific database can add their own
+ # ignored SQL. This ignored SQL is for Oracle.
+ IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im]
+
+ def initialize
+ $queries_executed = []
+ 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
+ unless 'CACHE' == values[:name]
+ $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r }
+ end
+ end
+ end
+ ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new)
end
unless ENV['FIXTURE_DEBUG']
@@ -63,15 +104,15 @@ class ActiveSupport::TestCase
self.use_transactional_fixtures = true
def create_fixtures(*table_names, &block)
- Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
+ Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, fixture_class_names, &block)
end
end
-# silence verbose schema loading
-original_stdout = $stdout
-$stdout = StringIO.new
+def load_schema
+ # silence verbose schema loading
+ original_stdout = $stdout
+ $stdout = StringIO.new
-begin
adapter_name = ActiveRecord::Base.connection.adapter_name.downcase
adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb"
@@ -83,3 +124,22 @@ begin
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
diff --git a/activerecord/test/cases/i18n_test.rb b/activerecord/test/cases/i18n_test.rb
index 3287626378..469f513e68 100644
--- a/activerecord/test/cases/i18n_test.rb
+++ b/activerecord/test/cases/i18n_test.rb
@@ -7,12 +7,12 @@ 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)
diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb
new file mode 100644
index 0000000000..89f7b92d09
--- /dev/null
+++ b/activerecord/test/cases/identity_map_test.rb
@@ -0,0 +1,402 @@
+require "cases/helper"
+require 'models/developer'
+require 'models/project'
+require 'models/company'
+require 'models/topic'
+require 'models/reply'
+require 'models/computer'
+require 'models/customer'
+require 'models/order'
+require 'models/post'
+require 'models/author'
+require 'models/tag'
+require 'models/tagging'
+require 'models/comment'
+require 'models/sponsor'
+require 'models/member'
+require 'models/essay'
+require 'models/subscriber'
+require "models/pirate"
+require "models/bird"
+require "models/parrot"
+
+if ActiveRecord::IdentityMap.enabled?
+class IdentityMapTest < ActiveRecord::TestCase
+ fixtures :accounts, :companies, :developers, :projects, :topics,
+ :developers_projects, :computers, :authors, :author_addresses,
+ :posts, :tags, :taggings, :comments, :subscribers
+
+ ##############################################################################
+ # Basic tests checking if IM is functioning properly on basic find operations#
+ ##############################################################################
+
+ def test_find_id
+ assert_same(Client.find(3), Client.find(3))
+ end
+
+ def test_find_id_without_identity_map
+ ActiveRecord::IdentityMap.without do
+ assert_not_same(Client.find(3), Client.find(3))
+ end
+ end
+
+ def test_find_id_use_identity_map
+ ActiveRecord::IdentityMap.enabled = false
+ ActiveRecord::IdentityMap.use do
+ assert_same(Client.find(3), Client.find(3))
+ end
+ ActiveRecord::IdentityMap.enabled = true
+ end
+
+ def test_find_pkey
+ assert_same(
+ Subscriber.find('swistak'),
+ Subscriber.find('swistak')
+ )
+ end
+
+ def test_find_by_id
+ assert_same(
+ Client.find_by_id(3),
+ Client.find_by_id(3)
+ )
+ end
+
+ def test_find_by_string_and_numeric_id
+ assert_same(
+ Client.find_by_id("3"),
+ Client.find_by_id(3)
+ )
+ end
+
+ def test_find_by_pkey
+ assert_same(
+ Subscriber.find_by_nick('swistak'),
+ Subscriber.find_by_nick('swistak')
+ )
+ end
+
+ def test_find_first_id
+ assert_same(
+ Client.find(:first, :conditions => {:id => 1}),
+ Client.find(:first, :conditions => {:id => 1})
+ )
+ end
+
+ def test_find_first_pkey
+ assert_same(
+ Subscriber.find(:first, :conditions => {:nick => 'swistak'}),
+ Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ )
+ end
+
+ ##############################################################################
+ # Tests checking if IM is functioning properly on more advanced finds #
+ # and associations #
+ ##############################################################################
+
+ def test_owner_object_is_associated_from_identity_map
+ post = Post.find(1)
+ comment = post.comments.first
+
+ assert_no_queries do
+ comment.post
+ end
+ assert_same post, comment.post
+ end
+
+ def test_associated_object_are_assigned_from_identity_map
+ post = Post.find(1)
+
+ post.comments.each do |comment|
+ assert_same post, comment.post
+ assert_equal post.object_id, comment.post.object_id
+ end
+ end
+
+ def test_creation
+ t1 = Topic.create("title" => "t1")
+ t2 = Topic.find(t1.id)
+ assert_same(t1, t2)
+ end
+
+ ##############################################################################
+ # Tests checking dirty attribute behaviour with IM #
+ ##############################################################################
+
+ def test_loading_new_instance_should_not_update_dirty_attributes
+ swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ swistak.name = "Swistak Sreberkowiec"
+ assert_equal(["name"], swistak.changed)
+ assert_equal({"name" => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes)
+
+ s = Subscriber.find('swistak')
+
+ assert swistak.name_changed?
+ assert_equal("Swistak Sreberkowiec", swistak.name)
+ end
+
+ def test_loading_new_instance_should_change_dirty_attribute_original_value
+ swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ swistak.name = "Swistak Sreberkowiec"
+
+ Subscriber.update_all({:name => "Raczkowski Marcin"}, {:name => "Marcin Raczkowski"})
+
+ s = Subscriber.find('swistak')
+
+ assert_equal({'name' => ["Raczkowski Marcin", "Swistak Sreberkowiec"]}, swistak.changes)
+ assert_equal("Swistak Sreberkowiec", swistak.name)
+ end
+
+ def test_loading_new_instance_should_remove_dirt
+ swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ swistak.name = "Swistak Sreberkowiec"
+
+ assert_equal({"name" => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes)
+
+ Subscriber.update_all({:name => "Swistak Sreberkowiec"}, {:name => "Marcin Raczkowski"})
+
+ s = Subscriber.find('swistak')
+
+ assert_equal("Swistak Sreberkowiec", swistak.name)
+ assert_equal({}, swistak.changes)
+ assert !swistak.name_changed?
+ end
+
+ def test_has_many_associations
+ pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ pirate.birds.create!(:name => 'Posideons Killer')
+ pirate.birds.create!(:name => 'Killer bandita Dionne')
+
+ posideons, killer = pirate.birds
+
+ pirate.reload
+
+ pirate.birds_attributes = [{ :id => posideons.id, :name => 'Grace OMalley' }]
+ assert_equal 'Grace OMalley', pirate.birds.to_a.find { |r| r.id == posideons.id }.name
+ end
+
+ def test_changing_associations
+ post1 = Post.create("title" => "One post", "body" => "Posting...")
+ post2 = Post.create("title" => "Another post", "body" => "Posting... Again...")
+ comment = Comment.new("body" => "comment")
+
+ comment.post = post1
+ assert comment.save
+
+ assert_same(post1.comments.first, comment)
+
+ comment.post = post2
+ assert comment.save
+
+ assert_same(post2.comments.first, comment)
+ assert_equal(0, post1.comments.size)
+ end
+
+ def test_im_with_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
+ tag = posts(:welcome).tags.first
+ tag_with_joins_and_select = posts(:welcome).tags.add_joins_and_select.first
+ assert_same(tag, tag_with_joins_and_select)
+ assert_nothing_raised(NoMethodError, "Joins/select was not loaded") { tag.author_id }
+ end
+
+ ##############################################################################
+ # Tests checking Identity Map behaviour with preloaded associations, joins, #
+ # includes etc. #
+ ##############################################################################
+
+ def test_find_with_preloaded_associations
+ assert_queries(2) do
+ posts = Post.preload(:comments).order('posts.id')
+ assert posts.first.comments.first
+ end
+
+ # With IM we'll retrieve post object from previous query, it'll have comments
+ # already preloaded from first call
+ assert_queries(1) do
+ posts = Post.preload(:comments).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
+
+ # With IM we'll retrieve post object from previous query, it'll have comments
+ # already preloaded from first call
+ assert_queries(1) do
+ posts = Post.preload(:author).order('posts.id')
+ assert posts.first.author
+ end
+
+ assert_queries(1) do
+ posts = Post.preload(:author, :comments).order('posts.id')
+ assert posts.first.author
+ assert posts.first.comments.first
+ end
+ end
+
+ def test_find_with_included_associations
+ assert_queries(2) do
+ posts = Post.includes(:comments).order('posts.id')
+ assert posts.first.comments.first
+ end
+
+ assert_queries(1) do
+ posts = Post.scoped.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(1) do
+ posts = Post.includes(:author, :comments).order('posts.id')
+ assert posts.first.author
+ assert posts.first.comments.first
+ end
+ end
+
+ def test_eager_loading_with_conditions_on_joined_table_preloads
+ posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_same posts.first.author, Author.first
+
+ posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_same posts.first.author, Author.first
+
+ posts = Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id')
+ assert_equal posts(:welcome, :thinking), posts
+ assert_same posts.first.author, Author.first
+
+ posts = Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id')
+ assert_equal posts(:welcome, :thinking), posts
+ assert_same posts.first.author, Author.first
+ end
+
+ def test_eager_loading_with_conditions_on_string_joined_table_preloads
+ posts = assert_queries(2) do
+ Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+
+ posts = assert_queries(1) do
+ Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+ end
+
+ ##############################################################################
+ # Behaviour related to saving failures
+ ##############################################################################
+
+ def test_reload_object_if_save_failed
+ developer = Developer.first
+ developer.salary = 0
+
+ assert !developer.save
+
+ same_developer = Developer.first
+
+ assert_not_same developer, same_developer
+ assert_not_equal 0, same_developer.salary
+ assert_not_equal developer.salary, same_developer.salary
+ end
+
+ def test_reload_object_if_forced_save_failed
+ developer = Developer.first
+ developer.salary = 0
+
+ assert_raise(ActiveRecord::RecordInvalid) { developer.save! }
+
+ same_developer = Developer.first
+
+ assert_not_same developer, same_developer
+ assert_not_equal 0, same_developer.salary
+ assert_not_equal developer.salary, same_developer.salary
+ end
+
+ def test_reload_object_if_update_attributes_fails
+ developer = Developer.first
+ developer.salary = 0
+
+ assert !developer.update_attributes(:salary => 0)
+
+ same_developer = Developer.first
+
+ assert_not_same developer, same_developer
+ assert_not_equal 0, same_developer.salary
+ assert_not_equal developer.salary, same_developer.salary
+ end
+
+ ##############################################################################
+ # Behaviour of readonly, frozen, destroyed
+ ##############################################################################
+
+ def test_find_using_identity_map_respects_readonly_when_loading_associated_object_first
+ author = Author.first
+ readonly_comment = author.readonly_comments.first
+
+ comment = Comment.first
+ assert !comment.readonly?
+
+ assert readonly_comment.readonly?
+
+ assert_raise(ActiveRecord::ReadOnlyRecord) {readonly_comment.save}
+ assert comment.save
+ end
+
+ def test_find_using_identity_map_respects_readonly
+ comment = Comment.first
+ assert !comment.readonly?
+
+ author = Author.first
+ readonly_comment = author.readonly_comments.first
+
+ assert readonly_comment.readonly?
+
+ assert_raise(ActiveRecord::ReadOnlyRecord) {readonly_comment.save}
+ assert comment.save
+ end
+
+ def test_find_using_select_and_identity_map
+ author_id, author = Author.select('id').first, Author.first
+
+ assert_equal author_id, author
+ assert_same author_id, author
+ assert_not_nil author.name
+
+ post, post_id = Post.first, Post.select('id').first
+
+ assert_equal post_id, post
+ assert_same post_id, post
+ assert_not_nil post.title
+ end
+
+# Currently AR is not allowing changing primary key (see Persistence#update)
+# So we ignore it. If this changes, this test needs to be uncommented.
+# def test_updating_of_pkey
+# assert client = Client.find(3),
+# client.update_attribute(:id, 666)
+#
+# assert Client.find(666)
+# assert_same(client, Client.find(666))
+#
+# s = Subscriber.find_by_nick('swistak')
+# assert s.update_attribute(:nick, 'swistakTheJester')
+# assert_equal('swistakTheJester', s.nick)
+#
+# assert stj = Subscriber.find_by_nick('swistakTheJester')
+# assert_same(s, stj)
+# end
+
+end
+end
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index 8c09fc4d59..b5d8314541 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -14,6 +14,20 @@ class InheritanceTest < ActiveRecord::TestCase
ActiveRecord::Base.store_full_sti_class = old
end
+ def test_class_with_blank_sti_name
+ company = Company.find(:first)
+ company = company.dup
+ company.extend(Module.new {
+ def read_attribute(name)
+ return ' ' if name == 'type'
+ super
+ end
+ })
+ company.save!
+ company = Company.find(:all).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
@@ -189,12 +203,12 @@ class InheritanceTest < ActiveRecord::TestCase
def test_eager_load_belongs_to_something_inherited
account = Account.find(1, :include => :firm)
- assert_not_nil account.instance_variable_get("@firm"), "nil proves eager load failed"
+ assert account.association_cache.key?(:firm), "nil proves eager load failed"
end
def test_eager_load_belongs_to_primary_key_quoting
con = Account.connection
- assert_sql(/\(#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} = 1\)/) do
+ assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} IN \(1\)/) do
Account.find(1, :include => :firm)
end
end
@@ -205,6 +219,10 @@ class InheritanceTest < ActiveRecord::TestCase
switch_to_default_inheritance_column
end
+ def test_inherits_custom_primary_key
+ assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key
+ end
+
def test_inheritance_without_mapping
assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save }
diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb
new file mode 100644
index 0000000000..afec64750e
--- /dev/null
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -0,0 +1,57 @@
+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 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
+
+ def teardown
+ if ActiveRecord::Base.connection.table_exists?("horses")
+ ActiveRecord::Base.connection.drop_table("horses")
+ end
+ end
+
+ def test_no_reverse
+ migration = NonInvertibleMigration.new
+ migration.migrate(:up)
+ assert_raises(IrreversibleMigration) do
+ migration.migrate(:down)
+ end
+ end
+
+ def test_up
+ migration = InvertibleMigration.new
+ migration.migrate(:up)
+ assert migration.connection.table_exists?("horses"), "horses should exist"
+ end
+
+ def test_down
+ migration = InvertibleMigration.new
+ migration.migrate :up
+ migration.migrate :down
+ assert !migration.connection.table_exists?("horses")
+ end
+ end
+end
diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb
index 2bc746c0b8..8664d63e8f 100644
--- a/activerecord/test/cases/json_serialization_test.rb
+++ b/activerecord/test/cases/json_serialization_test.rb
@@ -82,6 +82,13 @@ class JsonSerializationTest < ActiveRecord::TestCase
assert_match %r{"label":"Has cheezburger"}, methods_json
assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_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
@@ -174,7 +181,11 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase
def test_should_allow_except_option_for_list_of_authors
ActiveRecord::Base.include_root_in_json = false
authors = [@david, @mary]
- assert_equal %([{"id":1},{"id":2}]), ActiveSupport::JSON.encode(authors, :except => [:name, :author_address_id, :author_address_extra_id])
+ 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
ensure
ActiveRecord::Base.include_root_in_json = true
end
@@ -189,7 +200,7 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase
)
['"name":"David"', '"posts":[', '{"id":1}', '{"id":2}', '{"id":4}',
- '{"id":5}', '{"id":6}', '"name":"Mary"', '"posts":[{"id":7}]'].each do |fragment|
+ '{"id":5}', '{"id":6}', '"name":"Mary"', '"posts":[', '{"id":7}', '{"id":9}'].each do |fragment|
assert json.include?(fragment), json
end
end
@@ -204,7 +215,7 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase
def test_should_be_able_to_encode_relation
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
diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb
index 233338498f..6cd8494c9e 100644
--- a/activerecord/test/cases/lifecycle_test.rb
+++ b/activerecord/test/cases/lifecycle_test.rb
@@ -7,12 +7,31 @@ require 'models/comment'
class SpecialDeveloper < Developer; end
+class DeveloperObserver < ActiveRecord::Observer
+ def calls
+ @calls ||= []
+ end
+
+ def before_save(developer)
+ calls << developer
+ end
+end
+
class SalaryChecker < ActiveRecord::Observer
observe :special_developer
+ attr_accessor :last_saved
def before_save(developer)
return developer.salary > 80000
end
+
+ module Implementation
+ def after_save(developer)
+ self.last_saved = developer
+ end
+ end
+ include Implementation
+
end
class TopicaAuditor < ActiveRecord::Observer
@@ -92,9 +111,10 @@ class LifecycleTest < ActiveRecord::TestCase
fixtures :topics, :developers, :minimalistics
def test_before_destroy
- original_count = Topic.count
- (topic_to_be_destroyed = Topic.find(1)).destroy
- assert_equal original_count - (1 + topic_to_be_destroyed.replies.size), Topic.count
+ topic = Topic.find(1)
+ assert_difference 'Topic.count', -(1 + topic.replies.size) do
+ topic.destroy
+ end
end
def test_auto_observer
@@ -179,4 +199,21 @@ class LifecycleTest < ActiveRecord::TestCase
developer = SpecialDeveloper.new :name => 'Rookie', :salary => 50000
assert !developer.save, "allowed to save a developer with too low salary"
end
+
+ test "able to call methods defined with included module" do # https://rails.lighthouseapp.com/projects/8994/tickets/6065-activerecordobserver-is-not-aware-of-method-added-by-including-modules
+ SalaryChecker.instance # activate
+ developer = SpecialDeveloper.create! :name => 'Roger', :salary => 100000
+ assert_equal developer, SalaryChecker.instance.last_saved
+ end
+
+ def test_observer_is_called_once
+ observer = DeveloperObserver.instance # activate
+ observer.calls.clear
+
+ developer = Developer.create! :name => 'Ancestor', :salary => 100000
+ special_developer = SpecialDeveloper.create! :name => 'Descendent', :salary => 100000
+
+ assert_equal [developer, special_developer], observer.calls
+ end
+
end
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index e7126964cd..636a709924 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -1,5 +1,7 @@
+require 'thread'
require "cases/helper"
require 'models/person'
+require 'models/job'
require 'models/reader'
require 'models/legacy_thing'
require 'models/reference'
@@ -18,11 +20,6 @@ end
class OptimisticLockingTest < ActiveRecord::TestCase
fixtures :people, :legacy_things, :references
- # need to disable transactional fixtures, because otherwise the sqlite3
- # adapter (at least) chokes when we try and change the schema in the middle
- # of a test (see test_increment_counter_*).
- self.use_transactional_fixtures = false
-
def test_lock_existing
p1 = Person.find(1)
p2 = Person.find(1)
@@ -102,6 +99,14 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_equal 1, p1.lock_version
end
+ def test_touch_existing_lock
+ p1 = Person.find(1)
+ assert_equal 0, p1.lock_version
+
+ p1.touch
+ assert_equal 1, p1.lock_version
+ end
+
def test_lock_column_name_existing
t1 = LegacyThing.find(1)
@@ -151,6 +156,33 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_equal "unchangeable name", p.first_name
end
+ def test_quote_table_name
+ ref = references(:michael_magician)
+ ref.favourite = !ref.favourite
+ assert ref.save
+ end
+
+ # Useful for partial updates, don't only update the lock_version if there
+ # is nothing else being updated.
+ def test_update_without_attributes_does_not_only_update_lock_version
+ assert_nothing_raised do
+ p1 = Person.create!(:first_name => 'anika')
+ lock_version = p1.lock_version
+ p1.save
+ p1.reload
+ assert_equal lock_version, p1.lock_version
+ end
+ end
+end
+
+class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
+ fixtures :people, :legacy_things, :references
+
+ # need to disable transactional fixtures, because otherwise the sqlite3
+ # adapter (at least) chokes when we try and change the schema in the middle
+ # of a test (see test_increment_counter_*).
+ self.use_transactional_fixtures = false
+
{ :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model|
define_method("test_increment_counter_updates_#{name}") do
counter_test model, 1 do |id|
@@ -197,24 +229,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_raises(ActiveRecord::RecordNotFound) { LegacyThing.find(t.id) }
end
- def test_quote_table_name
- ref = references(:michael_magician)
- ref.favourite = !ref.favourite
- assert ref.save
- end
-
- # Useful for partial updates, don't only update the lock_version if there
- # is nothing else being updated.
- def test_update_without_attributes_does_not_only_update_lock_version
- assert_nothing_raised do
- p1 = Person.create!(:first_name => 'anika')
- lock_version = p1.lock_version
- p1.save
- p1.reload
- assert_equal lock_version, p1.lock_version
- end
- end
-
private
def add_counter_column_to(model, col='test_count')
@@ -251,12 +265,13 @@ end
# TODO: The Sybase, and OpenBase adapters currently have no support for pessimistic locking
-unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
+unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db?
class PessimisticLockingTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
fixtures :people, :readers
def setup
+ Person.connection_pool.clear_reloadable_connections!
# Avoid introspection queries during tests.
Person.columns; Reader.columns
end
@@ -306,8 +321,6 @@ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
end
if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
- use_concurrent_connections
-
def test_no_locks_no_wait
first, second = duel { Person.find 1 }
assert first.end > second.end
diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb
index 5256ab8d11..7e8383da9e 100644
--- a/activerecord/test/cases/method_scoping_test.rb
+++ b/activerecord/test/cases/method_scoping_test.rb
@@ -14,7 +14,7 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_set_conditions
Developer.send(:with_scope, :find => { :conditions => 'just a test...' }) do
- assert_equal '(just a test...)', Developer.scoped.arel.send(:where_clauses).join(' AND ')
+ assert_match '(just a test...)', Developer.scoped.arel.to_sql
end
end
@@ -219,13 +219,19 @@ class MethodScopingTest < ActiveRecord::TestCase
new_comment = nil
VerySpecialComment.send(:with_scope, :create => { :post_id => 1 }) do
- assert_equal({:post_id => 1}, VerySpecialComment.scoped.send(:scope_for_create))
+ assert_equal({:post_id => 1, :type => 'VerySpecialComment' }, VerySpecialComment.scoped.send(:scope_for_create))
new_comment = VerySpecialComment.create :body => "Wonderful world"
end
assert Post.find(1).comments.include?(new_comment)
end
+ def test_scoped_create_with_join_and_merge
+ Comment.where(:body => "but Who's Buying?").joins(:post).merge(Post.where(:body => 'Peace Sells...')).with_scope do
+ assert_equal({:body => "but Who's Buying?"}, Comment.scoped.scope_for_create)
+ end
+ end
+
def test_immutable_scope
options = { :conditions => "name = 'David'" }
Developer.send(:with_scope, :find => options) do
@@ -269,7 +275,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do
Developer.send(:with_scope, :find => { :limit => 10 }) do
devs = Developer.scoped
- assert_equal '(salary = 80000)', devs.arel.send(:where_clauses).join(' AND ')
+ assert_match '(salary = 80000)', devs.arel.to_sql
assert_equal 10, devs.taken
end
end
@@ -303,7 +309,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do
devs = Developer.scoped
- assert_equal "(name = 'David') AND (salary = 80000)", devs.arel.send(:where_clauses).join(' AND ')
+ assert_match "(name = 'David') AND (salary = 80000)", devs.arel.to_sql
assert_equal(1, Developer.count)
end
Developer.send(:with_scope, :find => { :conditions => "name = 'Maiha'" }) do
@@ -316,7 +322,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Developer.send(:with_scope, :find => { :conditions => 'salary = 80000', :limit => 10 }) do
Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
devs = Developer.scoped
- assert_equal "(salary = 80000) AND (name = 'David')", devs.arel.send(:where_clauses).join(' AND ')
+ assert_match "(salary = 80000) AND (name = 'David')", devs.arel.to_sql
assert_equal 10, devs.taken
end
end
@@ -400,7 +406,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Developer.send(:with_scope, :find => { :conditions => "salary < 100000" }) do
Developer.send(:with_scope, :find => { :offset => 1, :order => 'id asc' }) do
# Oracle adapter does not generated space after asc therefore trailing space removed from regex
- assert_sql(/ORDER BY id asc/) do
+ assert_sql(/ORDER BY\s+id asc/) do
assert_equal(poor_jamis, Developer.find(:first, :order => 'id asc'))
end
end
@@ -449,7 +455,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Comment.send(:with_scope, :create => { :body => "Hey guys, nested scopes are broken. Please fix!" }) do
Comment.send(:with_exclusive_scope, :create => { :post_id => 1 }) do
assert_equal({:post_id => 1}, Comment.scoped.send(:scope_for_create))
- assert Comment.new.body.blank?
+ assert_blank Comment.new.body
comment = Comment.create :body => "Hey guys"
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 0000000000..ae531ebb4c
--- /dev/null
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -0,0 +1,108 @@
+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]]], recorder.commands
+ end
+
+ def test_unknown_commands_raise_exception
+ @recorder.record :execute, ['some sql']
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ @recorder.inverse
+ end
+ end
+
+ def test_record
+ @recorder.record :create_table, [:system_settings]
+ assert_equal 1, @recorder.commands.length
+ end
+
+ def test_inverse
+ @recorder.record :create_table, [:system_settings]
+ assert_equal 1, @recorder.inverse.length
+
+ @recorder.record :rename_table, [:old, :new]
+ assert_equal 2, @recorder.inverse.length
+ end
+
+ def test_inverted_commands_are_reveresed
+ @recorder.record :create_table, [:hello]
+ @recorder.record :create_table, [:world]
+ tables = @recorder.inverse.map(&:last)
+ assert_equal [[:world], [:hello]], tables
+ end
+
+ def test_invert_create_table
+ @recorder.record :create_table, [:system_settings]
+ drop_table = @recorder.inverse.first
+ assert_equal [:drop_table, [:system_settings]], drop_table
+ end
+
+ def test_invert_rename_table
+ @recorder.record :rename_table, [:old, :new]
+ rename = @recorder.inverse.first
+ assert_equal [:rename_table, [:new, :old]], rename
+ end
+
+ def test_invert_add_column
+ @recorder.record :add_column, [:table, :column, :type, {}]
+ remove = @recorder.inverse.first
+ assert_equal [:remove_column, [:table, :column]], remove
+ end
+
+ def test_invert_rename_column
+ @recorder.record :rename_column, [:table, :old, :new]
+ rename = @recorder.inverse.first
+ assert_equal [:rename_column, [:table, :new, :old]], rename
+ end
+
+ def test_invert_add_index
+ @recorder.record :add_index, [:table, [:one, :two], {:options => true}]
+ remove = @recorder.inverse.first
+ assert_equal [:remove_index, [:table, {:column => [:one, :two]}]], remove
+ end
+
+ def test_invert_rename_index
+ @recorder.record :rename_index, [:old, :new]
+ rename = @recorder.inverse.first
+ assert_equal [:rename_index, [:new, :old]], rename
+ end
+
+ def test_invert_add_timestamps
+ @recorder.record :add_timestamps, [:table]
+ remove = @recorder.inverse.first
+ assert_equal [:remove_timestamps, [:table]], remove
+ end
+
+ def test_invert_remove_timestamps
+ @recorder.record :remove_timestamps, [:table]
+ add = @recorder.inverse.first
+ assert_equal [:add_timestamps, [:table]], add
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 0cf3979694..bf7565a0d0 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -5,10 +5,8 @@ require 'models/person'
require 'models/topic'
require 'models/developer'
-require MIGRATIONS_ROOT + "/valid/1_people_have_last_names"
require MIGRATIONS_ROOT + "/valid/2_we_need_reminders"
require MIGRATIONS_ROOT + "/decimal/1_give_me_big_numbers"
-require MIGRATIONS_ROOT + "/interleaved/pass_3/2_i_raise_on_down"
if ActiveRecord::Base.connection.supports_migrations?
class BigNumber < ActiveRecord::Base; end
@@ -16,12 +14,13 @@ if ActiveRecord::Base.connection.supports_migrations?
class Reminder < ActiveRecord::Base; end
class ActiveRecord::Migration
- class <<self
+ class << self
attr_accessor :message_count
- def puts(text="")
- self.message_count ||= 0
- self.message_count += 1
- end
+ end
+
+ def puts(text="")
+ ActiveRecord::Migration.message_count ||= 0
+ ActiveRecord::Migration.message_count += 1
end
end
@@ -51,7 +50,7 @@ if ActiveRecord::Base.connection.supports_migrations?
def setup
ActiveRecord::Migration.verbose = true
- PeopleHaveLastNames.message_count = 0
+ ActiveRecord::Migration.message_count = 0
end
def teardown
@@ -91,7 +90,7 @@ if ActiveRecord::Base.connection.supports_migrations?
# Oracle adapter is shortening index name when just column list is given
unless current_adapter?(:OracleAdapter)
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
- assert_nothing_raised { Person.connection.remove_index("people", :name => "index_people_on_last_name_and_first_name") }
+ assert_nothing_raised { Person.connection.remove_index("people", :name => :index_people_on_last_name_and_first_name) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", "last_name_and_first_name") }
end
@@ -124,19 +123,27 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
+ def test_index_symbol_names
+ assert_nothing_raised { Person.connection.add_index :people, :primary_contact_id, :name => :symbol_index_name }
+ assert Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name)
+ assert_nothing_raised { Person.connection.remove_index :people, :name => :symbol_index_name }
+ assert !Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name)
+ end
+
def test_add_index_length_limit
good_index_name = 'x' * Person.connection.index_name_length
too_long_index_name = good_index_name + 'x'
- assert_nothing_raised { Person.connection.add_index("people", "first_name", :name => too_long_index_name) }
+ assert_raise(ArgumentError) { Person.connection.add_index("people", "first_name", :name => too_long_index_name) }
assert !Person.connection.index_name_exists?("people", too_long_index_name, false)
assert_nothing_raised { Person.connection.add_index("people", "first_name", :name => good_index_name) }
assert Person.connection.index_name_exists?("people", good_index_name, false)
+ Person.connection.remove_index("people", :name => good_index_name)
end
def test_remove_nonexistent_index
# we do this by name, so OpenBase is a wash as noted above
unless current_adapter?(:OpenBaseAdapter)
- assert_nothing_raised { Person.connection.remove_index("people", "no_such_index") }
+ assert_raise(ArgumentError) { Person.connection.remove_index("people", "no_such_index") }
end
end
@@ -154,7 +161,7 @@ if ActiveRecord::Base.connection.supports_migrations?
def test_double_add_index
unless current_adapter?(:OpenBaseAdapter)
Person.connection.add_index('people', [:first_name], :name => 'some_idx')
- assert_nothing_raised { Person.connection.add_index('people', [:first_name], :name => 'some_idx') }
+ assert_raise(ArgumentError) { Person.connection.add_index('people', [:first_name], :name => 'some_idx') }
end
end
@@ -414,7 +421,7 @@ if ActiveRecord::Base.connection.supports_migrations?
# Sybase, and SQLite3 will not allow you to add a NOT NULL
# column to a table without a default value.
- unless current_adapter?(:SybaseAdapter, :SQLiteAdapter)
+ unless current_adapter?(:SybaseAdapter, :SQLite3Adapter)
def test_add_column_not_null_without_default
Person.connection.create_table :testings do |t|
t.column :foo, :string
@@ -536,7 +543,7 @@ if ActiveRecord::Base.connection.supports_migrations?
assert_equal "I was born ....", bob.bio
assert_equal 18, bob.age
- # Test for 30 significent digits (beyond the 16 of float), 10 of them
+ # Test for 30 significant digits (beyond the 16 of float), 10 of them
# after the decimal place.
unless current_adapter?(:SQLite3Adapter)
@@ -566,6 +573,7 @@ if ActiveRecord::Base.connection.supports_migrations?
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
@@ -806,10 +814,13 @@ if ActiveRecord::Base.connection.supports_migrations?
Topic.connection.change_column "topics", "written_on", :datetime, :null => false
Topic.reset_column_information
+
+ Topic.connection.change_column "topics", "written_on", :datetime, :null => true
+ Topic.reset_column_information
end
end
- if current_adapter?(:SQLiteAdapter)
+ if current_adapter?(:SQLite3Adapter)
def test_rename_table_for_sqlite_should_work_with_reserved_words
begin
assert_nothing_raised do
@@ -1119,7 +1130,7 @@ if ActiveRecord::Base.connection.supports_migrations?
# 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?(:SQLiteAdapter)
+ 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
@@ -1153,6 +1164,44 @@ if ActiveRecord::Base.connection.supports_migrations?
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(: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
assert !Person.column_methods_hash.include?(:last_name)
assert !Reminder.table_exists?
@@ -1220,51 +1269,56 @@ if ActiveRecord::Base.connection.supports_migrations?
def test_finds_migrations
migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid").migrations
- [[1, 'PeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i|
+ [[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.new(:up, directories).migrations
+
+ [[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_pending_migrations
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2", 1)
migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/interleaved/pass_2").pending_migrations
assert_equal 1, migrations.size
assert_equal migrations[0].version, 3
- assert_equal migrations[0].name, 'InnocentJointable'
+ assert_equal migrations[0].name, 'InterleavedInnocentJointable'
end
def test_relative_migrations
- $".delete_if do |fname|
- fname == (MIGRATIONS_ROOT + "/valid/1_people_have_last_names.rb")
- end
- Object.send(:remove_const, :PeopleHaveLastNames)
-
- Dir.chdir(MIGRATIONS_ROOT) do
+ list = Dir.chdir(MIGRATIONS_ROOT) do
ActiveRecord::Migrator.up("valid/", 1)
end
- assert defined?(PeopleHaveLastNames)
+ migration_proxy = list.find { |item|
+ item.name == 'ValidPeopleHaveLastNames'
+ }
+ assert migration_proxy, 'should find pending migration'
end
def test_only_loads_pending_migrations
# migrate up to 1
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
- # now unload the migrations that have been defined
- Object.send(:remove_const, :PeopleHaveLastNames)
-
- ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", nil)
+ proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", nil)
- assert !defined? PeopleHaveLastNames
-
- %w(WeNeedReminders, InnocentJointable).each do |migration|
- assert defined? migration
- end
-
- ensure
- load(MIGRATIONS_ROOT + "/valid/1_people_have_last_names.rb")
+ names = proxies.map(&:name)
+ assert !names.include?('ValidPeopleHaveLastNames')
+ assert names.include?('WeNeedReminders')
+ assert names.include?('InnocentJointable')
end
def test_target_version_zero_should_run_only_once
@@ -1274,16 +1328,9 @@ if ActiveRecord::Base.connection.supports_migrations?
# migrate down to 0
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0)
- # now unload the migrations that have been defined
- PeopleHaveLastNames.unloadable
- ActiveSupport::Dependencies.remove_unloadable_constants!
-
# migrate down to 0 again
- ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0)
-
- assert !defined? PeopleHaveLastNames
- ensure
- load(MIGRATIONS_ROOT + "/valid/1_people_have_last_names.rb")
+ proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0)
+ assert_equal [], proxies
end
def test_migrator_db_has_no_schema_migrations_table
@@ -1300,20 +1347,20 @@ if ActiveRecord::Base.connection.supports_migrations?
def test_migrator_verbosity
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
- assert PeopleHaveLastNames.message_count > 0
- PeopleHaveLastNames.message_count = 0
+ assert_not_equal 0, ActiveRecord::Migration.message_count
+ ActiveRecord::Migration.message_count = 0
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0)
- assert PeopleHaveLastNames.message_count > 0
- PeopleHaveLastNames.message_count = 0
+ assert_not_equal 0, ActiveRecord::Migration.message_count
+ ActiveRecord::Migration.message_count = 0
end
def test_migrator_verbosity_off
- PeopleHaveLastNames.verbose = false
+ ActiveRecord::Migration.verbose = false
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
- assert PeopleHaveLastNames.message_count.zero?
+ assert_equal 0, ActiveRecord::Migration.message_count
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0)
- assert PeopleHaveLastNames.message_count.zero?
+ assert_equal 0, ActiveRecord::Migration.message_count
end
def test_migrator_going_down_due_to_version_target
@@ -1358,10 +1405,10 @@ if ActiveRecord::Base.connection.supports_migrations?
ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid")
assert_equal(3, ActiveRecord::Migrator.current_version)
end
-
+
def test_get_all_versions
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid")
- assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions)
+ assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions)
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
assert_equal([1,2], ActiveRecord::Migrator.get_all_versions)
@@ -1576,13 +1623,23 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
- if current_adapter?(:PostgreSQLAdapter)
+ if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:SQLite3Adapter) || current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
def test_xml_creates_xml_column
+ type = current_adapter?(:PostgreSQLAdapter) ? 'xml' : :text
+
with_new_table do |t|
- t.expects(:column).with(:data, 'xml', {})
+ t.expects(:column).with(:data, type, {})
t.xml :data
end
end
+ else
+ def test_xml_creates_xml_column
+ with_new_table do |t|
+ assert_raises(NotImplementedError) do
+ t.xml :data
+ end
+ end
+ end
end
protected
@@ -1597,10 +1654,6 @@ if ActiveRecord::Base.connection.supports_migrations?
end # SexyMigrationsTest
class MigrationLoggerTest < ActiveRecord::TestCase
- def setup
- Object.send(:remove_const, :InnocentJointable)
- end
-
def test_migration_should_be_run_without_logger
previous_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
@@ -1613,10 +1666,6 @@ if ActiveRecord::Base.connection.supports_migrations?
end
class InterleavedMigrationsTest < ActiveRecord::TestCase
- def setup
- Object.send(:remove_const, :PeopleHaveLastNames)
- end
-
def test_migrator_interleaved_migrations
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_1")
@@ -1627,10 +1676,12 @@ if ActiveRecord::Base.connection.supports_migrations?
Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
- Object.send(:remove_const, :PeopleHaveLastNames)
- Object.send(:remove_const, :InnocentJointable)
assert_nothing_raised do
- ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/interleaved/pass_3")
+ proxies = ActiveRecord::Migrator.down(
+ MIGRATIONS_ROOT + "/interleaved/pass_3")
+ names = proxies.map(&:name)
+ assert names.include?('InterleavedPeopleHaveLastNames')
+ assert names.include?('InterleavedInnocentJointable')
end
end
end
@@ -1871,5 +1922,307 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
end
-end
+ if ActiveRecord::Base.connection.supports_bulk_alter?
+ class BulkAlterTableMigrationsTest < ActiveRecord::TestCase
+ def setup
+ @connection = Person.connection
+ @connection.create_table(:delete_me, :force => true) {|t| }
+ end
+
+ def teardown
+ Person.connection.drop_table(:delete_me) rescue nil
+ end
+
+ def test_adding_multiple_columns
+ assert_queries(1) do
+ with_bulk_change_table do |t|
+ t.column :name, :string
+ t.string :qualification, :experience
+ t.integer :age, :default => 0
+ t.date :birthdate
+ t.timestamps
+ end
+ end
+
+ assert_equal 8, columns.size
+ [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type }
+ assert_equal 0, column(:age).default
+ end
+
+ def test_removing_columns
+ with_bulk_change_table do |t|
+ t.string :qualification, :experience
+ end
+
+ [:qualification, :experience].each {|c| assert column(c) }
+
+ assert_queries(1) do
+ with_bulk_change_table do |t|
+ t.remove :qualification, :experience
+ t.string :qualification_experience
+ end
+ end
+
+ [:qualification, :experience].each {|c| assert ! column(c) }
+ assert column(:qualification_experience)
+ end
+
+ def test_adding_indexes
+ with_bulk_change_table do |t|
+ t.string :username
+ t.string :name
+ t.integer :age
+ end
+
+ # Adding an index fires a query 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) 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.rb")
+ assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb")
+ assert_equal [@migrations_path + "/4_people_have_hobbies.rb", @migrations_path + "/5_people_have_descriptions.rb"], copied.map(&:filename)
+
+ 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 = ActiveSupport::OrderedHash.new
+ 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.rb")
+ assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb")
+ assert File.exists?(@migrations_path + "/6_create_articles.rb")
+ assert File.exists?(@migrations_path + "/7_create_comments.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.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
+ expected = [@migrations_path + "/20100726101010_people_have_hobbies.rb",
+ @migrations_path + "/20100726101011_people_have_descriptions.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 = ActiveSupport::OrderedHash.new
+ 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.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
+ assert File.exists?(@migrations_path + "/20100726101012_create_articles.rb")
+ assert File.exists?(@migrations_path + "/20100726101013_create_comments.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.rb")
+ assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.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_skipping_migrations
+ @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ sources = ActiveSupport::OrderedHash.new
+ sources[:bukkits] = sources[:omg] = 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)
+ assert_equal 2, copied.length
+
+ assert_equal 2, skipped.length
+ assert_equal ["bukkits PeopleHaveHobbies", "bukkits PeopleHaveDescriptions"], skipped
+ 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.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.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.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
+ assert_equal 2, copied.length
+ end
+ ensure
+ clear
+ end
+ end
+end
diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb
index 4b635792c7..a2041af16a 100644
--- a/activerecord/test/cases/modules_test.rb
+++ b/activerecord/test/cases/modules_test.rb
@@ -13,7 +13,7 @@ class ModulesTest < ActiveRecord::TestCase
[: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
@@ -22,7 +22,7 @@ class ModulesTest < ActiveRecord::TestCase
@undefined_consts.each do |constant, value|
Object.send :const_set, constant, value unless value.nil?
end
-
+
ActiveRecord::Base.store_full_sti_class = true
end
@@ -49,7 +49,6 @@ class ModulesTest < ActiveRecord::TestCase
def test_find_account_and_include_company
account = MyApplication::Billing::Account.find(1, :include => :firm)
- assert_kind_of MyApplication::Business::Firm, account.instance_variable_get('@firm')
assert_kind_of MyApplication::Business::Firm, account.firm
end
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index c42dda2ccb..fb050c3e52 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -64,6 +64,10 @@ class NamedScopeTest < ActiveRecord::TestCase
assert Reply.scopes.include?(:base)
assert_equal Reply.find(:all), Reply.base
end
+
+ def test_classes_dont_inherit_subclasses_scopes
+ assert !ActiveRecord::Base.scopes.include?(:base)
+ end
def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
assert !Topic.find(:all, :conditions => {:approved => true}).empty?
@@ -122,7 +126,13 @@ class NamedScopeTest < ActiveRecord::TestCase
:joins => 'JOIN authors ON authors.id = posts.author_id',
:conditions => [ 'authors.author_address_id = ?', address.id ]
)
- assert_equal posts_with_authors_at_address_titles, Post.with_authors_at_address(address).find(:all, :select => 'title')
+ assert_equal posts_with_authors_at_address_titles.map(&:title), Post.with_authors_at_address(address).find(:all, :select => 'title').map(&:title)
+ 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_extensions
@@ -135,26 +145,26 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_equal 1, Topic.multiple_extensions.extension_one
end
- def test_has_many_associations_have_access_to_named_scopes
+ def test_has_many_associations_have_access_to_scopes
assert_not_equal Post.containing_the_letter_a, authors(:david).posts
assert !Post.containing_the_letter_a.empty?
assert_equal authors(:david).posts & Post.containing_the_letter_a, authors(:david).posts.containing_the_letter_a
end
- def test_named_scope_with_STI
+ def test_scope_with_STI
assert_equal 3,Post.containing_the_letter_a.count
assert_equal 1,SpecialPost.containing_the_letter_a.count
end
- def test_has_many_through_associations_have_access_to_named_scopes
+ def test_has_many_through_associations_have_access_to_scopes
assert_not_equal Comment.containing_the_letter_e, authors(:david).comments
assert !Comment.containing_the_letter_e.empty?
assert_equal authors(:david).comments & Comment.containing_the_letter_e, authors(:david).comments.containing_the_letter_e
end
- def test_named_scopes_honor_current_scopes_from_when_defined
+ def test_scopes_honor_current_scopes_from_when_defined
assert !Post.ranked_by_comments.limit_by(5).empty?
assert !authors(:david).posts.ranked_by_comments.limit_by(5).empty?
assert_not_equal Post.ranked_by_comments.limit_by(5), authors(:david).posts.ranked_by_comments.limit_by(5)
@@ -230,7 +240,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_any_should_not_fire_query_if_named_scope_loaded
+ def test_any_should_not_fire_query_if_scope_loaded
topics = Topic.base
topics.collect # force load
assert_no_queries { assert topics.any? }
@@ -253,7 +263,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_many_should_not_fire_query_if_named_scope_loaded
+ def test_many_should_not_fire_query_if_scope_loaded
topics = Topic.base
topics.collect # force load
assert_no_queries { assert topics.many? }
@@ -270,27 +280,27 @@ class NamedScopeTest < ActiveRecord::TestCase
assert Topic.base.many?
end
- def test_should_build_on_top_of_named_scope
+ def test_should_build_on_top_of_scope
topic = Topic.approved.build({})
assert topic.approved
end
- def test_should_build_new_on_top_of_named_scope
+ def test_should_build_new_on_top_of_scope
topic = Topic.approved.new
assert topic.approved
end
- def test_should_create_on_top_of_named_scope
+ def test_should_create_on_top_of_scope
topic = Topic.approved.create({})
assert topic.approved
end
- def test_should_create_with_bang_on_top_of_named_scope
+ def test_should_create_with_bang_on_top_of_scope
topic = Topic.approved.create!({})
assert topic.approved
end
- def test_should_build_on_top_of_chained_named_scopes
+ def test_should_build_on_top_of_chained_scopes
topic = Topic.approved.by_lifo.build({})
assert topic.approved
assert_equal 'lifo', topic.author_name
@@ -304,7 +314,7 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_kind_of Topic, Topic.approved.sample
end
- def test_should_use_where_in_query_for_named_scope
+ def test_should_use_where_in_query_for_scope
assert_equal Developer.find_all_by_name('Jamis').to_set, Developer.find_all_by_id(Developer.jamises).to_set
end
@@ -355,7 +365,7 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).all.uniq
end
- def test_named_scopes_batch_finders
+ def test_scopes_batch_finders
assert_equal 3, Topic.approved.count
assert_queries(4) do
@@ -375,7 +385,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_named_scopes_with_reserved_names
+ def test_scopes_with_reserved_names
class << Topic
def public_method; end
public :public_method
@@ -394,11 +404,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_deprecated_named_scope_method
- assert_deprecated('named_scope has been deprecated') { Topic.named_scope :deprecated_named_scope }
- end
-
- def test_named_scopes_on_relations
+ def test_scopes_on_relations
# Topic.replied
approved_topics = Topic.scoped.approved.order('id DESC')
assert_equal topics(:fourth), approved_topics.first
@@ -407,19 +413,19 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_equal topics(:third), replied_approved_topics.first
end
- def test_index_on_named_scope
+ def test_index_on_scope
approved = Topic.approved.order('id ASC')
assert_equal topics(:second), approved[0]
assert approved.loaded?
end
- def test_nested_named_scopes_queries_size
+ def test_nested_scopes_queries_size
assert_queries(1) do
Topic.approved.by_lifo.replied.written_before(Time.now).all
end
end
- def test_named_scopes_are_cached_on_associations
+ def test_scopes_are_cached_on_associations
post = posts(:welcome)
assert_equal post.comments.containing_the_letter_e.object_id, post.comments.containing_the_letter_e.object_id
@@ -428,7 +434,7 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_no_queries { post.comments.containing_the_letter_e.all }
end
- def test_named_scopes_with_arguments_are_cached_on_associations
+ def test_scopes_with_arguments_are_cached_on_associations
post = posts(:welcome)
one = post.comments.limit_by(1).all
@@ -441,17 +447,17 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_no_queries { post.comments.limit_by(2).all }
end
- def test_named_scopes_are_reset_on_association_reload
+ def test_scopes_are_reset_on_association_reload
post = posts(:welcome)
[:destroy_all, :reset, :delete_all].each do |method|
before = post.comments.containing_the_letter_e
- post.comments.send(method)
+ post.association(:comments).send(method)
assert before.object_id != post.comments.containing_the_letter_e.object_id, "AssociationCollection##{method} should reset the named scopes cache"
end
end
- def test_named_scoped_are_lazy_loaded_if_table_still_does_not_exist
+ def test_scoped_are_lazy_loaded_if_table_still_does_not_exist
assert_nothing_raised do
require "models/without_table"
end
@@ -480,8 +486,8 @@ class DynamicScopeTest < ActiveRecord::TestCase
end
def test_dynamic_scope_should_create_methods_after_hitting_method_missing
- assert Developer.methods.grep(/scoped_by_created_at/).blank?
+ assert_blank Developer.methods.grep(/scoped_by_created_at/)
Developer.scoped_by_created_at(nil)
- assert Developer.methods.grep(/scoped_by_created_at/).present?
+ assert_present Developer.methods.grep(/scoped_by_created_at/)
end
end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index df09bbd46a..c57ab7ed28 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -39,7 +39,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
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
@@ -74,9 +74,9 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
ship = pirate.create_ship(:name => 'Nights Dirty Lightning')
- assert_no_difference('Ship.count') do
- pirate.update_attributes(:ship_attributes => { '_destroy' => true, :id => ship.id })
- end
+ pirate.update_attributes(: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
@@ -114,6 +114,48 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
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_attributes({: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_attributes({:interests_attributes => { :topic => 'gardening', :id => interest.id } })
+ assert_equal 'photography', interest.reload.topic
+ 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_attributes({: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 => 'gardning'
+ man = Man.find man.id
+ man.interests_attributes = [{:id => interest.id, :topic => 'gardening'}]
+ assert_equal man.interests.first.topic, man.interests[0].topic
+ end
end
class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@@ -138,7 +180,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@ship.destroy
@pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
- assert @pirate.ship.new_record?
+ assert !@pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
@@ -159,7 +201,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_replace_an_existing_record_if_there_is_no_id
@pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
- assert @pirate.ship.new_record?
+ assert !@pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
assert_equal 'Nights Dirty Lightning', @ship.name
end
@@ -178,6 +220,12 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
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' }
@@ -194,28 +242,30 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
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|
- @pirate.reload.create_ship(:name => 'Mister Pablo')
- assert_difference('Ship.count', -1) do
- @pirate.update_attributes(:ship_attributes => { :id => @pirate.ship.id, :_destroy => truth })
- end
+ ship = @pirate.reload.create_ship(:name => 'Mister Pablo')
+ @pirate.update_attributes(: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|
- assert_no_difference('Ship.count') do
- @pirate.update_attributes(:ship_attributes => { :id => @pirate.ship.id, :_destroy => not_truth })
- end
+ @pirate.update_attributes(: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? }
- assert_no_difference('Ship.count') do
- @pirate.update_attributes(:ship_attributes => { :id => @pirate.ship.id, :_destroy => '1' })
- end
+ @pirate.update_attributes(: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
@@ -223,7 +273,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_also_work_with_a_HashWithIndifferentAccess
@pirate.ship_attributes = HashWithIndifferentAccess.new(:id => @ship.id, :name => 'Davy Jones Gold Dagger')
- assert !@pirate.ship.new_record?
+ assert @pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
@@ -236,12 +286,15 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
end
def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
- assert_no_difference('Ship.count') do
- @pirate.attributes = { :ship_attributes => { :id => @ship.id, :_destroy => '1' } }
- end
- assert_difference('Ship.count', -1) do
- @pirate.save
- end
+ @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
@@ -254,29 +307,30 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true
@ship.delete
- assert_difference('Ship.count', 1) do
- @pirate.reload.update_attributes(:update_only_ship_attributes => { :name => 'Mayflower' })
- end
+
+ @pirate.reload.update_attributes(: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')
- assert_no_difference('Ship.count') do
- @pirate.update_attributes(:update_only_ship_attributes => { :name => 'Mayflower' })
- end
+ @pirate.update_attributes(: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')
- assert_no_difference('Ship.count') do
- @pirate.update_attributes(:update_only_ship_attributes => { :name => 'Mayflower', :id => @ship.id })
- end
+ @pirate.update_attributes(: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
@@ -284,9 +338,11 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@ship.delete
@ship = @pirate.create_update_only_ship(:name => 'Nights Dirty Lightning')
- assert_difference('Ship.count', -1) do
- @pirate.update_attributes(:update_only_ship_attributes => { :name => 'Mayflower', :id => @ship.id, :_destroy => true })
- end
+ @pirate.update_attributes(: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
@@ -309,7 +365,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
@pirate.destroy
@ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
- assert @ship.pirate.new_record?
+ assert !@ship.pirate.persisted?
assert_equal 'Arr', @ship.pirate.catchphrase
end
@@ -330,7 +386,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_replace_an_existing_record_if_there_is_no_id
@ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
- assert @ship.pirate.new_record?
+ assert !@ship.pirate.persisted?
assert_equal 'Arr', @ship.pirate.catchphrase
assert_equal 'Aye', @pirate.catchphrase
end
@@ -349,14 +405,11 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
assert_equal 'Arr', @ship.pirate.catchphrase
end
- def test_should_associate_with_record_if_parent_record_is_not_saved
- @ship.destroy
- @pirate = Pirate.create(:catchphrase => 'Arr')
- @ship = Ship.new(:name => 'Nights Dirty Lightning', :pirate_attributes => { :id => @pirate.id, :catchphrase => @pirate.catchphrase})
-
- assert_equal @ship.name, 'Nights Dirty Lightning'
- assert_equal @pirate, @ship.pirate
- 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' }
@@ -375,27 +428,24 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
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|
- @ship.reload.create_pirate(:catchphrase => 'Arr')
- assert_difference('Pirate.count', -1) do
- @ship.update_attributes(:pirate_attributes => { :id => @ship.pirate.id, :_destroy => truth })
- end
+ pirate = @ship.reload.create_pirate(:catchphrase => 'Arr')
+ @ship.update_attributes(:pirate_attributes => { :id => pirate.id, :_destroy => truth })
+ assert_raise(ActiveRecord::RecordNotFound) { pirate.reload }
end
end
def test_should_not_destroy_an_existing_record_if_destroy_is_not_truthy
[nil, '0', 0, 'false', false].each do |not_truth|
- assert_no_difference('Pirate.count') do
- @ship.update_attributes(:pirate_attributes => { :id => @ship.pirate.id, :_destroy => not_truth })
- end
+ @ship.update_attributes(: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? }
- assert_no_difference('Pirate.count') do
- @ship.update_attributes(:pirate_attributes => { :id => @ship.pirate.id, :_destroy => '1' })
- end
+ @ship.update_attributes(:pirate_attributes => { :id => @ship.pirate.id, :_destroy => '1' })
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { @ship.pirate.reload }
Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
end
@@ -409,10 +459,12 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
end
def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
- assert_no_difference('Pirate.count') do
- @ship.attributes = { :pirate_attributes => { :id => @ship.pirate.id, '_destroy' => true } }
- end
- assert_difference('Pirate.count', -1) { @ship.save }
+ 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
@@ -421,29 +473,28 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true
@pirate.delete
- assert_difference('Pirate.count', 1) do
- @ship.reload.update_attributes(:update_only_pirate_attributes => { :catchphrase => 'Arr' })
- end
+ @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')
- assert_no_difference('Pirate.count') do
- @ship.update_attributes(:update_only_pirate_attributes => { :catchphrase => 'Arr' })
- end
+ @ship.update_attributes(: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')
- assert_no_difference('Pirate.count') do
- @ship.update_attributes(:update_only_pirate_attributes => { :catchphrase => 'Arr', :id => @pirate.id })
- end
+ @ship.update_attributes(: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
@@ -451,9 +502,10 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
@pirate.delete
@pirate = @ship.create_update_only_pirate(:catchphrase => 'Aye')
- assert_difference('Pirate.count', -1) do
- @ship.update_attributes(:update_only_pirate_attributes => { :catchphrase => 'Arr', :id => @pirate.id, :_destroy => true })
- end
+ @ship.update_attributes(: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
@@ -486,11 +538,6 @@ module NestedAttributesOnACollectionAssociationTests
assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.reload.name, @child_2.reload.name]
end
- def test_should_assign_existing_children_if_parent_is_new
- @pirate = Pirate.new({:catchphrase => "Don' botharr talkin' like one, savvy?"}.merge(@alternate_params))
- assert_equal ['Grace OMalley', 'Privateers Greed'], [@pirate.send(@association_name)[0].name, @pirate.send(@association_name)[1].name]
- end
-
def test_should_also_work_with_a_HashWithIndifferentAccess
@pirate.send(association_setter, HashWithIndifferentAccess.new('foo' => HashWithIndifferentAccess.new(:id => @child_1.id, :name => 'Grace OMalley')))
@pirate.save
@@ -554,8 +601,8 @@ module NestedAttributesOnACollectionAssociationTests
assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.name, @child_2.name]
end
- def test_should_not_raise_RecordNotFound_if_an_id_is_given_but_doesnt_return_a_record
- assert_nothing_raised ActiveRecord::RecordNotFound do
+ 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
@@ -566,10 +613,10 @@ module NestedAttributesOnACollectionAssociationTests
association_getter => { 'foo' => { :name => 'Grace OMalley' }, 'bar' => { :name => 'Privateers Greed' }}
}
- assert @pirate.send(@association_name).first.new_record?
+ assert !@pirate.send(@association_name).first.persisted?
assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
- assert @pirate.send(@association_name).last.new_record?
+ assert !@pirate.send(@association_name).last.persisted?
assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
end
@@ -789,7 +836,7 @@ class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase
fixtures :owners, :pets
def setup
- Owner.accepts_nested_attributes_for :pets
+ Owner.accepts_nested_attributes_for :pets, :allow_destroy => true
@owner = owners(:ashley)
@pet1, @pet2 = pets(:chew), pets(:mochi)
@@ -806,10 +853,22 @@ class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase
@owner.update_attributes(@params)
assert_equal ['Foo', 'Bar'], @owner.pets.map(&:name)
end
+
+ def test_attr_accessor_of_child_should_be_value_provided_during_update_attributes
+ @owner = owners(:ashley)
+ @pet1 = pets(:chew)
+ attributes = {:pets_attributes => { "1"=> { :id => @pet1.id,
+ :name => "Foo2",
+ :current_user => "John",
+ :_destroy=>true }}}
+ @owner.update_attributes(attributes)
+ assert_equal 'John', Pet.after_destroy_output
+ end
+
end
class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create!(:catchphrase => "My baby takes tha mornin' train!")
@@ -817,29 +876,29 @@ class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRe
@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")
@@ -849,7 +908,7 @@ class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRe
end
class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@ship = Ship.create!(:name => "The good ship Dollypop")
@@ -859,16 +918,16 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR
test "if association is not loaded and association record is saved and then in memory record attributes should be saved" do
@ship.parts_attributes=[{:id => @part.id,:name =>'Deck'}]
- assert_equal 1, @ship.parts.proxy_target.size
+ assert_equal 1, @ship.association(:parts).target.size
assert_equal 'Deck', @ship.parts[0].name
end
test "if association is not loaded and child doesn't change and I am saving a grandchild then in memory record should be used" do
@ship.parts_attributes=[{:id => @part.id,:trinkets_attributes =>[{:id => @trinket.id, :name => 'Ruby'}]}]
- assert_equal 1, @ship.parts.proxy_target.size
+ assert_equal 1, @ship.association(:parts).target.size
assert_equal 'Mast', @ship.parts[0].name
- assert_no_difference("@ship.parts[0].trinkets.proxy_target.size") do
- @ship.parts[0].trinkets.proxy_target.size
+ assert_no_difference("@ship.parts[0].association(:trinkets).target.size") do
+ @ship.parts[0].association(:trinkets).target.size
end
assert_equal 'Ruby', @ship.parts[0].trinkets[0].name
@ship.save
@@ -880,23 +939,23 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR
@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")
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index d7666b19f6..8ca9d626d1 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/post'
+require 'models/comment'
require 'models/author'
require 'models/topic'
require 'models/reply'
@@ -191,7 +192,6 @@ class PersistencesTest < ActiveRecord::TestCase
topic = Topic.create("title" => "New Topic") do |t|
t.author_name = "David"
end
- topicReloaded = Topic.find(topic.id)
assert_equal("New Topic", topic.title)
assert_equal("David", topic.author_name)
end
@@ -240,6 +240,15 @@ class PersistencesTest < ActiveRecord::TestCase
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_delete
topic = Topic.find(1)
assert_equal topic, topic.delete, 'topic.delete did not return self'
@@ -260,7 +269,7 @@ class PersistencesTest < ActiveRecord::TestCase
end
def test_record_not_found_exception
- assert_raise(ActiveRecord::RecordNotFound) { topicReloaded = Topic.find(99999) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) }
end
def test_update_all
@@ -332,23 +341,26 @@ class PersistencesTest < ActiveRecord::TestCase
assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute(:color, 'black') }
end
- def test_update_attribute_with_one_changed_and_one_updated
- t = Topic.order('id').limit(1).first
- title, author_name = t.title, t.author_name
- t.author_name = 'John'
- t.update_attribute(: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"
- assert !t.title_changed?, "title should not have changed"
- assert_nil t.title_change, 'title change should be nil'
- assert_equal ['author_name'], t.changed
-
- t.reload
- assert_equal 'David', t.author_name
- assert_equal 'super_title', t.title
- end
+ # This test is correct, but it is hard to fix it since
+ # update_attribute trigger simply call save! that triggers
+ # all callbacks.
+ # def test_update_attribute_with_one_changed_and_one_updated
+ # t = Topic.order('id').limit(1).first
+ # title, author_name = t.title, t.author_name
+ # t.author_name = 'John'
+ # t.update_attribute(: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"
+ # assert !t.title_changed?, "title should not have changed"
+ # assert_nil t.title_change, 'title change should be nil'
+ # assert_equal ['author_name'], t.changed
+ #
+ # t.reload
+ # assert_equal 'David', t.author_name
+ # assert_equal 'super_title', t.title
+ # end
def test_update_attribute_with_one_updated
t = Topic.first
@@ -363,13 +375,16 @@ class PersistencesTest < ActiveRecord::TestCase
assert_equal 'super_title', t.title
end
- def test_update_attribute_for_udpated_at_on
+ 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
diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb
index e61960059e..379cf5b44e 100644
--- a/activerecord/test/cases/pooled_connections_test.rb
+++ b/activerecord/test/cases/pooled_connections_test.rb
@@ -89,11 +89,16 @@ class PooledConnectionsTest < ActiveRecord::TestCase
def test_undefined_connection_returns_false
old_handler = ActiveRecord::Base.connection_handler
ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
- assert_equal false, ActiveRecord::Base.connected?
+ assert ! ActiveRecord::Base.connected?
ensure
ActiveRecord::Base.connection_handler = old_handler
end
+ def test_connection_config
+ ActiveRecord::Base.establish_connection(@connection)
+ assert_equal @connection, ActiveRecord::Base.connection_config
+ end
+
def test_with_connection_nesting_safety
ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1, :wait_timeout => 0.1}))
@@ -137,4 +142,4 @@ class PooledConnectionsTest < ActiveRecord::TestCase
def add_record(name)
ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name }
end
-end unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name
+end unless current_adapter?(:FrontBase) || in_memory_db?
diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb
index 1e44237e0a..63d8c7d1c1 100644
--- a/activerecord/test/cases/primary_keys_test.rb
+++ b/activerecord/test/cases/primary_keys_test.rb
@@ -11,7 +11,7 @@ class PrimaryKeysTest < ActiveRecord::TestCase
def test_to_key_with_default_primary_key
topic = Topic.new
- assert topic.to_key.nil?
+ assert_nil topic.to_key
topic = Topic.find(1)
assert_equal [1], topic.to_key
end
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index 594db1d0ab..53aefc7b58 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -22,6 +22,12 @@ class QueryCacheTest < ActiveRecord::TestCase
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 }
@@ -57,7 +63,7 @@ class QueryCacheTest < ActiveRecord::TestCase
# Oracle adapter returns count() as Fixnum or Float
if current_adapter?(:OracleAdapter)
assert_kind_of Numeric, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
- elsif current_adapter?(:SQLite3Adapter) && SQLite3::Version::VERSION > '1.2.5' or current_adapter?(:Mysql2Adapter)
+ elsif current_adapter?(:SQLite3Adapter) && SQLite3::VERSION > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter)
# Future versions of the sqlite3 adapter will return numeric
assert_instance_of Fixnum,
Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
@@ -127,7 +133,6 @@ class QueryCacheExpiryTest < ActiveRecord::TestCase
def test_cache_is_expired_by_habtm_delete
ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
ActiveRecord::Base.cache do
- c = Category.find(1)
p = Post.find(1)
assert p.categories.any?
p.categories.delete_all
diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb
new file mode 100644
index 0000000000..b87fb51d97
--- /dev/null
+++ b/activerecord/test/cases/quoting_test.rb
@@ -0,0 +1,220 @@
+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 { def to_yaml; 'lol' end }.new
+ assert_equal "'lol'", @quoter.quote(crazy, nil)
+ assert_equal "'lol'", @quoter.quote(crazy, Object.new)
+ end
+
+ def test_crazy_object_calls_quote_string
+ crazy = Class.new { def to_yaml; 'lo\l' end }.new
+ assert_equal "'lo\\\\l'", @quoter.quote(crazy, nil)
+ assert_equal "'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
+ end
+ end
+end
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index 98011f40a4..e21109baae 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -6,13 +6,8 @@ require 'models/project'
require 'models/reader'
require 'models/person'
-# Dummy class methods to test implicit association scoping.
-def Comment.foo() find :first end
-def Project.foo() find :first end
-
-
class ReadOnlyTest < ActiveRecord::TestCase
- fixtures :posts, :comments, :developers, :projects, :developers_projects
+ fixtures :posts, :comments, :developers, :projects, :developers_projects, :people, :readers
def test_cant_save_readonly_record
dev = Developer.find(1)
@@ -49,15 +44,6 @@ class ReadOnlyTest < ActiveRecord::TestCase
Developer.joins(', projects').readonly(false).each { |d| assert !d.readonly? }
end
-
- def test_habtm_find_readonly
- dev = Developer.find(1)
- assert !dev.projects.empty?
- assert dev.projects.all?(&:readonly?)
- assert dev.projects.find(:all).all?(&:readonly?)
- assert dev.projects.readonly(true).all?(&:readonly?)
- end
-
def test_has_many_find_readonly
post = Post.find(1)
assert !post.comments.empty?
@@ -71,6 +57,18 @@ class ReadOnlyTest < ActiveRecord::TestCase
assert !people.any?(&:readonly?)
end
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_by_id
+ assert !posts(:welcome).people.find(1).readonly?
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_first
+ assert !posts(:welcome).people.first.readonly?
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_last
+ assert !posts(:welcome).people.last.readonly?
+ end
+
def test_readonly_scoping
Post.send(:with_scope, :find => { :conditions => '1=1' }) do
assert !Post.find(1).readonly?
@@ -102,7 +100,13 @@ class ReadOnlyTest < ActiveRecord::TestCase
end
def test_association_collection_method_missing_scoping_not_readonly
- assert !Developer.find(1).projects.foo.readonly?
- assert !Post.find(1).comments.foo.readonly?
+ developer = Developer.find(1)
+ project = Post.find(1)
+
+ assert !developer.projects.all_as_method.first.readonly?
+ assert !developer.projects.all_as_scope.first.readonly?
+
+ assert !project.comments.all_as_method.first.readonly?
+ assert !project.comments.all_as_scope.first.readonly?
end
end
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index 03c4fc4e80..97d9669483 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -7,6 +7,17 @@ require 'models/subscriber'
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'
class ReflectionTest < ActiveRecord::TestCase
include ActiveRecord::Reflection
@@ -24,25 +35,25 @@ class ReflectionTest < ActiveRecord::TestCase
def test_read_attribute_names
assert_equal(
- %w( id title author_name author_email_address bonus_time written_on last_read content group approved replies_count parent_id parent_title type ).sort,
- @first.attribute_names
+ %w( id title author_name author_email_address bonus_time written_on last_read content group approved replies_count parent_id parent_title type created_at updated_at ).sort,
+ @first.attribute_names.sort
)
end
def test_columns
- assert_equal 14, Topic.columns.length
+ assert_equal 16, 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 approved replies_count parent_id parent_title type group), column_names
+ assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content 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 10, content_columns.length
- assert_equal %w(title author_name author_email_address written_on bonus_time last_read content group approved parent_title).sort, content_column_names.sort
+ assert_equal 12, content_columns.length
+ assert_equal %w(title author_name author_email_address written_on bonus_time last_read content group approved parent_title created_at updated_at).sort, content_column_names.sort
end
def test_column_string_type_and_limit
@@ -126,16 +137,16 @@ class ReflectionTest < ActiveRecord::TestCase
def test_belongs_to_inferred_foreign_key_from_assoc_name
Company.belongs_to :foo
- assert_equal "foo_id", Company.reflect_on_association(:foo).primary_key_name
+ assert_equal "foo_id", Company.reflect_on_association(:foo).foreign_key
Company.belongs_to :bar, :class_name => "Xyzzy"
- assert_equal "bar_id", Company.reflect_on_association(:bar).primary_key_name
+ assert_equal "bar_id", Company.reflect_on_association(:bar).foreign_key
Company.belongs_to :baz, :class_name => "Xyzzy", :foreign_key => "xyzzy_id"
- assert_equal "xyzzy_id", Company.reflect_on_association(:baz).primary_key_name
+ assert_equal "xyzzy_id", Company.reflect_on_association(:baz).foreign_key
end
def test_association_reflection_in_modules
ActiveRecord::Base.store_full_sti_class = false
-
+
assert_reflection MyApplication::Business::Firm,
:clients_of_firm,
:klass => MyApplication::Business::Client,
@@ -177,8 +188,8 @@ class ReflectionTest < ActiveRecord::TestCase
def test_reflection_of_all_associations
# FIXME these assertions bust a lot
- assert_equal 37, Firm.reflect_on_all_associations.size
- assert_equal 27, Firm.reflect_on_all_associations(:has_many).size
+ assert_equal 36, Firm.reflect_on_all_associations.size
+ assert_equal 26, Firm.reflect_on_all_associations(:has_many).size
assert_equal 10, Firm.reflect_on_all_associations(:has_one).size
assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size
end
@@ -191,6 +202,66 @@ class ReflectionTest < ActiveRecord::TestCase
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_conditions
+ expected = [
+ [{ :tags => { :name => 'Blue' } }],
+ [{ :taggings => { :comment => 'first' } }, { "taggable_type" => "Post" }],
+ [{ :posts => { :title => ['misc post by bob', 'misc post by mary'] } }]
+ ]
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags).conditions
+ assert_equal expected, actual
+
+ expected = [
+ [{ :tags => { :name => 'Blue' } }, { :taggings => { :comment => 'first' } }, { :posts => { :title => ['misc post by bob', 'misc post by mary'] } }],
+ [{ "taggable_type" => "Post" }],
+ []
+ ]
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions
+ 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 "id", Tagging.reflect_on_association(:taggable).association_primary_key.to_s
+
+ # Through association (uses the :primary_key option from the source reflection)
+ assert_equal "nick", Author.reflect_on_association(:subscribers).association_primary_key.to_s
+ 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_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_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?
@@ -228,6 +299,18 @@ class ReflectionTest < ActiveRecord::TestCase
assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, { :autosave => true, :validate => false }, Firm).validate?
end
+ def test_foreign_key
+ assert_equal "author_id", Author.reflect_on_association(:posts).foreign_key.to_s
+ assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s
+ end
+
+ def test_primary_key_name
+ assert_deprecated do
+ assert_equal "author_id", Author.reflect_on_association(:posts).primary_key_name.to_s
+ assert_equal "category_id", Post.reflect_on_association(:categorizations).primary_key_name.to_s
+ end
+ end
+
private
def assert_reflection(klass, association, options)
assert reflection = klass.reflect_on_association(association)
diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb
index a50a4d4165..7369aaea1d 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -152,7 +152,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
Developer.where('salary = 80000').scoping do
Developer.limit(10).scoping do
devs = Developer.scoped
- assert_equal '(salary = 80000)', devs.arel.send(:where_clauses).join(' AND ')
+ assert_match '(salary = 80000)', devs.arel.to_sql
assert_equal 10, devs.taken
end
end
@@ -161,7 +161,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
def test_merge_inner_scope_has_priority
Developer.limit(5).scoping do
Developer.limit(10).scoping do
- assert_equal 10, Developer.count
+ assert_equal 10, Developer.all.size
end
end
end
@@ -209,7 +209,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
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?
+ assert_blank Comment.new.body
Comment.create :body => "Hey guys"
end
end
@@ -254,14 +254,13 @@ class HasManyScopingTest< ActiveRecord::TestCase
end
def test_should_maintain_default_scope_on_associations
- person = people(:michael)
magician = BadReference.find(1)
assert_equal [magician], people(:michael).bad_references
end
def test_should_default_scope_on_associations_is_overriden_by_association_conditions
- person = people(:michael)
- assert_equal [], people(:michael).fixed_bad_references
+ reference = references(:michael_unicyclist).becomes(BadReference)
+ assert_equal [reference], people(:michael).fixed_bad_references
end
def test_should_maintain_default_scope_on_eager_loaded_associations
@@ -311,6 +310,35 @@ class DefaultScopingTest < ActiveRecord::TestCase
assert_equal expected, received
end
+ def test_default_scope_with_lambda
+ expected = Post.find_all_by_author_id(2)
+ PostForAuthor.selected_author = 2
+ received = PostForAuthor.all
+ assert_equal expected, received
+ expected = Post.find_all_by_author_id(1)
+ PostForAuthor.selected_author = 1
+ received = PostForAuthor.all
+ assert_equal expected, received
+ end
+
+ def test_default_scope_with_thing_that_responds_to_call
+ klass = Class.new(ActiveRecord::Base) do
+ self.table_name = 'posts'
+ end
+
+ klass.class_eval do
+ default_scope Class.new(Struct.new(:klass)) {
+ def call
+ klass.where(:author_id => 2)
+ end
+ }.new(self)
+ end
+
+ records = klass.all
+ assert_equal 3, records.length
+ assert_equal 2, records.first.author_id
+ end
+
def test_default_scope_is_unscoped_on_find
assert_equal 1, DeveloperCalledDavid.count
assert_equal 11, DeveloperCalledDavid.unscoped.count
@@ -339,7 +367,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
def test_default_scoping_with_inheritance
# Inherit a class having a default scope and define a new default scope
klass = Class.new(DeveloperOrderedBySalary)
- klass.send :default_scope, :limit => 1
+ klass.send :default_scope, :limit => 1
# Scopes added on children should append to parent scope
assert_equal 1, klass.scoped.limit_value
@@ -363,29 +391,47 @@ class DefaultScopingTest < ActiveRecord::TestCase
assert_equal "David", klass.first.name
assert_equal 100000, klass.first.salary
end
+
+ def test_default_scope_called_twice_in_different_place_merges_where_clause
+ Developer.destroy_all
+ Developer.create!(:name => "David", :salary => 80000)
+ Developer.create!(:name => "David", :salary => 100000)
+ Developer.create!(:name => "Brian", :salary => 100000)
+
+ klass = Class.new(Developer)
+ klass.class_eval do
+ default_scope where("name = 'David'")
+ default_scope where("salary = 100000")
+ end
+
+ assert_equal 1, klass.count
+ assert_equal "David", klass.first.name
+ assert_equal 100000, klass.first.salary
+ end
+
def test_method_scope
- expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
+ expected = Developer.find(:all, :order => 'salary DESC, name DESC').collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.all_ordered_by_name.collect { |dev| dev.salary }
assert_equal expected, received
end
def test_nested_scope
- expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
+ expected = Developer.find(:all, :order => 'salary DESC, name DESC').collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.send(:with_scope, :find => { :order => 'name DESC'}) do
DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
end
assert_equal expected, received
end
- def test_named_scope_overwrites_default
- expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.name }
+ def test_scope_overwrites_default
+ expected = Developer.find(:all, :order => 'salary DESC, name DESC').collect { |dev| dev.name }
received = DeveloperOrderedBySalary.by_name.find(:all).collect { |dev| dev.name }
assert_equal expected, received
end
- def test_named_scope_reorders_default
- expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.reordered_by_name.find(:all).collect { |dev| dev.name }
+ def test_except_and_order_overrides_default_scope_order
+ expected = Developer.order('name DESC').collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.except(:order).order('name DESC').collect { |dev| dev.name }
assert_equal expected, received
end
@@ -397,8 +443,8 @@ class DefaultScopingTest < ActiveRecord::TestCase
assert_equal expected, received
end
- def test_overwriting_default_scope
- expected = Developer.find(:all, :order => 'salary').collect { |dev| dev.salary }
+ def test_order_in_default_scope_should_prevail
+ expected = Developer.find(:all, :order => 'salary desc').collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.find(:all, :order => 'salary').collect { |dev| dev.salary }
assert_equal expected, received
end
@@ -413,9 +459,48 @@ class DefaultScopingTest < ActiveRecord::TestCase
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
end
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
new file mode 100644
index 0000000000..7bdbd773b6
--- /dev/null
+++ b/activerecord/test/cases/relation_test.rb
@@ -0,0 +1,139 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+
+module ActiveRecord
+ class RelationTest < ActiveRecord::TestCase
+ fixtures :posts, :comments
+
+ class FakeKlass < Struct.new(:table_name)
+ end
+
+ def test_construction
+ relation = nil
+ assert_nothing_raised do
+ relation = Relation.new :a, :b
+ end
+ assert_equal :a, relation.klass
+ assert_equal :b, relation.table
+ assert !relation.loaded, 'relation is not loaded'
+ end
+
+ def test_single_values
+ assert_equal [:limit, :offset, :lock, :readonly, :create_with, :from].map(&:to_s).sort,
+ Relation::SINGLE_VALUE_METHODS.map(&:to_s).sort
+ end
+
+ def test_initialize_single_values
+ relation = Relation.new :a, :b
+ Relation::SINGLE_VALUE_METHODS.each do |method|
+ assert_nil relation.send("#{method}_value"), method.to_s
+ end
+ end
+
+ def test_association_methods
+ assert_equal [:includes, :eager_load, :preload].map(&:to_s).sort,
+ Relation::ASSOCIATION_METHODS.map(&:to_s).sort
+ end
+
+ def test_initialize_association_methods
+ relation = Relation.new :a, :b
+ Relation::ASSOCIATION_METHODS.each do |method|
+ assert_equal [], relation.send("#{method}_values"), method.to_s
+ end
+ end
+
+ def test_multi_value_methods
+ assert_equal [:select, :group, :order, :joins, :where, :having, :bind].map(&:to_s).sort,
+ Relation::MULTI_VALUE_METHODS.map(&:to_s).sort
+ end
+
+ def test_multi_value_initialize
+ relation = Relation.new :a, :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 :a, :b
+ assert_equal [], relation.extensions
+ end
+
+ def test_empty_where_values_hash
+ relation = Relation.new :a, :b
+ assert_equal({}, relation.where_values_hash)
+
+ relation.where_values << :hello
+ assert_equal({}, relation.where_values_hash)
+ end
+
+ def test_has_values
+ relation = Relation.new Post, Post.arel_table
+ relation.where_values << 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_values << 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_values << 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 :a, :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_values << 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_values << 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 :a, :b
+ assert !relation.eager_loading?
+ end
+
+ def test_eager_load_values
+ relation = Relation.new :a, :b
+ relation.eager_load_values << :b
+ assert relation.eager_loading?
+ end
+ end
+end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index ac7b501bb7..4c5c871251 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -1,4 +1,5 @@
require "cases/helper"
+require 'models/tag'
require 'models/tagging'
require 'models/post'
require 'models/topic'
@@ -10,16 +11,46 @@ require 'models/entrant'
require 'models/developer'
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,
- :taggings
+ :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.scoped
+ 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_apply_relation_as_where_id
- posts = Post.arel_table
- post_authors = posts.where(posts[:author_id].eq(1)).project(posts[:id])
- assert_equal 5, post_authors.to_a.size
- assert_equal 5, Post.where(:id => post_authors).size
+ 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
@@ -120,12 +151,6 @@ class RelationTest < ActiveRecord::TestCase
assert_equal topics(:fourth).title, topics.first.title
end
- def test_finding_with_reorder
- topics = Topic.order('author_name').order('title').reorder('id')
- assert_equal 4, topics.to_a.size
- assert_equal topics(:first).title, topics.first.title
- end
-
def test_finding_with_order_and_take
entrants = Entrant.order("id ASC").limit(2).to_a
@@ -133,6 +158,16 @@ class RelationTest < ActiveRecord::TestCase
assert_equal entrants(:first).name, entrants.first.name
end
+ def test_finding_with_complex_order_and_limit
+ tags = Tag.includes(: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).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)
@@ -155,6 +190,10 @@ class RelationTest < ActiveRecord::TestCase
assert_equal [2, 4, 6, 8, 10], even_ids.sort
end
+ def test_joins_with_nil_argument
+ assert_nothing_raised { DependentFirm.joins(nil).first }
+ end
+
def test_finding_with_hash_conditions_on_joined_table
firms = DependentFirm.joins(:account).where({:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}).to_a
assert_equal 1, firms.size
@@ -219,7 +258,7 @@ class RelationTest < ActiveRecord::TestCase
end
end
- def test_respond_to_class_methods_and_named_scopes
+ def test_respond_to_class_methods_and_scopes
assert DeveloperOrderedBySalary.scoped.respond_to?(:all_ordered_by_name)
assert Topic.scoped.respond_to?(:by_lifo)
end
@@ -242,27 +281,27 @@ class RelationTest < ActiveRecord::TestCase
def test_find_with_preloaded_associations
assert_queries(2) do
- posts = Post.preload(:comments)
+ posts = Post.preload(:comments).order('posts.id')
assert posts.first.comments.first
end
- assert_queries(2) do
- posts = Post.preload(:comments).to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
+ posts = Post.preload(:comments).order('posts.id')
assert posts.first.comments.first
end
assert_queries(2) do
- posts = Post.preload(:author)
+ posts = Post.preload(:author).order('posts.id')
assert posts.first.author
end
- assert_queries(2) do
- posts = Post.preload(:author).to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
+ posts = Post.preload(:author).order('posts.id')
assert posts.first.author
end
- assert_queries(3) do
- posts = Post.preload(:author, :comments).to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 3) do
+ posts = Post.preload(:author, :comments).order('posts.id')
assert posts.first.author
assert posts.first.comments.first
end
@@ -270,22 +309,22 @@ class RelationTest < ActiveRecord::TestCase
def test_find_with_included_associations
assert_queries(2) do
- posts = Post.includes(:comments)
+ posts = Post.includes(:comments).order('posts.id')
assert posts.first.comments.first
end
- assert_queries(2) do
- posts = Post.scoped.includes(:comments)
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
+ posts = Post.scoped.includes(:comments).order('posts.id')
assert posts.first.comments.first
end
assert_queries(2) do
- posts = Post.includes(:author)
+ posts = Post.includes(:author).order('posts.id')
assert posts.first.author
end
- assert_queries(3) do
- posts = Post.includes(:author, :comments).to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 3) do
+ posts = Post.includes(:author, :comments).order('posts.id')
assert posts.first.author
assert posts.first.comments.first
end
@@ -361,7 +400,7 @@ class RelationTest < ActiveRecord::TestCase
lifo = authors.find_or_initialize_by_name('Lifo')
assert_equal "Lifo", lifo.name
- assert lifo.new_record?
+ assert !lifo.persisted?
assert_equal authors(:david), authors.find_or_initialize_by_name(:name => 'David')
end
@@ -371,7 +410,7 @@ class RelationTest < ActiveRecord::TestCase
lifo = authors.find_or_create_by_name('Lifo')
assert_equal "Lifo", lifo.name
- assert ! lifo.new_record?
+ assert lifo.persisted?
assert_equal authors(:david), authors.find_or_create_by_name(:name => 'David')
end
@@ -401,7 +440,87 @@ class RelationTest < ActiveRecord::TestCase
def test_find_in_empty_array
authors = Author.scoped.where(:id => [])
- assert authors.all.blank?
+ assert_blank authors.all
+ end
+
+ def test_where_with_ar_object
+ author = Author.first
+ authors = Author.scoped.where(:id => author)
+ assert_equal 1, authors.all.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.all
+ end
+
+ def test_multi_where_ands_queries
+ relation = Author.unscoped
+ david = authors(:david)
+ sql = relation.where(:name => david.name).where(:name => 'Santiago').to_sql
+ assert_match('AND', sql)
+ end
+
+ def test_find_all_with_multiple_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.all
+ end
+
+ def test_find_all_using_where_with_relation
+ david = authors(:david)
+ # switching the lines below would succeed in current rails
+ # assert_queries(2) {
+ assert_queries(1) {
+ relation = Author.where(:id => Author.where(:id => david.id))
+ assert_equal [david], relation.all
+ }
+ end
+
+ def test_find_all_using_where_with_relation_with_joins
+ david = authors(:david)
+ assert_queries(1) {
+ relation = Author.where(:id => Author.joins(:posts).where(:id => david.id))
+ assert_equal [david], relation.all
+ }
+ end
+
+
+ def test_find_all_using_where_with_relation_with_select_to_build_subquery
+ david = authors(:david)
+ assert_queries(1) {
+ relation = Author.where(:name => Author.where(:id => david.id).select(:name))
+ assert_equal [david], relation.all
+ }
end
def test_exists
@@ -419,7 +538,7 @@ class RelationTest < ActiveRecord::TestCase
def test_last
authors = Author.scoped
- assert_equal authors(:mary), authors.last
+ assert_equal authors(:bob), authors.last
end
def test_destroy_all
@@ -455,18 +574,22 @@ class RelationTest < ActiveRecord::TestCase
assert davids.loaded?
end
+ def test_select_argument_error
+ assert_raises(ArgumentError) { Developer.select }
+ end
+
def test_relation_merging
- devs = Developer.where("salary >= 80000") & Developer.limit(2) & Developer.order('id ASC').where("id < 3")
+ devs = Developer.where("salary >= 80000").merge(Developer.limit(2)).merge(Developer.order('id ASC').where("id < 3"))
assert_equal [developers(:david), developers(:jamis)], devs.to_a
- dev_with_count = Developer.limit(1) & Developer.order('id DESC') & Developer.select('developers.*')
+ dev_with_count = Developer.limit(1).merge(Developer.order('id DESC')).merge(Developer.select('developers.*'))
assert_equal [developers(:poor_jamis)], dev_with_count.to_a
end
def test_relation_merging_with_eager_load
relations = []
- relations << (Post.order('comments.id DESC') & Post.eager_load(:last_comment) & Post.scoped)
- relations << (Post.eager_load(:last_comment) & Post.order('comments.id DESC') & Post.scoped)
+ relations << Post.order('comments.id DESC').merge(Post.eager_load(:last_comment)).merge(Post.scoped)
+ relations << Post.eager_load(:last_comment).merge(Post.order('comments.id DESC')).merge(Post.scoped)
relations.each do |posts|
post = posts.find { |p| p.id == 1 }
@@ -475,35 +598,42 @@ class RelationTest < ActiveRecord::TestCase
end
def test_relation_merging_with_locks
- devs = Developer.lock.where("salary >= 80000").order("id DESC") & Developer.limit(2)
- assert devs.locked.present?
+ devs = Developer.lock.where("salary >= 80000").order("id DESC").merge(Developer.limit(2))
+ assert_present devs.locked
end
def test_relation_merging_with_preload
- [Post.scoped & Post.preload(:author), Post.preload(:author) & Post.scoped].each do |posts|
- assert_queries(2) { assert posts.first.author }
+ ActiveRecord::IdentityMap.without do
+ [Post.scoped.merge(Post.preload(:author)), Post.preload(:author).merge(Post.scoped)].each do |posts|
+ assert_queries(2) { assert posts.first.author }
+ end
end
end
+ def test_relation_merging_with_joins
+ comments = Comment.joins(:post).where(:body => 'Thank you for the welcome').merge(Post.where(:body => 'Such a lovely day'))
+ assert_equal 1, comments.count
+ end
+
def test_count
posts = Post.scoped
- assert_equal 7, posts.count
- assert_equal 7, posts.count(:all)
- assert_equal 7, posts.count(:id)
+ 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 5, posts.where(:comments_count => 0).count
+ assert_equal 9, posts.where(:comments_count => 0).count
end
def test_count_with_distinct
posts = Post.scoped
assert_equal 3, posts.count(:comments_count, :distinct => true)
- assert_equal 7, posts.count(:comments_count, :distinct => false)
+ assert_equal 11, posts.count(:comments_count, :distinct => false)
assert_equal 3, posts.select(:comments_count).count(:distinct => true)
- assert_equal 7, posts.select(:comments_count).count(:distinct => false)
+ assert_equal 11, posts.select(:comments_count).count(:distinct => false)
end
def test_count_explicit_columns
@@ -511,9 +641,9 @@ class RelationTest < ActiveRecord::TestCase
posts = Post.scoped
assert_equal [0], posts.select('comments_count').where('id is not null').group('id').order('id').count.values.uniq
- assert_equal 7, posts.where('id is not null').select('comments_count').count
+ assert_equal 0, posts.where('id is not null').select('comments_count').count
- assert_equal 7, posts.select('comments_count').count('id')
+ 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')
@@ -528,12 +658,12 @@ class RelationTest < ActiveRecord::TestCase
def test_size
posts = Post.scoped
- assert_queries(1) { assert_equal 7, posts.size }
+ 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 5, best_posts.size }
+ assert_no_queries { assert_equal 9, best_posts.size }
end
def test_count_complex_chained_relations
@@ -543,9 +673,43 @@ class RelationTest < ActiveRecord::TestCase
assert_equal expected, posts.count
end
+ def test_empty
+ posts = Post.scoped
+
+ 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.scoped
+ # This test was failing when run on its own (as opposed to running the entire suite).
+ # The second line in the assert_queries block was causing visit_Arel_Attributes_Attribute
+ # in Arel::Visitors::ToSql to trigger a SHOW TABLES query. Running that line here causes
+ # the SHOW TABLES result to be cached so we don't have to do it again in the block.
+ #
+ # This is obviously a rubbish fix but it's the best I can come up with for now...
+ posts.where(:id => nil).any?
+
assert_queries(3) do
assert posts.any? # Uses COUNT()
assert ! posts.where(:id => nil).any?
@@ -596,10 +760,10 @@ class RelationTest < ActiveRecord::TestCase
sparrow = birds.create
assert_kind_of Bird, sparrow
- assert sparrow.new_record?
+ assert !sparrow.persisted?
hen = birds.where(:name => 'hen').create
- assert ! hen.new_record?
+ assert hen.persisted?
assert_equal 'hen', hen.name
end
@@ -610,7 +774,7 @@ class RelationTest < ActiveRecord::TestCase
hen = birds.where(:name => 'hen').create!
assert_kind_of Bird, hen
- assert ! hen.new_record?
+ assert hen.persisted?
assert_equal 'hen', hen.name
end
@@ -633,6 +797,25 @@ class RelationTest < ActiveRecord::TestCase
assert_equal Post.all, all_posts.all
end
+ def test_extensions_with_except
+ assert_equal 2, Topic.named_extension.order(:author_name).except(:order).two
+ end
+
+ def test_only
+ relation = Post.where(:author_id => 1).order('id ASC').limit(1)
+ assert_equal [posts(:welcome)], relation.all
+
+ author_posts = relation.only(:where)
+ assert_equal Post.where(:author_id => 1).all, author_posts.all
+
+ all_posts = relation.only(:limit)
+ assert_equal Post.limit(1).all.first, all_posts.first
+ end
+
+ def test_extensions_with_only
+ assert_equal 2, Topic.named_extension.order(:author_name).only(:order).two
+ end
+
def test_anonymous_extension
relation = Post.where(:author_id => 1).order('id ASC').extending do
def author
@@ -654,7 +837,66 @@ class RelationTest < ActiveRecord::TestCase
assert_equal Post.order(Post.arel_table[:title]).all, Post.order("title").all
end
- def test_relations_limit_with_conditions_or_limit
- assert_equal Post.limit(2).size, Post.limit(2).all.size
+ def test_order_with_find_with_order
+ assert_equal 'zyke', CoolCar.order('name desc').find(:first, :order => 'id').name
+ assert_equal 'zyke', FastCar.order('name desc').find(:first, :order => 'id').name
+ end
+
+ def test_default_scope_order_with_scope_order
+ assert_equal 'zyke', CoolCar.order_using_new_style.limit(1).first.name
+ assert_equal 'zyke', CoolCar.order_using_old_style.limit(1).first.name
+ assert_equal 'zyke', FastCar.order_using_new_style.limit(1).first.name
+ assert_equal 'zyke', FastCar.order_using_old_style.limit(1).first.name
+ end
+
+ def test_order_using_scoping
+ car1 = CoolCar.order('id DESC').scoping do
+ CoolCar.find(:first, :order => 'id asc')
+ end
+ assert_equal 'zyke', car1.name
+
+ car2 = FastCar.order('id DESC').scoping do
+ FastCar.find(:first, :order => 'id asc')
+ end
+ assert_equal 'zyke', 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', CoolCar.unscoped { CoolCar.order_using_old_style.limit(1).first.name}
+
+ assert_equal 'honda', FastCar.unscoped { FastCar.order_using_new_style.limit(1).first.name}
+ assert_equal 'honda', FastCar.unscoped { FastCar.order_using_old_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_removing_limit_with_options
+ assert_not_equal 1, Post.limit(1).all(:limit => nil).count
+ end
+
+ def test_primary_key
+ assert_equal "id", Post.scoped.primary_key
+ end
+
+ 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 scope.eager_loading?
end
end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 66446b6b7e..9b2c7c00df 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -100,7 +100,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_match %r{c_int_4.*}, output
assert_no_match %r{c_int_4.*:limit}, output
- elsif current_adapter?(:SQLiteAdapter)
+ 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
@@ -109,7 +109,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_match %r{c_int_without_limit.*}, output
assert_no_match %r{c_int_without_limit.*:limit}, output
- if current_adapter?(:SQLiteAdapter)
+ 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
diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb
index dab81530af..677d659f39 100644
--- a/activerecord/test/cases/serialization_test.rb
+++ b/activerecord/test/cases/serialization_test.rb
@@ -5,7 +5,7 @@ require 'models/reply'
require 'models/company'
class SerializationTest < ActiveRecord::TestCase
-
+
fixtures :topics, :companies, :accounts
FORMATS = [ :xml, :json ]
@@ -23,6 +23,12 @@ class SerializationTest < ActiveRecord::TestCase
@contact = Contact.new(@contact_attributes)
end
+ def test_serialized_init_with
+ topic = Topic.allocate
+ topic.init_with('attributes' => { 'content' => '--- foo' })
+ assert_equal 'foo', topic.content
+ end
+
def test_to_xml
xml = REXML::Document.new(topics(:first).to_xml(:indent => 0))
bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb
index 6f1c170a0c..cee5ddd003 100644
--- a/activerecord/test/cases/session_store/session_test.rb
+++ b/activerecord/test/cases/session_store/session_test.rb
@@ -5,7 +5,7 @@ require 'active_record/session_store'
module ActiveRecord
class SessionStore
class SessionTest < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints? && ActiveRecord::Base.connection.supports_ddl_transactions?
def setup
super
@@ -60,6 +60,7 @@ module ActiveRecord
end
def test_loaded?
+ Session.create_table!
s = Session.new
assert !s.loaded?, 'session is not loaded'
end
diff --git a/activerecord/test/cases/session_store/sql_bypass.rb b/activerecord/test/cases/session_store/sql_bypass.rb
index f0ba166465..7402b2afd6 100644
--- a/activerecord/test/cases/session_store/sql_bypass.rb
+++ b/activerecord/test/cases/session_store/sql_bypass.rb
@@ -18,9 +18,9 @@ module ActiveRecord
assert !Session.table_exists?
end
- def test_new_record?
+ def test_persisted?
s = SqlBypass.new :data => 'foo', :session_id => 10
- assert s.new_record?, 'this is a new record!'
+ assert !s.persisted?, 'this is a new record!'
end
def test_not_loaded?
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index 401439994d..1c21f0f3b6 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -3,9 +3,11 @@ 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
+ fixtures :developers, :owners, :pets, :toys, :cars, :tasks
def setup
@developer = Developer.first
@@ -15,21 +17,21 @@ class TimestampTest < ActiveRecord::TestCase
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'
@@ -37,8 +39,18 @@ class TimestampTest < ActiveRecord::TestCase
@developer.reload
assert_equal previous_salary, @developer.salary
end
-
- def test_touching_a_different_attribute
+
+ 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_touching_an_attribute_updates_timestamp
previously_created_at = @developer.created_at
@developer.touch(:created_at)
@@ -47,15 +59,27 @@ class TimestampTest < ActiveRecord::TestCase
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
@@ -63,27 +87,43 @@ class TimestampTest < ActiveRecord::TestCase
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_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute
Pet.belongs_to :owner, :touch => :happy_at
pet = Pet.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
ensure
Pet.belongs_to :owner, :touch => true
end
+ def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_update_the_parent
+ Pet.belongs_to :owner, :counter_cache => :use_count, :touch => true
+
+ pet = Pet.first
+ owner = pet.owner
+ owner.update_attribute(:happy_at, 3.days.ago)
+ previously_owner_updated_at = owner.updated_at
+
+ pet.name = "I'm a parrot"
+ pet.save
+
+ assert_not_equal previously_owner_updated_at, pet.owner.updated_at
+ ensure
+ Pet.belongs_to :owner, :touch => true
+ end
+
def test_touching_a_record_touches_parent_record_and_grandparent_record
Toy.belongs_to :pet, :touch => true
Pet.belongs_to :owner, :touch => true
@@ -100,4 +140,34 @@ class TimestampTest < ActiveRecord::TestCase
ensure
Toy.belongs_to :pet
end
+
+ def test_timestamp_attributes_for_create
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_create), [:created_at, :created_on]
+ end
+
+ def test_timestamp_attributes_for_update
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_update), [:updated_at, :updated_on]
+ end
+
+ def test_all_timestamp_attributes
+ toy = Toy.first
+ assert_equal toy.send(:all_timestamp_attributes), [:created_at, :created_on, :updated_at, :updated_on]
+ end
+
+ def test_timestamp_attributes_for_create_in_model
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_create_in_model), [:created_at]
+ end
+
+ def test_timestamp_attributes_for_update_in_model
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_update_in_model), [:updated_at]
+ end
+
+ def test_all_timestamp_attributes_in_model
+ toy = Toy.first
+ assert_equal toy.send(:all_timestamp_attributes_in_model), [:created_at, :updated_at]
+ end
end
diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb
index d72c4bf7c4..85f222bca2 100644
--- a/activerecord/test/cases/transaction_callbacks_test.rb
+++ b/activerecord/test/cases/transaction_callbacks_test.rb
@@ -260,22 +260,26 @@ class TransactionObserverCallbacksTest < ActiveRecord::TestCase
class TopicWithObserverAttachedObserver < ActiveRecord::Observer
def after_commit(record)
- record.history.push :"TopicWithObserverAttachedObserver#after_commit"
+ record.history.push "after_commit"
end
def after_rollback(record)
- record.history.push :"TopicWithObserverAttachedObserver#after_rollback"
+ record.history.push "after_rollback"
end
end
def test_after_commit_called
+ assert TopicWithObserverAttachedObserver.instance, 'should have observer'
+
topic = TopicWithObserverAttached.new
topic.save!
- assert topic.history, [:"TopicWithObserverAttachedObserver#after_commit"]
+ assert_equal %w{ after_commit }, topic.history
end
def test_after_rollback_called
+ assert TopicWithObserverAttachedObserver.instance, 'should have observer'
+
topic = TopicWithObserverAttached.new
Topic.transaction do
@@ -283,6 +287,6 @@ class TransactionObserverCallbacksTest < ActiveRecord::TestCase
raise ActiveRecord::Rollback
end
- assert topic.history, [:"TopicWithObserverObserver#after_rollback"]
+ assert_equal %w{ after_rollback }, topic.history
end
end
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 9255190613..110a18772f 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -163,7 +163,7 @@ class TransactionTest < ActiveRecord::TestCase
@first.author_name += '_this_should_not_end_up_in_the_db'
@first.save!
flunk
- rescue => e
+ rescue
assert_equal original_author_name, @first.reload.author_name
assert_equal nbooks_before_save, Book.count
ensure
@@ -182,7 +182,7 @@ class TransactionTest < ActiveRecord::TestCase
:bonus_time => "2005-01-30t15:28:00.00+01:00",
:content => "Have a nice day",
:approved => false)
- new_record_snapshot = new_topic.new_record?
+ new_record_snapshot = !new_topic.persisted?
id_present = new_topic.has_attribute?(Topic.primary_key)
id_snapshot = new_topic.id
@@ -195,7 +195,7 @@ class TransactionTest < ActiveRecord::TestCase
flunk
rescue => e
assert_equal "Make the transaction rollback", e.message
- assert_equal new_record_snapshot, new_topic.new_record?, "The topic should have its old new_record value"
+ assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
ensure
@@ -263,6 +263,27 @@ class TransactionTest < ActiveRecord::TestCase
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
@@ -349,23 +370,23 @@ class TransactionTest < ActiveRecord::TestCase
assert topic_2.save
@first.save
@second.destroy
- assert_equal false, topic_1.new_record?
+ assert topic_1.persisted?, 'persisted'
assert_not_nil topic_1.id
- assert_equal false, topic_2.new_record?
+ assert topic_2.persisted?, 'persisted'
assert_not_nil topic_2.id
- assert_equal false, @first.new_record?
+ assert @first.persisted?, 'persisted'
assert_not_nil @first.id
- assert_equal true, @second.destroyed?
+ assert @second.destroyed?, 'destroyed'
raise ActiveRecord::Rollback
end
- assert_equal true, topic_1.new_record?
+ assert !topic_1.persisted?, 'not persisted'
assert_nil topic_1.id
- assert_equal true, topic_2.new_record?
+ assert !topic_2.persisted?, 'not persisted'
assert_nil topic_2.id
- assert_equal false, @first.new_record?
+ assert @first.persisted?, 'persisted'
assert_not_nil @first.id
- assert_equal false, @second.destroyed?
+ assert !@second.destroyed?, 'not destroyed'
end
if current_adapter?(:PostgreSQLAdapter) && defined?(PGconn::PQTRANS_IDLE)
@@ -399,7 +420,7 @@ class TransactionTest < ActiveRecord::TestCase
end
def test_sqlite_add_column_in_transaction
- return true unless current_adapter?(:SQLite3Adapter, :SQLiteAdapter)
+ return true unless current_adapter?(:SQLite3Adapter)
# Test first if column creation/deletion works correctly when no
# transaction is in place.
@@ -529,8 +550,6 @@ end if Topic.connection.supports_savepoints?
if current_adapter?(:PostgreSQLAdapter)
class ConcurrentTransactionTest < TransactionTest
- use_concurrent_connections
-
# This will cause transactions to overlap and fail unless they are performed on
# separate database connections.
def test_transaction_per_thread
diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb
index 23ad10f3f9..f85fb4e5da 100644
--- a/activerecord/test/cases/unconnected_test.rb
+++ b/activerecord/test/cases/unconnected_test.rb
@@ -4,7 +4,7 @@ class TestRecord < ActiveRecord::Base
end
class TestUnconnectedAdapter < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@underlying = ActiveRecord::Base.connection
@@ -14,6 +14,7 @@ class TestUnconnectedAdapter < ActiveRecord::TestCase
def teardown
@underlying = nil
ActiveRecord::Base.establish_connection(@specification)
+ load_schema if in_memory_db?
end
def test_connection_no_longer_established
diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb
index 1246dd4276..56e345990f 100644
--- a/activerecord/test/cases/validations/association_validation_test.rb
+++ b/activerecord/test/cases/validations/association_validation_test.rb
@@ -17,7 +17,7 @@ class AssociationValidationTest < ActiveRecord::TestCase
o = Owner.new('name' => 'nopets')
assert !o.save
assert o.errors[:pets].any?
- pet = o.pets.build('name' => 'apet')
+ o.pets.build('name' => 'apet')
assert o.valid?
end
@@ -27,7 +27,7 @@ class AssociationValidationTest < ActiveRecord::TestCase
assert !o.save
assert o.errors[:pets].any?
- pet = o.pets.build('name' => 'apet')
+ o.pets.build('name' => 'apet')
assert o.valid?
2.times { o.pets.build('name' => 'apet') }
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 9a863c25a8..b4f3dd034c 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -6,19 +6,6 @@ require 'models/warehouse_thing'
require 'models/guid'
require 'models/event'
-# The following methods in Topic are used in test_conditional_validation_*
-class Topic
- has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
- has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
-end
-
-class UniqueReply < Reply
- validates_uniqueness_of :content, :scope => 'parent_id'
-end
-
-class SillyUniqueReply < UniqueReply
-end
-
class Wizard < ActiveRecord::Base
self.abstract_class = true
@@ -60,7 +47,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
def test_validates_uniqueness_with_validates
Topic.validates :title, :uniqueness => true
- t = Topic.create!('title' => 'abc')
+ Topic.create!('title' => 'abc')
t2 = Topic.new('title' => 'abc')
assert !t2.valid?
@@ -201,7 +188,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer
Topic.validates_uniqueness_of(:title, :case_sensitve => true)
- t = Topic.create!('title' => 101)
+ Topic.create!('title' => 101)
t2 = Topic.new('title' => 101)
assert !t2.valid?
diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb
index fd771ef4be..c3e494866b 100644
--- a/activerecord/test/cases/validations_test.rb
+++ b/activerecord/test/cases/validations_test.rb
@@ -13,24 +13,6 @@ class ProtectedPerson < ActiveRecord::Base
attr_protected :first_name
end
-class DeprecatedPerson < ActiveRecord::Base
- set_table_name 'people'
-
- private
-
- def validate
- errors[:name] << "always invalid"
- end
-
- def validate_on_create
- errors[:name] << "invalid on create"
- end
-
- def validate_on_update
- errors[:name] << "invalid on update"
- end
-end
-
class ValidationsTest < ActiveRecord::TestCase
fixtures :topics, :developers
@@ -141,14 +123,6 @@ class ValidationsTest < ActiveRecord::TestCase
assert reply.save(:validate => false)
end
- def test_deprecated_create_without_validation
- reply = WrongReply.new
- assert !reply.save
- assert_deprecated do
- assert reply.save(false)
- end
- end
-
def test_validates_acceptance_of_with_non_existant_table
Object.const_set :IncorporealModel, Class.new(ActiveRecord::Base)
@@ -170,23 +144,6 @@ class ValidationsTest < ActiveRecord::TestCase
assert topic["approved"]
end
- def test_validate_is_deprecated_on_create
- p = DeprecatedPerson.new
- assert_deprecated do
- assert !p.valid?
- end
- assert_equal ["always invalid", "invalid on create"], p.errors[:name]
- end
-
- def test_validate_is_deprecated_on_update
- p = DeprecatedPerson.new(:first_name => "David")
- assert p.save(:validate => false)
- assert_deprecated do
- assert !p.valid?
- end
- assert_equal ["always invalid", "invalid on update"], p.errors[:name]
- end
-
def test_validators
assert_equal 1, Parrot.validators.size
assert_equal 1, Company.validators.size
diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb
index b11b340e94..a6074b23e7 100644
--- a/activerecord/test/cases/xml_serialization_test.rb
+++ b/activerecord/test/cases/xml_serialization_test.rb
@@ -4,6 +4,7 @@ require 'models/post'
require 'models/author'
require 'models/comment'
require 'models/company_in_module'
+require 'models/toy'
class XmlSerializationTest < ActiveRecord::TestCase
def test_should_serialize_default_root
@@ -83,6 +84,26 @@ class DefaultXmlSerializationTest < ActiveRecord::TestCase
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')
@@ -241,4 +262,10 @@ class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase
assert array.include? 'github'
end
+ def test_should_support_aliased_attributes
+ xml = Author.select("name as firstname").to_xml
+ array = Hash.from_xml(xml)['authors']
+ assert_equal array.size, array.select { |author| author.has_key? 'firstname' }.size
+ end
+
end
diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb
index f221def6b6..0b54c309d1 100644
--- a/activerecord/test/cases/yaml_serialization_test.rb
+++ b/activerecord/test/cases/yaml_serialization_test.rb
@@ -2,10 +2,45 @@ require "cases/helper"
require 'models/topic'
class YamlSerializationTest < ActiveRecord::TestCase
+ fixtures :topics
+
def test_to_yaml_with_time_with_zone_should_not_raise_exception
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 }
end
+
+ def test_roundtrip
+ topic = Topic.first
+ assert topic
+ t = YAML.load YAML.dump topic
+ assert_equal topic, t
+ end
+
+ def test_encode_with_coder
+ topic = Topic.first
+ coder = {}
+ topic.encode_with coder
+ assert_equal({'attributes' => topic.attributes}, coder)
+ end
+
+ begin
+ require 'psych'
+
+ def test_psych_roundtrip
+ topic = Topic.first
+ assert topic
+ t = Psych.load Psych.dump topic
+ assert_equal topic, t
+ end
+
+ def test_psych_roundtrip_new_object
+ topic = Topic.new
+ assert topic
+ t = Psych.load Psych.dump topic
+ assert_equal topic.attributes, t.attributes
+ end
+ rescue LoadError
+ end
end
diff --git a/activerecord/test/connections/native_oracle/connection.rb b/activerecord/test/connections/native_oracle/connection.rb
index bb4040058f..99f921879c 100644
--- a/activerecord/test/connections/native_oracle/connection.rb
+++ b/activerecord/test/connections/native_oracle/connection.rb
@@ -1,10 +1,5 @@
-# gem "rsim-activerecord-oracle_enhanced-adapter"
-# gem "activerecord-oracle_enhanced-adapter", ">=1.2.1"
-# uses local copy of oracle_enhanced adapter
-$:.unshift("../../oracle-enhanced/lib")
+# uses oracle_enhanced adapter in ENV['ORACLE_ENHANCED_PATH'] or from github.com/rsim/oracle-enhanced.git
require 'active_record/connection_adapters/oracle_enhanced_adapter'
-# gem "activerecord-jdbc-adapter"
-# require 'active_record/connection_adapters/jdbc_adapter'
# otherwise failed with silence_warnings method missing exception
require 'active_support/core_ext/kernel/reporting'
@@ -13,32 +8,22 @@ print "Using Oracle\n"
require_dependency 'models/course'
require 'logger'
-# ActiveRecord::Base.logger = Logger.new STDOUT
-# ActiveRecord::Base.logger.level = Logger::WARN
ActiveRecord::Base.logger = Logger.new("debug.log")
# Set these to your database connection strings
-db = ENV['ARUNIT_DB_NAME'] = 'orcl'
+ENV['ARUNIT_DB_NAME'] ||= 'orcl'
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'oracle_enhanced',
- :database => db,
- :host => "localhost", # used just by JRuby to construct JDBC connect string
- # :adapter => "jdbc",
- # :driver => "oracle.jdbc.driver.OracleDriver",
- # :url => "jdbc:oracle:thin:@localhost:1521:#{db}",
+ :database => ENV['ARUNIT_DB_NAME'],
:username => 'arunit',
:password => 'arunit',
:emulate_oracle_adapter => true
},
'arunit2' => {
:adapter => 'oracle_enhanced',
- :database => db,
- :host => "localhost", # used just by JRuby to construct JDBC connect string
- # :adapter => "jdbc",
- # :driver => "oracle.jdbc.driver.OracleDriver",
- # :url => "jdbc:oracle:thin:@localhost:1521:#{db}",
+ :database => ENV['ARUNIT_DB_NAME'],
:username => 'arunit2',
:password => 'arunit2',
:emulate_oracle_adapter => true
@@ -48,21 +33,3 @@ ActiveRecord::Base.configurations = {
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'
-# ActiveRecord::Base.connection.execute %q{alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'}
-# ActiveRecord::Base.connection.execute %q{alter session set nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS'} rescue nil
-
-# for assert_queries test helper
-ActiveRecord::Base.connection.class.class_eval do
- IGNORED_SELECT_SQL = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from ((all|user)_tab_columns|(all|user)_triggers|(all|user)_constraints)/im]
-
- def select_with_query_record(sql, name = nil, return_column_names = false)
- $queries_executed ||= []
- $queries_executed << sql unless IGNORED_SELECT_SQL.any? { |r| sql =~ r }
- select_without_query_record(sql, name, return_column_names)
- end
-
- alias_method_chain :select, :query_record
-end
-
-# For JRuby Set default $KCODE to UTF8
-$KCODE = "UTF8" if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby'
diff --git a/activerecord/test/connections/native_sqlite3/connection.rb b/activerecord/test/connections/native_sqlite3/connection.rb
index c517c2375e..c2aff5551f 100644
--- a/activerecord/test/connections/native_sqlite3/connection.rb
+++ b/activerecord/test/connections/native_sqlite3/connection.rb
@@ -3,21 +3,12 @@ require_dependency 'models/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
-class SqliteError < StandardError
-end
-
BASE_DIR = FIXTURES_ROOT
sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite3"
sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite3"
def make_connection(clazz, db_file)
ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => db_file, :timeout => 5000 } }
- unless File.exist?(db_file)
- puts "SQLite3 database not found at #{db_file}. Rebuilding it."
- sqlite_command = %Q{sqlite3 "#{db_file}" "create table a (a integer); drop table a;"}
- puts "Executing '#{sqlite_command}'"
- raise SqliteError.new("Seems that there is no sqlite3 executable available") unless system(sqlite_command)
- end
clazz.establish_connection(clazz.name)
end
diff --git a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb b/activerecord/test/connections/native_sqlite3/in_memory_connection.rb
deleted file mode 100644
index 6aba9719bb..0000000000
--- a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-print "Using native SQLite3\n"
-require_dependency 'models/course'
-require 'logger'
-ActiveRecord::Base.logger = Logger.new("debug.log")
-
-class SqliteError < StandardError
-end
-
-def make_connection(clazz, db_definitions_file)
- clazz.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
- File.read(SCHEMA_ROOT + "/#{db_definitions_file}").split(';').each do |command|
- clazz.connection.execute(command) unless command.strip.empty?
- end
-end
-
-make_connection(ActiveRecord::Base, 'sqlite.sql')
-make_connection(Course, 'sqlite2.sql')
-load(SCHEMA_ROOT + "/schema.rb")
diff --git a/activerecord/test/connections/native_sqlite3_mem/connection.rb b/activerecord/test/connections/native_sqlite3_mem/connection.rb
new file mode 100644
index 0000000000..14e10900d1
--- /dev/null
+++ b/activerecord/test/connections/native_sqlite3_mem/connection.rb
@@ -0,0 +1,19 @@
+# This file connects to an in-memory SQLite3 database, which is a very fast way to run the tests.
+# The downside is that disconnect from the database results in the database effectively being
+# wiped. For this reason, pooled_connections_test.rb is disabled when using an in-memory database.
+
+print "Using native SQLite3 (in memory)\n"
+require_dependency 'models/course'
+require 'logger'
+ActiveRecord::Base.logger = Logger.new("debug.log")
+
+class SqliteError < StandardError
+end
+
+def make_connection(clazz)
+ ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => ':memory:' } }
+ clazz.establish_connection(clazz.name)
+end
+
+make_connection(ActiveRecord::Base)
+make_connection(Course)
diff --git a/activerecord/test/fixtures/authors.yml b/activerecord/test/fixtures/authors.yml
index de2ec7d38b..832236a486 100644
--- a/activerecord/test/fixtures/authors.yml
+++ b/activerecord/test/fixtures/authors.yml
@@ -3,7 +3,13 @@ david:
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/books.yml b/activerecord/test/fixtures/books.yml
index 473663ff5b..fb48645456 100644
--- a/activerecord/test/fixtures/books.yml
+++ b/activerecord/test/fixtures/books.yml
@@ -1,7 +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
index 23c98e8144..b4c748aaa7 100644
--- a/activerecord/test/fixtures/cars.yml
+++ b/activerecord/test/fixtures/cars.yml
@@ -2,3 +2,8 @@ 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
index b0770a093d..3e75e733a6 100644
--- a/activerecord/test/fixtures/categories.yml
+++ b/activerecord/test/fixtures/categories.yml
@@ -12,3 +12,8 @@ sti_test:
id: 3
name: Special category
type: SpecialCategory
+
+cooking:
+ id: 4
+ name: Cooking
+ type: Category
diff --git a/activerecord/test/fixtures/categories_posts.yml b/activerecord/test/fixtures/categories_posts.yml
index 9b67ab4fa4..c6f0d885f5 100644
--- a/activerecord/test/fixtures/categories_posts.yml
+++ b/activerecord/test/fixtures/categories_posts.yml
@@ -21,3 +21,11 @@ sti_test_sti_habtm:
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
index c5b6fc9a51..62e5bd111a 100644
--- a/activerecord/test/fixtures/categorizations.yml
+++ b/activerecord/test/fixtures/categorizations.yml
@@ -15,3 +15,9 @@ mary_thinking_general:
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
index 1986d28229..82e439e8e5 100644
--- a/activerecord/test/fixtures/clubs.yml
+++ b/activerecord/test/fixtures/clubs.yml
@@ -1,6 +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 \ No newline at end of file
+ name: Skull and bones
+ category_id: 2
diff --git a/activerecord/test/fixtures/comments.yml b/activerecord/test/fixtures/comments.yml
index 236bdb2e36..ddbb823c49 100644
--- a/activerecord/test/fixtures/comments.yml
+++ b/activerecord/test/fixtures/comments.yml
@@ -9,7 +9,7 @@ more_greetings:
post_id: 1
body: Thank you again for the welcome
type: Comment
-
+
does_it_hurt:
id: 3
post_id: 2
@@ -37,7 +37,7 @@ eager_sti_on_associations_s_comment2:
eager_sti_on_associations_comment:
id: 8
post_id: 4
- body: Normal type
+ body: Normal type
type: Comment
check_eager_sti_on_associations:
@@ -57,3 +57,9 @@ eager_other_comment1:
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
index 9ad68fbe11..a982d3921d 100644
--- a/activerecord/test/fixtures/companies.yml
+++ b/activerecord/test/fixtures/companies.yml
@@ -12,6 +12,7 @@ first_firm:
type: Firm
name: 37signals
ruby_type: Firm
+ firm_id: 1
second_client:
id: 3
@@ -44,17 +45,17 @@ a_third_client:
ruby_type: Client
rails_core:
- id: 6
+ id: 6
name: RailsCore
type: DependentFirm
-
+
leetsoft:
- id: 7
+ id: 7
name: Leetsoft
client_of: 6
-
+
jadedpixel:
- id: 8
+ id: 8
name: Jadedpixel
client_of: 6
diff --git a/activerecord/test/fixtures/dashboards.yml b/activerecord/test/fixtures/dashboards.yml
index e75bf46e6c..a4c7e0d309 100644
--- a/activerecord/test/fixtures/dashboards.yml
+++ b/activerecord/test/fixtures/dashboards.yml
@@ -1,3 +1,6 @@
cool_first:
dashboard_id: d1
- name: my_dashboard \ No newline at end of file
+ name: my_dashboard
+second:
+ dashboard_id: d2
+ name: second
diff --git a/activerecord/test/fixtures/essays.yml b/activerecord/test/fixtures/essays.yml
new file mode 100644
index 0000000000..9d15d82359
--- /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/items.yml b/activerecord/test/fixtures/items.yml
index 31fd657df9..94e3821445 100644
--- a/activerecord/test/fixtures/items.yml
+++ b/activerecord/test/fixtures/items.yml
@@ -1,4 +1,3 @@
dvd:
id: 1
name: Godfather
- \ No newline at end of file
diff --git a/activerecord/test/fixtures/member_details.yml b/activerecord/test/fixtures/member_details.yml
new file mode 100644
index 0000000000..e1fe695a9b
--- /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/members.yml b/activerecord/test/fixtures/members.yml
index 6db945e61d..f3bbf0dac6 100644
--- a/activerecord/test/fixtures/members.yml
+++ b/activerecord/test/fixtures/members.yml
@@ -1,6 +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
index 99fbe46d9b..60eb641054 100644
--- a/activerecord/test/fixtures/memberships.yml
+++ b/activerecord/test/fixtures/memberships.yml
@@ -1,20 +1,27 @@
membership_of_boring_club:
joined_on: <%= 3.weeks.ago.to_s(:db) %>
club: boring_club
- member: groucho
+ member_id: 1
favourite: false
type: CurrentMembership
-
+
membership_of_favourite_club:
joined_on: <%= 3.weeks.ago.to_s(:db) %>
club: moustache_club
- member: groucho
+ member_id: 1
favourite: true
type: Membership
other_guys_membership:
joined_on: <%= 4.weeks.ago.to_s(:db) %>
club: boring_club
- member: some_other_guy
+ 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
diff --git a/activerecord/test/fixtures/mixins.yml b/activerecord/test/fixtures/mixins.yml
index 0f60e92c2f..f0009cc5f0 100644
--- a/activerecord/test/fixtures/mixins.yml
+++ b/activerecord/test/fixtures/mixins.yml
@@ -1,6 +1,6 @@
# Nested set mixins
-<% (1..10).each do |counter| %>
+<% (1..10).each do |counter| %>
set_<%= counter %>:
id: <%= counter+3000 %>
<% end %>
diff --git a/activerecord/test/fixtures/owners.yml b/activerecord/test/fixtures/owners.yml
index d5493a84b7..2d21ce433c 100644
--- a/activerecord/test/fixtures/owners.yml
+++ b/activerecord/test/fixtures/owners.yml
@@ -1,6 +1,7 @@
blackbeard:
owner_id: 1
name: blackbeard
+ essay_id: A Modest Proposal
ashley:
owner_id: 2
diff --git a/activerecord/test/fixtures/posts.yml b/activerecord/test/fixtures/posts.yml
index f817493190..7298096025 100644
--- a/activerecord/test/fixtures/posts.yml
+++ b/activerecord/test/fixtures/posts.yml
@@ -5,6 +5,7 @@ welcome:
body: Such a lovely day
comments_count: 2
taggings_count: 1
+ tags_count: 1
type: Post
thinking:
@@ -14,6 +15,7 @@ thinking:
body: Like I hopefully always am
comments_count: 1
taggings_count: 1
+ tags_count: 1
type: SpecialPost
authorless:
@@ -50,3 +52,31 @@ eager_other:
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/ratings.yml b/activerecord/test/fixtures/ratings.yml
new file mode 100644
index 0000000000..34e208efa3
--- /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/ships.yml b/activerecord/test/fixtures/ships.yml
index 137055aad1..df914262b3 100644
--- a/activerecord/test/fixtures/ships.yml
+++ b/activerecord/test/fixtures/ships.yml
@@ -1,5 +1,6 @@
black_pearl:
name: "Black Pearl"
+ pirate: blackbeard
interceptor:
id: 2
name: "Interceptor"
diff --git a/activerecord/test/fixtures/speedometers.yml b/activerecord/test/fixtures/speedometers.yml
index 6a471aba0a..e12398f0c4 100644
--- a/activerecord/test/fixtures/speedometers.yml
+++ b/activerecord/test/fixtures/speedometers.yml
@@ -1,4 +1,8 @@
cool_first:
speedometer_id: s1
name: my_speedometer
- dashboard_id: d1 \ No newline at end of file
+ dashboard_id: d1
+second:
+ speedometer_id: s2
+ name: second
+ dashboard_id: d2
diff --git a/activerecord/test/fixtures/sponsors.yml b/activerecord/test/fixtures/sponsors.yml
index 42df8957d1..bfc6b238b1 100644
--- a/activerecord/test/fixtures/sponsors.yml
+++ b/activerecord/test/fixtures/sponsors.yml
@@ -1,9 +1,12 @@
moustache_club_sponsor_for_groucho:
sponsor_club: moustache_club
- sponsorable: groucho (Member)
+ sponsorable_id: 1
+ sponsorable_type: Member
boring_club_sponsor_for_groucho:
sponsor_club: boring_club
- sponsorable: some_other_guy (Member)
+ sponsorable_id: 2
+ sponsorable_type: Member
crazy_club_sponsor_for_groucho:
sponsor_club: crazy_club
- sponsorable: some_other_guy (Member) \ No newline at end of file
+ sponsorable_id: 2
+ sponsorable_type: Member
diff --git a/activerecord/test/fixtures/subscribers.yml b/activerecord/test/fixtures/subscribers.yml
index 9ffb4a156f..c6a8c2fa24 100644
--- a/activerecord/test/fixtures/subscribers.yml
+++ b/activerecord/test/fixtures/subscribers.yml
@@ -5,3 +5,7 @@ first:
second:
nick: webster132
name: David Heinemeier Hansson
+
+thrid:
+ nick: swistak
+ name: Marcin Raczkowski \ No newline at end of file
diff --git a/activerecord/test/fixtures/taggings.yml b/activerecord/test/fixtures/taggings.yml
index 1e3d5965b8..d339c12b25 100644
--- a/activerecord/test/fixtures/taggings.yml
+++ b/activerecord/test/fixtures/taggings.yml
@@ -11,7 +11,7 @@ thinking_general:
taggable_id: 2
taggable_type: Post
-fake:
+fake:
id: 3
tag_id: 1
taggable_id: 1
@@ -26,3 +26,53 @@ godfather:
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
index 471b96f362..d4b7c9a4d5 100644
--- a/activerecord/test/fixtures/tags.yml
+++ b/activerecord/test/fixtures/tags.yml
@@ -1,7 +1,11 @@
general:
id: 1
name: General
-
+
misc:
id: 2
- name: Misc \ No newline at end of file
+ name: Misc
+
+blue:
+ id: 3
+ name: Blue
diff --git a/activerecord/test/fixtures/tasks.yml b/activerecord/test/fixtures/tasks.yml
index 1e6a061acc..01c95b3a4c 100644
--- a/activerecord/test/fixtures/tasks.yml
+++ b/activerecord/test/fixtures/tasks.yml
@@ -1,4 +1,4 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
first_task:
id: 1
starting: 2005-03-30t06:30:00.00+01:00
diff --git a/activerecord/test/fixtures/traffic_lights.yml b/activerecord/test/fixtures/traffic_lights.yml
new file mode 100644
index 0000000000..6dabd53474
--- /dev/null
+++ b/activerecord/test/fixtures/traffic_lights.yml
@@ -0,0 +1,6 @@
+uk:
+ location: UK
+ state:
+ - Green
+ - Red
+ - Orange
diff --git a/activerecord/test/migrations/empty/.gitkeep b/activerecord/test/migrations/empty/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/activerecord/test/migrations/empty/.gitkeep
diff --git a/activerecord/test/migrations/interleaved/pass_2/3_innocent_jointable.rb b/activerecord/test/migrations/interleaved/pass_1/3_interleaved_innocent_jointable.rb
index 21c9ca5328..bf912fbfc8 100644
--- a/activerecord/test/migrations/interleaved/pass_2/3_innocent_jointable.rb
+++ b/activerecord/test/migrations/interleaved/pass_1/3_interleaved_innocent_jointable.rb
@@ -1,4 +1,4 @@
-class InnocentJointable < ActiveRecord::Migration
+class InterleavedInnocentJointable < ActiveRecord::Migration
def self.up
create_table("people_reminders", :id => false) do |t|
t.column :reminder_id, :integer
@@ -9,4 +9,4 @@ class InnocentJointable < ActiveRecord::Migration
def self.down
drop_table "people_reminders"
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/migrations/valid/1_people_have_last_names.rb b/activerecord/test/migrations/interleaved/pass_2/1_interleaved_people_have_last_names.rb
index 81af5fef5e..c6c94213a0 100644
--- a/activerecord/test/migrations/valid/1_people_have_last_names.rb
+++ b/activerecord/test/migrations/interleaved/pass_2/1_interleaved_people_have_last_names.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class InterleavedPeopleHaveLastNames < ActiveRecord::Migration
def self.up
add_column "people", "last_name", :string
end
@@ -6,4 +6,4 @@ class PeopleHaveLastNames < ActiveRecord::Migration
def self.down
remove_column "people", "last_name"
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/migrations/interleaved/pass_3/3_innocent_jointable.rb b/activerecord/test/migrations/interleaved/pass_2/3_interleaved_innocent_jointable.rb
index 21c9ca5328..bf912fbfc8 100644
--- a/activerecord/test/migrations/interleaved/pass_3/3_innocent_jointable.rb
+++ b/activerecord/test/migrations/interleaved/pass_2/3_interleaved_innocent_jointable.rb
@@ -1,4 +1,4 @@
-class InnocentJointable < ActiveRecord::Migration
+class InterleavedInnocentJointable < ActiveRecord::Migration
def self.up
create_table("people_reminders", :id => false) do |t|
t.column :reminder_id, :integer
@@ -9,4 +9,4 @@ class InnocentJointable < ActiveRecord::Migration
def self.down
drop_table "people_reminders"
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/migrations/interleaved/pass_3/1_people_have_last_names.rb b/activerecord/test/migrations/interleaved/pass_3/1_interleaved_people_have_last_names.rb
index 81af5fef5e..c6c94213a0 100644
--- a/activerecord/test/migrations/interleaved/pass_3/1_people_have_last_names.rb
+++ b/activerecord/test/migrations/interleaved/pass_3/1_interleaved_people_have_last_names.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class InterleavedPeopleHaveLastNames < ActiveRecord::Migration
def self.up
add_column "people", "last_name", :string
end
@@ -6,4 +6,4 @@ class PeopleHaveLastNames < ActiveRecord::Migration
def self.down
remove_column "people", "last_name"
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb b/activerecord/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb
deleted file mode 100644
index 9b1ce9f017..0000000000
--- a/activerecord/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-class IRaiseOnDown < ActiveRecord::Migration
- def self.up
- end
-
- def self.down
- raise
- end
-end \ No newline at end of file
diff --git a/activerecord/test/migrations/interleaved/pass_3/2_interleaved_i_raise_on_down.rb b/activerecord/test/migrations/interleaved/pass_3/2_interleaved_i_raise_on_down.rb
new file mode 100644
index 0000000000..6849995f5e
--- /dev/null
+++ b/activerecord/test/migrations/interleaved/pass_3/2_interleaved_i_raise_on_down.rb
@@ -0,0 +1,8 @@
+class InterleavedIRaiseOnDown < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ raise
+ end
+end
diff --git a/activerecord/test/migrations/interleaved/pass_1/3_innocent_jointable.rb b/activerecord/test/migrations/interleaved/pass_3/3_interleaved_innocent_jointable.rb
index 21c9ca5328..bf912fbfc8 100644
--- a/activerecord/test/migrations/interleaved/pass_1/3_innocent_jointable.rb
+++ b/activerecord/test/migrations/interleaved/pass_3/3_interleaved_innocent_jointable.rb
@@ -1,4 +1,4 @@
-class InnocentJointable < ActiveRecord::Migration
+class InterleavedInnocentJointable < ActiveRecord::Migration
def self.up
create_table("people_reminders", :id => false) do |t|
t.column :reminder_id, :integer
@@ -9,4 +9,4 @@ class InnocentJointable < ActiveRecord::Migration
def self.down
drop_table "people_reminders"
end
-end \ No newline at end of file
+end
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 0000000000..639841f663
--- /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 0000000000..b3d0b30640
--- /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 0000000000..0f048d90f7
--- /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 0000000000..0f048d90f7
--- /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_timestamps/20090101010101_people_have_hobbies.rb b/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb
new file mode 100644
index 0000000000..639841f663
--- /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 0000000000..b3d0b30640
--- /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 0000000000..0f048d90f7
--- /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 0000000000..2b048edbb5
--- /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/interleaved/pass_2/1_people_have_last_names.rb b/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb
index 81af5fef5e..06cb911117 100644
--- a/activerecord/test/migrations/interleaved/pass_2/1_people_have_last_names.rb
+++ b/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class ValidPeopleHaveLastNames < ActiveRecord::Migration
def self.up
add_column "people", "last_name", :string
end
@@ -6,4 +6,4 @@ class PeopleHaveLastNames < ActiveRecord::Migration
def self.down
remove_column "people", "last_name"
end
-end \ No newline at end of file
+end
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 0000000000..1da99ceaba
--- /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 0000000000..cb6d735c8b
--- /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 0000000000..4bd4b4714d
--- /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/author.rb b/activerecord/test/models/author.rb
index 727978431c..e0cbc44265 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -26,6 +26,12 @@ class Author < ActiveRecord::Base
has_many :comments_with_order_and_conditions, :through => :posts, :source => :comments, :order => 'comments.body', :conditions => "comments.body like 'Thank%'"
has_many :comments_with_include, :through => :posts, :source => :comments, :include => :post
+ has_many :first_posts
+ has_many :comments_on_first_posts, :through => :first_posts, :source => :comments, :order => 'posts.id desc, comments.id asc'
+
+ has_one :first_post
+ has_one :comment_on_first_post, :through => :first_post, :source => :comments, :order => 'posts.id desc, comments.id asc'
+
has_many :thinking_posts, :class_name => 'Post', :conditions => { :title => 'So I was thinking' }, :dependent => :delete_all
has_many :welcome_posts, :class_name => 'Post', :conditions => { :title => 'Welcome to the weblog' }
@@ -72,6 +78,11 @@ class Author < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
+ has_many :named_categories, :through => :categorizations
+
+ has_many :special_categorizations
+ has_many :special_categories, :through => :special_categorizations, :source => :category
+ has_one :special_category, :through => :special_categorizations, :source => :category
has_many :categories_like_general, :through => :categorizations, :source => :category, :class_name => 'Category', :conditions => { :name => 'General' }
@@ -83,16 +94,53 @@ class Author < ActiveRecord::Base
has_many :author_favorites
has_many :favorite_authors, :through => :author_favorites, :order => 'name'
- has_many :tagging, :through => :posts # through polymorphic has_one
- has_many :taggings, :through => :posts, :source => :taggings # through polymorphic has_many
- has_many :tags, :through => :posts # through has_many :through
+ has_many :tagging, :through => :posts
+ has_many :taggings, :through => :posts
+ has_many :tags, :through => :posts
+ has_many :similar_posts, :through => :tags, :source => :tagged_posts, :uniq => true
+ has_many :distinct_tags, :through => :posts, :source => :tags, :select => "DISTINCT tags.*", :order => "tags.name"
has_many :post_categories, :through => :posts, :source => :categories
+ has_many :tagging_tags, :through => :taggings, :source => :tag
+ has_many :tags_with_primary_key, :through => :posts
+
+ has_many :books
+ has_many :subscriptions, :through => :books
+ has_many :subscribers, :through => :subscriptions, :order => "subscribers.nick" # through has_many :through (on through reflection)
+ has_many :distinct_subscribers, :through => :subscriptions, :source => :subscriber, :select => "DISTINCT subscribers.*", :order => "subscribers.nick"
has_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 :author_address, :dependent => :destroy
+ 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 :post_categories, :through => :posts, :source => :categories
+ has_many :category_post_comments, :through => :categories, :source => :post_comments
+
+ has_many :misc_posts, :class_name => 'Post',
+ :conditions => { :posts => { :title => ['misc post by bob', 'misc post by mary'] } }
+ has_many :misc_post_first_blue_tags, :through => :misc_posts, :source => :first_blue_tags
+
+ has_many :misc_post_first_blue_tags_2, :through => :posts, :source => :first_blue_tags_2,
+ :conditions => { :posts => { :title => ['misc post by bob', 'misc post by mary'] } }
+
+ scope :relation_include_posts, includes(:posts)
+ scope :relation_include_tags, includes(:tags)
+
attr_accessor :post_log
after_initialize :set_post_log
diff --git a/activerecord/test/models/book.rb b/activerecord/test/models/book.rb
index 1e030b4f59..d27d0af77c 100644
--- a/activerecord/test/models/book.rb
+++ b/activerecord/test/models/book.rb
@@ -1,4 +1,6 @@
class Book < ActiveRecord::Base
+ has_many :authors
+
has_many :citations, :foreign_key => 'book1_id'
has_many :references, :through => :citations, :source => :reference_of, :uniq => true
diff --git a/activerecord/test/models/boolean.rb b/activerecord/test/models/boolean.rb
new file mode 100644
index 0000000000..7bae22e5f9
--- /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 0000000000..7178bb0d00
--- /dev/null
+++ b/activerecord/test/models/bulb.rb
@@ -0,0 +1,14 @@
+class Bulb < ActiveRecord::Base
+
+ default_scope :conditions => {:name => 'defaulty' }
+
+ belongs_to :car
+
+ attr_reader :scoped_methods_after_initialize
+
+ after_initialize :record_scoped_methods_after_initialize
+ def record_scoped_methods_after_initialize
+ @scoped_methods_after_initialize = self.class.scoped_methods.dup
+ end
+
+end
diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb
index 1101180a67..e7db3d3423 100644
--- a/activerecord/test/models/car.rb
+++ b/activerecord/test/models/car.rb
@@ -1,4 +1,22 @@
class Car < ActiveRecord::Base
+
+ has_many :bulbs
+ has_many :tyres
has_many :engines
has_many :wheels, :as => :wheelable
+
+ scope :incl_tyres, includes(:tyres)
+ scope :incl_engines, includes(:engines)
+
+ scope :order_using_new_style, order('name asc')
+ scope :order_using_old_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
index 10594323ff..09489b8ea4 100644
--- a/activerecord/test/models/categorization.rb
+++ b/activerecord/test/models/categorization.rb
@@ -1,5 +1,20 @@
class Categorization < ActiveRecord::Base
belongs_to :post
belongs_to :category
+ belongs_to :named_category, :class_name => 'Category', :foreign_key => :named_category_name, :primary_key => :name
belongs_to :author
-end \ No newline at end of file
+
+ has_many :post_taggings, :through => :author, :source => :taggings
+
+ belongs_to :author_using_custom_pk, :class_name => 'Author', :foreign_key => :author_id, :primary_key => :author_address_extra_id
+ has_many :authors_using_custom_pk, :class_name => 'Author', :foreign_key => :id, :primary_key => :category_id
+end
+
+class SpecialCategorization < ActiveRecord::Base
+ self.table_name = 'categorizations'
+
+ default_scope where(:special => true)
+
+ belongs_to :author
+ belongs_to :category
+end
diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb
index 48415846dd..02b85fd38a 100644
--- a/activerecord/test/models/category.rb
+++ b/activerecord/test/models/category.rb
@@ -22,7 +22,12 @@ class Category < ActiveRecord::Base
end
has_many :categorizations
- has_many :authors, :through => :categorizations, :select => 'authors.*, categorizations.post_id'
+ has_many :post_comments, :through => :posts, :source => :comments
+
+ has_many :authors, :through => :categorizations
+ has_many :authors_with_select, :through => :categorizations, :source => :author, :select => 'authors.*, categorizations.post_id'
+
+ scope :general, :conditions => { :name => 'General' }
end
class SpecialCategory < Category
diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb
index 6e7cdd643a..24a65b0f2f 100644
--- a/activerecord/test/models/club.rb
+++ b/activerecord/test/models/club.rb
@@ -1,13 +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 \ No newline at end of file
+end
diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb
index 9f6e2d3b71..2a4c37089a 100644
--- a/activerecord/test/models/comment.rb
+++ b/activerecord/test/models/comment.rb
@@ -1,12 +1,14 @@
class Comment < ActiveRecord::Base
scope :limit_by, lambda {|l| limit(l) }
scope :containing_the_letter_e, :conditions => "comments.body LIKE '%e%'"
+ scope :not_again, where("comments.body NOT LIKE '%again%'")
scope :for_first_post, :conditions => { :post_id => 1 }
scope :for_first_author,
:joins => :post,
:conditions => { "posts.author_id" => 1 }
belongs_to :post, :counter_cache => true
+ has_many :ratings
def self.what_are_you
'a comment...'
@@ -15,6 +17,11 @@ class Comment < ActiveRecord::Base
def self.search_by_type(q)
self.find(:all, :conditions => ["#{QUOTED_TYPE} = ?", q])
end
+
+ def self.all_as_method
+ all
+ end
+ scope :all_as_scope, {}
end
class SpecialComment < Comment
@@ -23,6 +30,9 @@ class SpecialComment < Comment
end
end
+class SubSpecialComment < SpecialComment
+end
+
class VerySpecialComment < Comment
def self.what_are_you
'a very special comment...'
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index be6dd71e3b..e0b30efd51 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -38,7 +38,9 @@ end
class Firm < Company
has_many :clients, :order => "id", :dependent => :destroy, :counter_sql =>
"SELECT COUNT(*) FROM companies WHERE firm_id = 1 " +
- "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )"
+ "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )",
+ :before_remove => :log_before_remove,
+ :after_remove => :log_after_remove
has_many :unsorted_clients, :class_name => "Client"
has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC"
has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id"
@@ -46,20 +48,16 @@ class Firm < Company
has_many :dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :destroy
has_many :exclusively_dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all
has_many :limited_clients, :class_name => "Client", :limit => 1
+ has_many :clients_with_interpolated_conditions, :class_name => "Client", :conditions => proc { "rating > #{rating}" }
has_many :clients_like_ms, :conditions => "name = 'Microsoft'", :class_name => "Client", :order => "id"
- has_many :clients_with_interpolated_conditions, :class_name => "Client", :conditions => 'rating > #{rating}'
has_many :clients_like_ms_with_hash_conditions, :conditions => { :name => 'Microsoft' }, :class_name => "Client", :order => "id"
- has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}'
- has_many :clients_using_multiline_sql, :class_name => "Client", :finder_sql => '
- SELECT
- companies.*
- FROM companies WHERE companies.client_of = #{id}'
+ has_many :clients_using_sql, :class_name => "Client", :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" }
has_many :clients_using_counter_sql, :class_name => "Client",
- :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}',
- :counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = #{id}'
+ :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id} " },
+ :counter_sql => proc { "SELECT COUNT(*) FROM companies WHERE client_of = #{id}" }
has_many :clients_using_zero_counter_sql, :class_name => "Client",
- :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}',
- :counter_sql => 'SELECT 0 FROM companies WHERE client_of = #{id}'
+ :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" },
+ :counter_sql => proc { "SELECT 0 FROM companies WHERE client_of = #{id}" }
has_many :no_clients_using_counter_sql, :class_name => "Client",
:finder_sql => 'SELECT * FROM companies WHERE client_of = 1000',
:counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = 1000'
@@ -88,6 +86,19 @@ class Firm < Company
has_one :unautosaved_account, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false
has_many :accounts
has_many :unautosaved_accounts, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false
+
+ def log
+ @log ||= []
+ end
+
+ private
+ def log_before_remove(record)
+ log << "before_remove#{record.id}"
+ end
+
+ def log_after_remove(record)
+ log << "after_remove#{record.id}"
+ end
end
class DependentFirm < Company
@@ -107,7 +118,11 @@ class Client < Company
belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of"
belongs_to :firm_with_condition, :class_name => "Firm", :foreign_key => "client_of", :conditions => ["1 = ?", 1]
belongs_to :firm_with_primary_key, :class_name => "Firm", :primary_key => "name", :foreign_key => "firm_name"
+ belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name
belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true
+ belongs_to :bob_firm, :class_name => "Firm", :foreign_key => "client_of", :conditions => { :name => "Bob" }
+ has_many :accounts, :through => :firm
+ belongs_to :account
# Record destruction so we can test whether firm.clients.clear has
# is calling client.destroy, deleting from the database, or setting
diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb
index 975a885331..e081eee661 100644
--- a/activerecord/test/models/contact.rb
+++ b/activerecord/test/models/contact.rb
@@ -1,8 +1,14 @@
class Contact < ActiveRecord::Base
+ establish_connection(:adapter => 'fake')
+
+ connection.tables = ['contacts']
+ connection.primary_keys = {
+ 'contacts' => 'id'
+ }
+
# mock out self.columns so no pesky db is needed for these tests
def self.column(name, sql_type = nil, options = {})
- @columns ||= []
- @columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], sql_type.to_s, options[:null])
+ connection.merge_column('contacts', name, sql_type, options)
end
column :name, :string
diff --git a/activerecord/test/models/contract.rb b/activerecord/test/models/contract.rb
index 606c99cd4e..94fd48e12a 100644
--- a/activerecord/test/models/contract.rb
+++ b/activerecord/test/models/contract.rb
@@ -1,4 +1,4 @@
class Contract < ActiveRecord::Base
belongs_to :company
belongs_to :developer
-end \ No newline at end of file
+end
diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb
index e258ccdb6c..777f6b5ba0 100644
--- a/activerecord/test/models/customer.rb
+++ b/activerecord/test/models/customer.rb
@@ -70,4 +70,4 @@ class Fullname
def to_s
"#{first} #{last.upcase}"
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
index c61c583c1d..32d060cf09 100644
--- a/activerecord/test/models/developer.rb
+++ b/activerecord/test/models/developer.rb
@@ -56,7 +56,7 @@ class Developer < ActiveRecord::Base
audit_logs.build :message => message
end
- def self.all_johns
+ def self.all_johns
self.with_exclusive_scope :find => where(:name => 'John') do
self.all
end
@@ -87,8 +87,7 @@ end
class DeveloperOrderedBySalary < ActiveRecord::Base
self.table_name = 'developers'
default_scope :order => 'salary DESC'
- scope :by_name, :order => 'name DESC'
- scope :reordered_by_name, reorder('name DESC')
+ scope :by_name, order('name DESC')
def self.all_ordered_by_name
with_scope(:find => { :order => 'name DESC' }) do
diff --git a/activerecord/test/models/engine.rb b/activerecord/test/models/engine.rb
index 751c3f02d1..851ff8c22b 100644
--- a/activerecord/test/models/engine.rb
+++ b/activerecord/test/models/engine.rb
@@ -1,3 +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/essay.rb b/activerecord/test/models/essay.rb
index 6c28f5e49b..ec4b982b5b 100644
--- a/activerecord/test/models/essay.rb
+++ b/activerecord/test/models/essay.rb
@@ -1,3 +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/eye.rb b/activerecord/test/models/eye.rb
new file mode 100644
index 0000000000..dc8ae2b3f6
--- /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/job.rb b/activerecord/test/models/job.rb
index 3333a02e27..f7b0e787b1 100644
--- a/activerecord/test/models/job.rb
+++ b/activerecord/test/models/job.rb
@@ -2,4 +2,6 @@ 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
index 3978abc2ba..d7f01e59e6 100644
--- a/activerecord/test/models/joke.rb
+++ b/activerecord/test/models/joke.rb
@@ -1,3 +1,7 @@
class Joke < ActiveRecord::Base
set_table_name 'funny_jokes'
end
+
+class GoodJoke < ActiveRecord::Base
+ set_table_name 'funny_jokes'
+end
diff --git a/activerecord/test/models/lesson.rb b/activerecord/test/models/lesson.rb
new file mode 100644
index 0000000000..4c88153068
--- /dev/null
+++ b/activerecord/test/models/lesson.rb
@@ -0,0 +1,11 @@
+class LessonError < Exception
+end
+
+class Lesson < ActiveRecord::Base
+ has_and_belongs_to_many :students
+ before_destroy :ensure_no_students
+
+ def ensure_no_students
+ raise LessonError unless students.empty?
+ end
+end
diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb
index 255fb569d7..991e0e051f 100644
--- a/activerecord/test/models/member.rb
+++ b/activerecord/test/models/member.rb
@@ -1,12 +1,30 @@
class Member < ActiveRecord::Base
has_one :current_membership
- has_many :memberships
+ has_one :membership
has_many :fellow_members, :through => :club, :source => :members
has_one :club, :through => :current_membership
- has_one :favourite_club, :through => :memberships, :conditions => ["memberships.favourite = ?", true], :source => :club
+ has_one :favourite_club, :through => :membership, :conditions => ["memberships.favourite = ?", true], :source => :club
+ has_one :hairy_club, :through => :membership, :conditions => {:clubs => {:name => "Moustache and Eyebrow Fancier Club"}}, :source => :club
has_one :sponsor, :as => :sponsorable
has_one :sponsor_club, :through => :sponsor
has_one :member_detail
has_one :organization, :through => :member_detail
belongs_to :member_type
-end \ No newline at end of file
+
+ 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
+ has_one :club_through_many, :through => :current_memberships, :source => :club
+
+ has_many :current_memberships, :conditions => { :favourite => true }
+ has_many :clubs, :through => :current_memberships
+end
diff --git a/activerecord/test/models/member_detail.rb b/activerecord/test/models/member_detail.rb
index 94f59e5794..fe619f8732 100644
--- a/activerecord/test/models/member_detail.rb
+++ b/activerecord/test/models/member_detail.rb
@@ -2,4 +2,6 @@ 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/minivan.rb b/activerecord/test/models/minivan.rb
index 602438d16f..830cdb5796 100644
--- a/activerecord/test/models/minivan.rb
+++ b/activerecord/test/models/minivan.rb
@@ -1,9 +1,9 @@
class Minivan < ActiveRecord::Base
set_primary_key :minivan_id
-
+
belongs_to :speedometer
has_one :dashboard, :through => :speedometer
-
+
attr_readonly :color
end
diff --git a/activerecord/test/models/organization.rb b/activerecord/test/models/organization.rb
index 1da342a0bd..4a4111833f 100644
--- a/activerecord/test/models/organization.rb
+++ b/activerecord/test/models/organization.rb
@@ -2,5 +2,11 @@ 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 \ No newline at end of file
+end
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index 951ec93c53..ad59d12672 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -1,19 +1,50 @@
class Person < ActiveRecord::Base
has_many :readers
+ has_one :reader
+
has_many :posts, :through => :readers
has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments, :conditions => 'comments.id is null'
has_many :references
has_many :bad_references
has_many :fixed_bad_references, :conditions => { :favourite => true }, :class_name => 'BadReference'
- has_many :jobs, :through => :references
has_one :favourite_reference, :class_name => 'Reference', :conditions => ['favourite=?', true]
has_many :posts_with_comments_sorted_by_comment_id, :through => :readers, :source => :post, :include => :comments, :order => 'comments.id'
+ has_many :jobs, :through => :references
+ has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy
+ has_many :jobs_with_dependent_delete_all, :source => :job, :through => :references, :dependent => :delete_all
+ has_many :jobs_with_dependent_nullify, :source => :job, :through => :references, :dependent => :nullify
+
belongs_to :primary_contact, :class_name => 'Person'
has_many :agents, :class_name => 'Person', :foreign_key => 'primary_contact_id'
+ has_many :agents_of_agents, :through => :agents, :source => :agents
belongs_to :number1_fan, :class_name => 'Person'
+ has_many :agents_posts, :through => :agents, :source => :posts
+ has_many :agents_posts_authors, :through => :agents_posts, :source => :author
+
scope :males, :conditions => { :gender => 'M' }
scope :females, :conditions => { :gender => 'F' }
end
+
+class PersonWithDependentDestroyJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :destroy
+end
+
+class PersonWithDependentDeleteAllJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :delete_all
+end
+
+class PersonWithDependentNullifyJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :nullify
+end
diff --git a/activerecord/test/models/pet.rb b/activerecord/test/models/pet.rb
index a8bf94dd86..113826756a 100644
--- a/activerecord/test/models/pet.rb
+++ b/activerecord/test/models/pet.rb
@@ -1,5 +1,17 @@
class Pet < ActiveRecord::Base
+
+ attr_accessor :current_user
+
set_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
index d89c8cf381..0d3f62bb33 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -34,6 +34,8 @@ class Pirate < ActiveRecord::Base
:after_remove => proc {|p,b| p.ship_log << "after_removing_proc_bird_#{b.id}"}
has_many :birds_with_reject_all_blank, :class_name => "Bird"
+ has_one :bulb, :foreign_key => :car_id
+
accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
accepts_nested_attributes_for :update_only_ship, :update_only => true
@@ -48,7 +50,7 @@ class Pirate < ActiveRecord::Base
end
def reject_empty_ships_on_create(attributes)
- attributes.delete('_reject_me_if_new').present? && new_record?
+ attributes.delete('_reject_me_if_new').present? && !persisted?
end
attr_accessor :cancel_save_from_callback
@@ -78,3 +80,7 @@ class Pirate < ActiveRecord::Base
ship_log << "#{callback}_#{record.class.name.downcase}_#{record.id || '<new>'}"
end
end
+
+class DestructivePirate < Pirate
+ has_one :dependent_ship, :class_name => 'Ship', :foreign_key => :pirate_id, :dependent => :destroy
+end
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index 6c7b93be87..82894a3d57 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -38,40 +38,73 @@ class Post < ActiveRecord::Base
end
has_many :author_favorites, :through => :author
+ has_many :author_categorizations, :through => :author, :source => :categorizations
+ has_many :author_addresses, :through => :author
has_many :comments_with_interpolated_conditions, :class_name => 'Comment',
- :conditions => ['#{"#{aliased_table_name}." rescue ""}body = ?', 'Thank you for the welcome']
+ :conditions => proc { ["#{"#{aliased_table_name}." rescue ""}body = ?", 'Thank you for the welcome'] }
has_one :very_special_comment
has_one :very_special_comment_with_post, :class_name => "VerySpecialComment", :include => :post
has_many :special_comments
has_many :nonexistant_comments, :class_name => 'Comment', :conditions => 'comments.id < 0'
+ 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
- find :all, :select => 'tags.*, authors.id as author_id', :include => false,
+ find :all, :select => 'tags.*, authors.id as author_id',
:joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id'
end
end
- has_many :misc_tags, :through => :taggings, :source => :tag, :conditions => "tags.name = 'Misc'"
+ has_many :interpolated_taggings, :class_name => 'Tagging', :as => :taggable, :conditions => proc { "1 = #{1}" }
+ has_many :interpolated_tags, :through => :taggings
+ has_many :interpolated_tags_2, :through => :interpolated_taggings, :source => :tag
+
+ has_many :taggings_with_delete_all, :class_name => 'Tagging', :as => :taggable, :dependent => :delete_all
+ has_many :taggings_with_destroy, :class_name => 'Tagging', :as => :taggable, :dependent => :destroy
+
+ has_many :tags_with_destroy, :through => :taggings, :source => :tag, :dependent => :destroy
+ has_many :tags_with_nullify, :through => :taggings, :source => :tag, :dependent => :nullify
+
+ has_many :misc_tags, :through => :taggings, :source => :tag, :conditions => { :tags => { :name => 'Misc' } }
has_many :funky_tags, :through => :taggings, :source => :tag
has_many :super_tags, :through => :taggings
+ has_many :tags_with_primary_key, :through => :taggings, :source => :tag_with_primary_key
has_one :tagging, :as => :taggable
+ has_many :first_taggings, :as => :taggable, :class_name => 'Tagging', :conditions => { :taggings => { :comment => 'first' } }
+ has_many :first_blue_tags, :through => :first_taggings, :source => :tag, :conditions => { :tags => { :name => 'Blue' } }
+
+ has_many :first_blue_tags_2, :through => :taggings, :source => :blue_tag, :conditions => { :taggings => { :comment => 'first' } }
+
has_many :invalid_taggings, :as => :taggable, :class_name => "Tagging", :conditions => 'taggings.id < 0'
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 :readers_with_person, :include => :person, :class_name => "Reader"
has_many :people, :through => :readers
+ has_many :single_people, :through => :readers
has_many :people_with_callbacks, :source=>:person, :through => :readers,
:before_add => lambda {|owner, reader| log(:added, :before, reader.first_name) },
:after_add => lambda {|owner, reader| log(:added, :after, reader.first_name) },
@@ -87,7 +120,7 @@ class Post < ActiveRecord::Base
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]
@@ -113,3 +146,16 @@ class PostWithComment < ActiveRecord::Base
self.table_name = 'posts'
default_scope where("posts.comments_count > 0").order("posts.comments_count ASC")
end
+
+class PostForAuthor < ActiveRecord::Base
+ self.table_name = 'posts'
+ cattr_accessor :selected_author
+ default_scope lambda { where(:author_id => PostForAuthor.selected_author) }
+end
+
+class FirstPost < ActiveRecord::Base
+ self.table_name = 'posts'
+ default_scope where(:id => 1)
+ has_many :comments, :foreign_key => :post_id
+ has_one :comment, :foreign_key => :post_id
+end
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
index 416032cb75..efe1ce67da 100644
--- a/activerecord/test/models/project.rb
+++ b/activerecord/test/models/project.rb
@@ -7,14 +7,15 @@ class Project < ActiveRecord::Base
has_and_belongs_to_many :developers_named_david, :class_name => "Developer", :conditions => "name = 'David'", :uniq => true
has_and_belongs_to_many :developers_named_david_with_hash_conditions, :class_name => "Developer", :conditions => { :name => 'David' }, :uniq => true
has_and_belongs_to_many :salaried_developers, :class_name => "Developer", :conditions => "salary > 0"
- has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => 'SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id'
- has_and_belongs_to_many :developers_with_multiline_finder_sql, :class_name => "Developer", :finder_sql => '
- SELECT
- t.*, j.*
- FROM
- developers_projects j,
- developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id'
- has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => "DELETE FROM developers_projects WHERE project_id = \#{id} AND developer_id = \#{record.id}"
+ has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => proc { "SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id" }
+ has_and_belongs_to_many :developers_with_multiline_finder_sql, :class_name => "Developer", :finder_sql => proc {
+ "SELECT
+ t.*, j.*
+ FROM
+ developers_projects j,
+ developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id"
+ }
+ has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => proc { |record| "DELETE FROM developers_projects WHERE project_id = #{id} AND developer_id = #{record.id}" }
has_and_belongs_to_many :developers_with_callbacks, :class_name => "Developer", :before_add => Proc.new {|o, r| o.developers_log << "before_adding#{r.id || '<new>'}"},
:after_add => Proc.new {|o, r| o.developers_log << "after_adding#{r.id || '<new>'}"},
:before_remove => Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"},
@@ -28,6 +29,10 @@ class Project < ActiveRecord::Base
@developers_log = []
end
+ def self.all_as_method
+ all
+ end
+ scope :all_as_scope, {}
end
class SpecialProject < Project
diff --git a/activerecord/test/models/rating.rb b/activerecord/test/models/rating.rb
new file mode 100644
index 0000000000..25a52c4ad7
--- /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
index 27527bf566..0207a2bd92 100644
--- a/activerecord/test/models/reader.rb
+++ b/activerecord/test/models/reader.rb
@@ -1,4 +1,5 @@
class Reader < ActiveRecord::Base
belongs_to :post
- belongs_to :person
+ belongs_to :person, :inverse_of => :readers
+ belongs_to :single_person, :class_name => 'Person', :foreign_key => :person_id, :inverse_of => :reader
end
diff --git a/activerecord/test/models/reference.rb b/activerecord/test/models/reference.rb
index 4a17c936f5..e33a0f2acc 100644
--- a/activerecord/test/models/reference.rb
+++ b/activerecord/test/models/reference.rb
@@ -1,6 +1,20 @@
class Reference < ActiveRecord::Base
belongs_to :person
belongs_to :job
+
+ has_many :agents_posts_authors, :through => :person
+
+ class << self
+ attr_accessor :make_comments
+ end
+
+ before_destroy :make_comments
+
+ def make_comments
+ if self.class.make_comments
+ person.update_attributes :comments => "Reference destroyed"
+ end
+ end
end
class BadReference < ActiveRecord::Base
diff --git a/activerecord/test/models/reply.rb b/activerecord/test/models/reply.rb
index 110d540120..6adfe0ae3c 100644
--- a/activerecord/test/models/reply.rb
+++ b/activerecord/test/models/reply.rb
@@ -10,6 +10,13 @@ class Reply < Topic
attr_accessible :title, :author_name, :author_email_address, :written_on, :content, :last_read, :parent_title
end
+class UniqueReply < Reply
+ validates_uniqueness_of :content, :scope => 'parent_id'
+end
+
+class SillyUniqueReply < UniqueReply
+end
+
class WrongReply < Reply
validate :errors_on_empty_content
validate :title_is_wrong_create, :on => :create
diff --git a/activerecord/test/models/shop.rb b/activerecord/test/models/shop.rb
index b232185693..81414227ea 100644
--- a/activerecord/test/models/shop.rb
+++ b/activerecord/test/models/shop.rb
@@ -6,7 +6,7 @@ module Shop
class Product < ActiveRecord::Base
has_many :variants, :dependent => :delete_all
end
-
+
class Variant < ActiveRecord::Base
end
end
diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb
index 50c2c2d76c..aa4a3638fd 100644
--- a/activerecord/test/models/sponsor.rb
+++ b/activerecord/test/models/sponsor.rb
@@ -1,4 +1,7 @@
class Sponsor < ActiveRecord::Base
belongs_to :sponsor_club, :class_name => "Club", :foreign_key => "club_id"
belongs_to :sponsorable, :polymorphic => true
-end \ No newline at end of file
+ belongs_to :thing, :polymorphic => true, :foreign_type => :sponsorable_type, :foreign_key => :sponsorable_id
+ belongs_to :sponsorable_with_conditions, :polymorphic => true,
+ :foreign_type => 'sponsorable_type', :foreign_key => 'sponsorable_id', :conditions => {:name => 'Ernie'}
+end
diff --git a/activerecord/test/models/student.rb b/activerecord/test/models/student.rb
new file mode 100644
index 0000000000..f459f2a9a3
--- /dev/null
+++ b/activerecord/test/models/student.rb
@@ -0,0 +1,3 @@
+class Student < ActiveRecord::Base
+ has_and_belongs_to_many :lessons
+end
diff --git a/activerecord/test/models/subject.rb b/activerecord/test/models/subject.rb
index 1b9d8107f8..8e28f8b86b 100644
--- a/activerecord/test/models/subject.rb
+++ b/activerecord/test/models/subject.rb
@@ -1,12 +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
- # added initialization of author_email_address in the same way as in Topic class
- # as otherwise synonym test was failing
- def after_initialize
- if self.new_record?
+ def set_email_address
+ unless self.persisted?
self.author_email_address = 'test@test.com'
end
end
+
end
diff --git a/activerecord/test/models/tagging.rb b/activerecord/test/models/tagging.rb
index a1fa1a9750..ef323df158 100644
--- a/activerecord/test/models/tagging.rb
+++ b/activerecord/test/models/tagging.rb
@@ -6,5 +6,9 @@ class Tagging < ActiveRecord::Base
belongs_to :tag, :include => :tagging
belongs_to :super_tag, :class_name => 'Tag', :foreign_key => 'super_tag_id'
belongs_to :invalid_tag, :class_name => 'Tag', :foreign_key => 'tag_id'
+ belongs_to :blue_tag, :class_name => 'Tag', :foreign_key => :tag_id, :conditions => { :tags => { :name => 'Blue' } }
+ belongs_to :tag_with_primary_key, :class_name => 'Tag', :foreign_key => :tag_id, :primary_key => :custom_primary_key
+ belongs_to :interpolated_tag, :class_name => 'Tag', :foreign_key => :tag_id, :conditions => proc { "1 = #{1}" }
belongs_to :taggable, :polymorphic => true, :counter_cache => true
-end \ No newline at end of file
+ has_many :things, :through => :taggable
+end
diff --git a/activerecord/test/models/task.rb b/activerecord/test/models/task.rb
index ee0282c79b..e36989dd56 100644
--- a/activerecord/test/models/task.rb
+++ b/activerecord/test/models/task.rb
@@ -1,3 +1,5 @@
class Task < ActiveRecord::Base
-
+ def updated_at
+ ending
+ end
end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
index 617f01b47d..6440dbe8ab 100644
--- a/activerecord/test/models/topic.rb
+++ b/activerecord/test/models/topic.rb
@@ -9,7 +9,7 @@ class Topic < ActiveRecord::Base
scope :rejected, :conditions => {:approved => false}
scope :by_lifo, :conditions => {:author_name => 'lifo'}
-
+
scope :approved_as_hash_condition, :conditions => {:topics => {:approved => true}}
scope 'approved_as_string', :conditions => {:approved => true}
scope :replied, :conditions => ['replies_count > 0']
@@ -18,6 +18,13 @@ class Topic < ActiveRecord::Base
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
@@ -38,6 +45,10 @@ class Topic < ActiveRecord::Base
has_many :replies, :dependent => :destroy, :foreign_key => "parent_id"
has_many :replies_with_primary_key, :class_name => "Reply", :dependent => :destroy, :primary_key => "title", :foreign_key => "parent_title"
+
+ has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
+ has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
+
serialize :content
before_create :default_written_on
@@ -82,7 +93,7 @@ class Topic < ActiveRecord::Base
end
def set_email_address
- if self.new_record?
+ unless self.persisted?
self.author_email_address = 'test@test.com'
end
end
diff --git a/activerecord/test/models/traffic_light.rb b/activerecord/test/models/traffic_light.rb
new file mode 100644
index 0000000000..228f3f7bd4
--- /dev/null
+++ b/activerecord/test/models/traffic_light.rb
@@ -0,0 +1,3 @@
+class TrafficLight < ActiveRecord::Base
+ serialize :state, Array
+end
diff --git a/activerecord/test/models/tyre.rb b/activerecord/test/models/tyre.rb
new file mode 100644
index 0000000000..bc3444aa7d
--- /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/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb
index c78d99f4af..30e1c5a167 100644
--- a/activerecord/test/schema/mysql_specific_schema.rb
+++ b/activerecord/test/schema/mysql_specific_schema.rb
@@ -21,4 +21,15 @@ BEGIN
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
+
end
diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb
index 065d8cfe98..f38f4f3b44 100644
--- a/activerecord/test/schema/postgresql_specific_schema.rb
+++ b/activerecord/test/schema/postgresql_specific_schema.rb
@@ -100,7 +100,7 @@ _SQL
obj_id OID
);
_SQL
-
+
execute <<_SQL
CREATE TABLE postgresql_timestamp_with_zones (
id SERIAL PRIMARY KEY,
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index fc3810f82b..362475de36 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -18,8 +18,13 @@ ActiveRecord::Schema.define do
end
- # Please keep these create table statements in alphabetical order
- # unless the ordering matters. In which case, define them below
+ # ------------------------------------------------------------------- #
+ # #
+ # 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
@@ -44,6 +49,8 @@ ActiveRecord::Schema.define do
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|
@@ -54,7 +61,6 @@ ActiveRecord::Schema.define do
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
@@ -71,13 +77,19 @@ ActiveRecord::Schema.define do
end
create_table :books, :force => true do |t|
+ t.integer :author_id
t.column :name, :string
end
- create_table :booleantests, :force => true do |t|
+ create_table :booleans, :force => true do |t|
t.boolean :value
end
+ create_table :bulbs, :force => true do |t|
+ t.integer :car_id
+ t.string :name
+ end
+
create_table "CamelCase", :force => true do |t|
t.string :name
end
@@ -101,8 +113,10 @@ ActiveRecord::Schema.define do
create_table :categorizations, :force => true do |t|
t.column :category_id, :integer
+ t.string :named_category_name
t.column :post_id, :integer
t.column :author_id, :integer
+ t.column :special, :boolean
end
create_table :citations, :force => true do |t|
@@ -112,6 +126,7 @@ ActiveRecord::Schema.define do
create_table :clubs, :force => true do |t|
t.string :name
+ t.integer :category_id
end
create_table :collections, :force => true do |t|
@@ -132,6 +147,7 @@ ActiveRecord::Schema.define do
t.text :body, :null => false
end
t.string :type
+ t.integer :taggings_count, :default => 0
end
create_table :companies, :force => true do |t|
@@ -142,6 +158,7 @@ ActiveRecord::Schema.define do
t.string :name
t.integer :client_of
t.integer :rating, :default => 1
+ t.integer :account_id
end
add_index :companies, [:firm_id, :type, :rating, :ruby_type], :name => "company_index"
@@ -164,7 +181,7 @@ ActiveRecord::Schema.define do
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
@@ -203,28 +220,32 @@ ActiveRecord::Schema.define do
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 :goofy_string_id, :force => true, :id => false do |t|
t.string :id, :null => false
t.string :info
end
- create_table :invoices, :force => true do |t|
- t.integer :balance
- t.datetime :updated_at
- end
-
- create_table :items, :force => true do |t|
- t.column :name, :integer
+ create_table :guids, :force => true do |t|
+ t.column :key, :string
end
create_table :inept_wizards, :force => true do |t|
@@ -233,6 +254,26 @@ ActiveRecord::Schema.define do
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
@@ -248,6 +289,15 @@ ActiveRecord::Schema.define do
t.integer :version, :null => false, :default => 0
end
+ create_table :lessons, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :lessons_students, :id => false, :force => true do |t|
+ t.references :lesson
+ t.references :student
+ end
+
create_table :line_items, :force => true do |t|
t.integer :invoice_id
t.integer :amount
@@ -289,13 +339,6 @@ ActiveRecord::Schema.define do
t.string :name
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 :minivans, :force => true, :id => false do |t|
t.string :minivan_id
t.string :name
@@ -334,8 +377,8 @@ ActiveRecord::Schema.define do
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 supports precision up to 38
- if current_adapter?(:OracleAdapter)
+ # 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
@@ -356,9 +399,9 @@ ActiveRecord::Schema.define do
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
@@ -393,6 +436,8 @@ ActiveRecord::Schema.define do
t.string :gender, :limit => 1
t.references :number1_fan
t.integer :lock_version, :null => false, :default => 0
+ t.string :comments
+ t.timestamps
end
create_table :pets, :primary_key => :pet_id ,:force => true do |t|
@@ -421,6 +466,11 @@ ActiveRecord::Schema.define do
t.string :type
t.integer :comments_count, :default => 0
t.integer :taggings_count, :default => 0
+ t.integer :taggings_with_delete_all_count, :default => 0
+ t.integer :taggings_with_destroy_count, :default => 0
+ t.integer :tags_count, :default => 0
+ t.integer :tags_with_destroy_count, :default => 0
+ t.integer :tags_with_nullify_count, :default => 0
end
create_table :price_estimates, :force => true do |t|
@@ -439,12 +489,24 @@ ActiveRecord::Schema.define do
t.string :type
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
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
@@ -465,7 +527,7 @@ ActiveRecord::Schema.define do
t.string :name
t.integer :ship_id
end
-
+
create_table :speedometers, :force => true, :id => false do |t|
t.string :speedometer_id
t.string :name
@@ -478,6 +540,10 @@ ActiveRecord::Schema.define do
t.string :sponsorable_type
end
+ create_table :students, :force => true do |t|
+ t.string :name
+ end
+
create_table :subscribers, :force => true, :id => false do |t|
t.string :nick, :null => false
t.string :name
@@ -489,6 +555,19 @@ ActiveRecord::Schema.define do
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
@@ -514,18 +593,7 @@ ActiveRecord::Schema.define do
t.string :parent_title
t.string :type
t.string :group
- 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
- end
-
- create_table :tags, :force => true do |t|
- t.column :name, :string
- t.column :taggings_count, :integer, :default => 0
+ t.timestamps
end
create_table :toys, :primary_key => :toy_id ,:force => true do |t|
@@ -547,6 +615,10 @@ ActiveRecord::Schema.define do
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
@@ -564,17 +636,6 @@ ActiveRecord::Schema.define do
create_table(t, :force => true) { }
end
- create_table :guids, :force => true do |t|
- t.column :key, :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
-
# 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
@@ -629,7 +690,9 @@ ActiveRecord::Schema.define do
t.integer :molecule_id
t.string :name
end
-
+ create_table :weirds, :force => true do |t|
+ t.string 'a$b'
+ end
except 'SQLite' do
# fk_test_has_fk should be before fk_test_has_pk
diff --git a/activeresource/CHANGELOG b/activeresource/CHANGELOG
index 8fa1b0b4b3..386bafd7de 100644
--- a/activeresource/CHANGELOG
+++ b/activeresource/CHANGELOG
@@ -1,19 +1,18 @@
-*Rails 3.0.0 [release candidate] (July 26th, 2010)*
+*Rails 3.1.0 (unreleased)*
-* No material changes
-
-
-*Rails 3.0.0 [beta 4] (June 8th, 2010)*
+* No changes
-* JSON: set Base.include_root_in_json = true to include a root value in the JSON: {"post": {"title": ...}}. Mirrors the Active Record option. [Santiago Pastorino]
+*Rails 3.0.2 (unreleased)*
+* No changes
-*Rails 3.0.0 [beta 3] (April 13th, 2010)*
+*Rails 3.0.1 (October 15, 2010)*
-* No changes
+* No Changes, just a version bump.
+*Rails 3.0.0 (August 29, 2010)*
-*Rails 3.0.0 [beta 1] (February 4, 2010)*
+* JSON: set Base.include_root_in_json = true to include a root value in the JSON: {"post": {"title": ...}}. Mirrors the Active Record option. [Santiago Pastorino]
* Add support for errors in JSON format. #1956 [Fabien Jakimowicz]
@@ -87,7 +86,7 @@
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, "<person><name>David</name></person>"
end
-
+
Now:
ActiveResource::HttpMock.respond_to.get "/people/1.xml", {}, "<person><name>David</name></person>"
@@ -97,14 +96,14 @@
self.site = "http://app/"
self.format = :json
end
-
+
person = Person.find(1) # => GET http://app/people/1.json
person.name = "David"
person.save # => PUT http://app/people/1.json {name: "David"}
-
+
Person.format = :xml
person.name = "Mary"
- person.save # => PUT http://app/people/1.json <person><name>Mary</name></person>
+ person.save # => PUT http://app/people/1.json <person><name>Mary</name></person>
* Fix reload error when path prefix is used. #8727 [Ian Warshak]
@@ -133,7 +132,7 @@
class Project
headers['X-Token'] = 'foo'
end
-
+
# makes the GET request with the custom X-Token header
Project.find(:all)
@@ -156,7 +155,7 @@
end
assert_kind_of Highrise::Comment, Note.find(1).comments.first
-
+
* Added load_attributes_from_response as a way of loading attributes from other responses than just create [David Heinemeier Hansson]
@@ -248,8 +247,8 @@ d
* Basic validation support [Rick Olson]
- Parses the xml response of ActiveRecord::Errors#to_xml with a similar interface to ActiveRecord::Errors.
-
+ Parses the xml response of ActiveRecord::Errors#to_xml with a similar interface to ActiveRecord::Errors.
+
render :xml => @person.errors.to_xml, :status => '400 Validation Error'
* Deep hashes are converted into collections of resources. [Jeremy Kemper]
@@ -267,12 +266,12 @@ d
* Add support for specifying prefixes.
* Allow overriding of element_name, collection_name, and primary key
* Provide simpler HTTP mock interface for testing
-
+
# rails routing code
map.resources :posts do |post|
post.resources :comments
end
-
+
# ActiveResources
class Post < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000/"
@@ -281,7 +280,7 @@ d
class Comment < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000/posts/:post_id/"
end
-
+
@post = Post.find 5
@comments = Comment.find :all, :post_id => @post.id
diff --git a/activeresource/MIT-LICENSE b/activeresource/MIT-LICENSE
index 1bf965ff1e..216b6e5ba0 100644
--- a/activeresource/MIT-LICENSE
+++ b/activeresource/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2006-2010 David Heinemeier Hansson
+Copyright (c) 2006-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activeresource/README.rdoc b/activeresource/README.rdoc
index 127ac5b4a9..afa25e1676 100644
--- a/activeresource/README.rdoc
+++ b/activeresource/README.rdoc
@@ -9,7 +9,7 @@ in ActionController::Resources).
Active Resource attempts to provide a coherent wrapper object-relational mapping for REST
web services. It follows the same philosophy as Active Record, in that one of its prime aims
-is to reduce the amount of code needed to map to these resources. This is made possible
+is to reduce the amount of code needed to map to these resources. This is made possible
by relying on a number of code- and protocol-based conventions that make it easy for Active Resource
to infer complex relations and structures. These conventions are outlined in detail in the documentation
for ActiveResource::Base.
@@ -30,25 +30,25 @@ that inherits from ActiveResource::Base and providing a <tt>site</tt> class vari
end
Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes
-lifecycle methods that operate against a persistent store.
+life cycle methods that operate against a persistent store.
# Find a person with id = 1
ryan = Person.find(1)
- Person.exists?(1) #=> true
+ Person.exists?(1) # => true
As you can see, the methods are quite similar to Active Record's methods for dealing with database
records. But rather than dealing directly with a database record, you're dealing with HTTP resources (which may or may not be database records).
==== Protocol
-Active Resource is built on a standard XML format for requesting and submitting resources over HTTP. It mirrors the RESTful routing
+Active Resource is built on a standard XML format for requesting and submitting resources over HTTP. It mirrors the RESTful routing
built into Action Controller but will also work with any other REST service that properly implements the protocol.
REST uses HTTP, but unlike "typical" web applications, it makes use of all the verbs available in the HTTP specification:
* GET requests are used for finding and retrieving resources.
* POST requests are used to create new resources.
* PUT requests are used to update existing resources.
-* DELETE requests are used to delete resources.
+* DELETE requests are used to delete resources.
For more information on how this protocol works with Active Resource, see the ActiveResource::Base documentation;
for more general information on REST web services, see the article here[http://en.wikipedia.org/wiki/Representational_State_Transfer].
@@ -69,8 +69,8 @@ for a request for a single element, the XML of that item is expected in response
The XML document that is received is used to build a new object of type Person, with each
XML element becoming an attribute on the object.
- ryan.is_a? Person #=> true
- ryan.attribute1 #=> 'value1'
+ ryan.is_a? Person # => true
+ ryan.attribute1 # => 'value1'
Any complex element (one that contains other elements) becomes its own object:
@@ -81,8 +81,8 @@ Any complex element (one that contains other elements) becomes its own object:
# for GET http://api.people.com:3000/people/1.xml
#
ryan = Person.find(1)
- ryan.complex #=> <Person::Complex::xxxxx>
- ryan.complex.attribute2 #=> 'value2'
+ ryan.complex # => <Person::Complex::xxxxx>
+ ryan.complex.attribute2 # => 'value2'
Collections can also be requested in a similar fashion
@@ -95,9 +95,9 @@ Collections can also be requested in a similar fashion
#
# for GET http://api.people.com:3000/people.xml
#
- people = Person.find(:all)
- people.first #=> <Person::xxx 'first' => 'Ryan' ...>
- people.last #=> <Person::xxx 'first' => 'Jim' ...>
+ people = Person.all
+ people.first # => <Person::xxx 'first' => 'Ryan' ...>
+ people.last # => <Person::xxx 'first' => 'Jim' ...>
==== Create
@@ -111,17 +111,17 @@ as the id of the ARes object.
# is submitted as the body on
#
# POST http://api.people.com:3000/people.xml
- #
+ #
# when save is called on a new Person object. An empty response is
# is expected with a 'Location' header value:
#
# Response (201): Location: http://api.people.com:3000/people/2
#
ryan = Person.new(:first => 'Ryan')
- ryan.new? #=> true
- ryan.save #=> true
- ryan.new? #=> false
- ryan.id #=> 2
+ ryan.new? # => true
+ ryan.save # => true
+ ryan.new? # => false
+ ryan.id # => 2
==== Update
@@ -139,9 +139,9 @@ server side was successful.
# is expected with code (204)
#
ryan = Person.find(1)
- ryan.first #=> 'Ryan'
+ ryan.first # => 'Ryan'
ryan.first = 'Rizzle'
- ryan.save #=> true
+ ryan.save # => true
==== Delete
@@ -155,10 +155,10 @@ Destruction of a resource can be invoked as a class and instance method of the r
# is expected with response code (200)
#
ryan = Person.find(1)
- ryan.destroy #=> true
- ryan.exists? #=> false
- Person.delete(2) #=> true
- Person.exists?(2) #=> false
+ ryan.destroy # => true
+ ryan.exists? # => false
+ Person.delete(2) # => true
+ Person.exists?(2) # => false
You can find more usage information in the ActiveResource::Base documentation.
diff --git a/activeresource/Rakefile b/activeresource/Rakefile
index 2145f1017c..42e450da66 100644..100755
--- a/activeresource/Rakefile
+++ b/activeresource/Rakefile
@@ -1,8 +1,5 @@
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
-require 'rake'
+#!/usr/bin/env rake
require 'rake/testtask'
-require 'rdoc/task'
require 'rake/packagetask'
require 'rake/gempackagetask'
@@ -22,25 +19,11 @@ namespace :test do
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
activesupport_path = "#{File.dirname(__FILE__)}/../activesupport/lib"
Dir.glob("test/**/*_test.rb").all? do |file|
- system(ruby, '-w', "-Ilib:test:#{activesupport_path}", file)
+ sh(ruby, '-w', "-Ilib:test:#{activesupport_path}", file)
end or raise "Failures"
end
end
-# Generate the RDoc documentation
-
-RDoc::Task.new { |rdoc|
- rdoc.rdoc_dir = 'doc'
- rdoc.title = "Active Resource -- Object-oriented REST services"
- rdoc.options << '-f' << 'horo'
- rdoc.options << '--main' << 'README.rdoc'
- rdoc.options << '--charset' << 'utf-8'
- rdoc.rdoc_files.include('README.rdoc', 'CHANGELOG')
- rdoc.rdoc_files.include('lib/**/*.rb')
- rdoc.rdoc_files.exclude('lib/activeresource.rb')
-}
-
-
spec = eval(File.read('activeresource.gemspec'))
Rake::GemPackageTask.new(spec) do |p|
diff --git a/activeresource/lib/active_resource.rb b/activeresource/lib/active_resource.rb
index 3e4a1dd4a1..186865f811 100644
--- a/activeresource/lib/active_resource.rb
+++ b/activeresource/lib/active_resource.rb
@@ -29,6 +29,7 @@ $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include
require 'active_support'
require 'active_model'
+require 'active_resource/version'
module ActiveResource
extend ActiveSupport::Autoload
diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb
index 62420725ad..160763779e 100644
--- a/activeresource/lib/active_resource/base.rb
+++ b/activeresource/lib/active_resource/base.rb
@@ -1,6 +1,6 @@
require 'active_support'
require 'active_support/core_ext/class/attribute_accessors'
-require 'active_support/core_ext/class/inheritable_attributes'
+require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/module/attr_accessor_with_default'
@@ -12,6 +12,7 @@ require 'active_support/core_ext/object/duplicable'
require 'set'
require 'uri'
+require 'active_support/core_ext/uri'
require 'active_resource/exceptions'
require 'active_resource/connection'
require 'active_resource/formats'
@@ -21,7 +22,7 @@ require 'active_resource/log_subscriber'
module ActiveResource
# ActiveResource::Base is the main class for mapping RESTful resources as models in a Rails application.
#
- # For an outline of what Active Resource is capable of, see link:files/vendor/rails/activeresource/README.html.
+ # For an outline of what Active Resource is capable of, see its {README}[link:files/activeresource/README_rdoc.html].
#
# == Automated mapping
#
@@ -35,7 +36,7 @@ module ActiveResource
# end
#
# Now the Person class is mapped to RESTful resources located at <tt>http://api.people.com:3000/people/</tt>, and
- # you can now use Active Resource's lifecycle methods to manipulate resources. In the case where you already have
+ # you can now use Active Resource's life cycle methods to manipulate resources. In the case where you already have
# an existing model with the same name as the desired RESTful resource you can set the +element_name+ value.
#
# class PersonResource < ActiveResource::Base
@@ -51,7 +52,7 @@ module ActiveResource
# end
#
#
- # == Lifecycle methods
+ # == Life cycle methods
#
# Active Resource exposes methods for creating, finding, updating, and deleting resources
# from REST web services.
@@ -70,12 +71,12 @@ module ActiveResource
#
# ryan.destroy # => true
#
- # As you can see, these are very similar to Active Record's lifecycle methods for database records.
+ # As you can see, these are very similar to Active Record's life cycle methods for database records.
# You can read more about each of these methods in their respective documentation.
#
# === Custom REST methods
#
- # Since simple CRUD/lifecycle methods can't accomplish every task, Active Resource also supports
+ # Since simple CRUD/life cycle methods can't accomplish every task, Active Resource also supports
# defining your own custom REST methods. To invoke them, Active Resource provides the <tt>get</tt>,
# <tt>post</tt>, <tt>put</tt> and <tt>\delete</tt> methods where you can specify a custom REST method
# name to invoke.
@@ -166,6 +167,7 @@ module ActiveResource
# # GET http://api.people.com:3000/people/999.xml
# ryan = Person.find(999) # 404, raises ActiveResource::ResourceNotFound
#
+ #
# <tt>404</tt> is just one of the HTTP error response codes that Active Resource will handle with its own exception. The
# following HTTP response codes will also result in these exceptions:
#
@@ -194,6 +196,16 @@ module ActiveResource
# redirect_to :action => 'new'
# end
#
+ # When a GET is requested for a nested resource and you don't provide the prefix_param
+ # an ActiveResource::MissingPrefixParam will be raised.
+ #
+ # class Comment < ActiveResource::Base
+ # self.site = "http://someip.com/posts/:post_id/"
+ # end
+ #
+ # Comment.find(1)
+ # # => ActiveResource::MissingPrefixParam: post_id prefix_option is missing
+ #
# === Validation errors
#
# Active Resource supports validations on resources and will return errors if any of these validations fail
@@ -251,6 +263,8 @@ module ActiveResource
# The logger for diagnosing and tracing Active Resource calls.
cattr_accessor :logger
+ class_attribute :_format
+
class << self
# Creates a schema for this resource - setting the attributes that are
# known prior to fetching an instance from the remote system.
@@ -403,8 +417,8 @@ module ActiveResource
@site = nil
else
@site = create_site_uri_from(site)
- @user = uri_parser.unescape(@site.user) if @site.user
- @password = uri_parser.unescape(@site.password) if @site.password
+ @user = URI.parser.unescape(@site.user) if @site.user
+ @password = URI.parser.unescape(@site.password) if @site.password
end
end
@@ -480,13 +494,13 @@ module ActiveResource
format = mime_type_reference_or_format.is_a?(Symbol) ?
ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format
- write_inheritable_attribute(:format, format)
+ self._format = format
connection.format = format if site
end
# Returns the current format, default is ActiveResource::Formats::XmlFormat.
def format
- read_inheritable_attribute(:format) || ActiveResource::Formats::XmlFormat
+ self._format || ActiveResource::Formats::XmlFormat
end
# Sets the number of seconds after which requests to the REST API should time out.
@@ -508,9 +522,9 @@ module ActiveResource
#
# * <tt>:key</tt> - An OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
# * <tt>:cert</tt> - An OpenSSL::X509::Certificate object as client certificate
- # * <tt>:ca_file</tt> - Path to a CA certification file in PEM format. The file can contrain several CA certificates.
+ # * <tt>:ca_file</tt> - Path to a CA certification file in PEM format. The file can contain several CA certificates.
# * <tt>:ca_path</tt> - Path of a CA certification directory containing certifications in PEM format.
- # * <tt>:verify_mode</tt> - Flags for server the certification verification at begining of SSL/TLS session. (OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable)
+ # * <tt>:verify_mode</tt> - Flags for server the certification verification at beginning of SSL/TLS session. (OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable)
# * <tt>:verify_callback</tt> - The verify callback for the server certification verification.
# * <tt>:verify_depth</tt> - The maximum depth for the certificate chain verification.
# * <tt>:cert_store</tt> - OpenSSL::X509::Store to verify peer certificate.
@@ -577,7 +591,7 @@ module ActiveResource
# Default value is <tt>site.path</tt>.
def prefix=(value = '/')
# Replace :placeholders with '#{embedded options[:lookups]}'
- prefix_call = value.gsub(/:\w+/) { |key| "\#{URI.escape options[#{key}].to_s}" }
+ prefix_call = value.gsub(/:\w+/) { |key| "\#{URI.parser.escape options[#{key}].to_s}" }
# Clear prefix parameters in case they have been cached
@prefix_parameters = nil
@@ -589,8 +603,8 @@ module ActiveResource
def prefix(options={}) "#{prefix_call}" end
RUBY_EVAL
end
- rescue
- logger.error "Couldn't set prefix: #{$!}\n #{code}" if logger
+ rescue Exception => e
+ logger.error "Couldn't set prefix: #{e}\n #{code}" if logger
raise
end
@@ -621,8 +635,10 @@ module ActiveResource
# # => /posts/5/comments/1.xml?active=1
#
def element_path(id, prefix_options = {}, query_options = nil)
+ check_prefix_options(prefix_options)
+
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
- "#{prefix(prefix_options)}#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
+ "#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
end
# Gets the new element path for REST resources.
@@ -663,6 +679,7 @@ module ActiveResource
# # => /posts/5/comments.xml?active=1
#
def collection_path(prefix_options = {}, query_options = nil)
+ check_prefix_options(prefix_options)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}"
end
@@ -678,7 +695,7 @@ module ActiveResource
# Returns the new resource instance.
#
def build(attributes = {})
- attrs = connection.get("#{new_element_path}").merge(attributes)
+ attrs = self.format.decode(connection.get("#{new_element_path}").body).merge(attributes)
self.new(attrs)
end
@@ -842,6 +859,14 @@ module ActiveResource
end
private
+
+ def check_prefix_options(prefix_options)
+ p_options = HashWithIndifferentAccess.new(prefix_options)
+ prefix_parameters.each do |p|
+ raise(MissingPrefixParam, "#{p} prefix_option is missing") if p_options[p].blank?
+ end
+ end
+
# Find every resource
def find_every(options)
begin
@@ -850,11 +875,11 @@ module ActiveResource
instantiate_collection(get(from, options[:params]))
when String
path = "#{from}#{query_string(options[:params])}"
- instantiate_collection(connection.get(path, headers) || [])
+ instantiate_collection(format.decode(connection.get(path, headers).body) || [])
else
prefix_options, query_options = split_options(options[:params])
path = collection_path(prefix_options, query_options)
- instantiate_collection( (connection.get(path, headers) || []), prefix_options )
+ instantiate_collection( (format.decode(connection.get(path, headers).body) || []), prefix_options )
end
rescue ActiveResource::ResourceNotFound
# Swallowing ResourceNotFound exceptions and return nil - as per
@@ -870,7 +895,7 @@ module ActiveResource
instantiate_record(get(from, options[:params]))
when String
path = "#{from}#{query_string(options[:params])}"
- instantiate_record(connection.get(path, headers))
+ instantiate_record(format.decode(connection.get(path, headers).body))
end
end
@@ -878,7 +903,7 @@ module ActiveResource
def find_single(scope, options)
prefix_options, query_options = split_options(options[:params])
path = element_path(scope, prefix_options, query_options)
- instantiate_record(connection.get(path, headers), prefix_options)
+ instantiate_record(format.decode(connection.get(path, headers).body), prefix_options)
end
def instantiate_collection(collection, prefix_options = {})
@@ -886,7 +911,7 @@ module ActiveResource
end
def instantiate_record(record, prefix_options = {})
- new(record).tap do |resource|
+ new(record, true).tap do |resource|
resource.prefix_options = prefix_options
end
end
@@ -894,12 +919,12 @@ module ActiveResource
# Accepts a URI and creates the site URI from that.
def create_site_uri_from(site)
- site.is_a?(URI) ? site.dup : uri_parser.parse(site)
+ site.is_a?(URI) ? site.dup : URI.parser.parse(site)
end
# Accepts a URI and creates the proxy URI from that.
def create_proxy_uri_from(proxy)
- proxy.is_a?(URI) ? proxy.dup : uri_parser.parse(proxy)
+ proxy.is_a?(URI) ? proxy.dup : URI.parser.parse(proxy)
end
# contains a set of the current prefix parameters.
@@ -924,10 +949,6 @@ module ActiveResource
[ prefix_options, query_options ]
end
-
- def uri_parser
- @uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
- end
end
attr_accessor :attributes #:nodoc:
@@ -959,9 +980,10 @@ module ActiveResource
#
# my_other_course = Course.new(:name => "Philosophy: Reason and Being", :lecturer => "Ralph Cling")
# my_other_course.save
- def initialize(attributes = {})
+ def initialize(attributes = {}, persisted = false)
@attributes = {}.with_indifferent_access
@prefix_options = {}
+ @persisted = persisted
load(attributes)
end
@@ -987,10 +1009,7 @@ module ActiveResource
# not_ryan.hash # => {:not => "an ARes instance"}
def clone
# Clone all attributes except the pk and any nested ARes
- cloned = attributes.reject {|k,v| k == self.class.primary_key || v.is_a?(ActiveResource::Base)}.inject({}) do |attrs, (k, v)|
- attrs[k] = v.clone
- attrs
- end
+ cloned = Hash[attributes.reject {|k,v| k == self.class.primary_key || v.is_a?(ActiveResource::Base)}.map { |k, v| [k, v.clone] }]
# Form the new resource - bypass initialize of resource with 'new' as that will call 'load' which
# attempts to convert hashes into member objects and arrays into collections of objects. We want
# the raw objects to be cloned so we bypass load by directly setting the attributes hash.
@@ -1014,7 +1033,7 @@ module ActiveResource
# is_new.new? # => false
#
def new?
- id.nil?
+ !persisted?
end
alias :new_record? :new?
@@ -1031,7 +1050,7 @@ module ActiveResource
# not_persisted.persisted? # => true
#
def persisted?
- !new?
+ @persisted
end
# Gets the <tt>\id</tt> attribute of the resource.
@@ -1076,7 +1095,7 @@ module ActiveResource
end
# Delegates to id in order to allow two resources of the same type and \id to work with something like:
- # [Person.find(1), Person.find(2)] & [Person.find(1), Person.find(4)] # => [Person.find(1)]
+ # [(a = Person.find 1), (b = Person.find 2)] & [(c = Person.find 1), (d = Person.find 4)] # => [a]
def hash
id.hash
end
@@ -1318,8 +1337,9 @@ module ActiveResource
end
def load_attributes_from_response(response)
- if response['Content-Length'] != "0" && response.body.strip.size > 0
+ if !response['Content-Length'].blank? && response['Content-Length'] != "0" && !response.body.nil? && response.body.strip.size > 0
load(self.class.format.decode(response.body))
+ @persisted = true
end
end
@@ -1353,8 +1373,9 @@ module ActiveResource
namespaces = module_names[0, module_names.size-1].map do |module_name|
receiver = receiver.const_get(module_name)
end
- if namespace = namespaces.reverse.detect { |ns| ns.const_defined?(resource_name) }
- return namespace.const_get(resource_name)
+ const_args = RUBY_VERSION < "1.9" ? [resource_name] : [resource_name, false]
+ if namespace = namespaces.reverse.detect { |ns| ns.const_defined?(*const_args) }
+ return namespace.const_get(*const_args)
else
raise NameError
end
@@ -1370,8 +1391,9 @@ module ActiveResource
self.class.const_get(resource_name)
end
rescue NameError
- if self.class.const_defined?(resource_name)
- resource = self.class.const_get(resource_name)
+ const_args = RUBY_VERSION < "1.9" ? [resource_name] : [resource_name, false]
+ if self.class.const_defined?(*const_args)
+ resource = self.class.const_get(*const_args)
else
resource = self.class.const_set(resource_name, Class.new(ActiveResource::Base))
end
diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb
index b7befe110d..480f2fbecb 100644
--- a/activeresource/lib/active_resource/connection.rb
+++ b/activeresource/lib/active_resource/connection.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/benchmark'
+require 'active_support/core_ext/uri'
require 'net/https'
require 'date'
require 'time'
@@ -31,21 +32,20 @@ module ActiveResource
def initialize(site, format = ActiveResource::Formats::XmlFormat)
raise ArgumentError, 'Missing site URI' unless site
@user = @password = nil
- @uri_parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI
self.site = site
self.format = format
end
# Set URI for remote service.
def site=(site)
- @site = site.is_a?(URI) ? site : @uri_parser.parse(site)
- @user = @uri_parser.unescape(@site.user) if @site.user
- @password = @uri_parser.unescape(@site.password) if @site.password
+ @site = site.is_a?(URI) ? site : URI.parser.parse(site)
+ @user = URI.parser.unescape(@site.user) if @site.user
+ @password = URI.parser.unescape(@site.password) if @site.password
end
# Set the proxy for remote service.
def proxy=(proxy)
- @proxy = proxy.is_a?(URI) ? proxy : @uri_parser.parse(proxy)
+ @proxy = proxy.is_a?(URI) ? proxy : URI.parser.parse(proxy)
end
# Sets the user for remote service.
@@ -76,7 +76,7 @@ module ActiveResource
# Executes a GET request.
# Used to get (find) resources.
def get(path, headers = {})
- with_auth { format.decode(request(:get, path, build_request_headers(headers, :get, self.site.merge(path))).body) }
+ with_auth { request(:get, path, build_request_headers(headers, :get, self.site.merge(path))) }
end
# Executes a DELETE request (see HTTP protocol documentation if unfamiliar).
diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb
index dd3e35dfc7..9879f8cded 100644
--- a/activeresource/lib/active_resource/custom_methods.rb
+++ b/activeresource/lib/active_resource/custom_methods.rb
@@ -54,7 +54,7 @@ module ActiveResource
#
# Person.find(:all, :from => :active)
def get(custom_method_name, options = {})
- connection.get(custom_method_collection_url(custom_method_name, options), headers)
+ format.decode(connection.get(custom_method_collection_url(custom_method_name, options), headers).body)
end
def post(custom_method_name, options = {}, body = '')
@@ -85,7 +85,7 @@ module ActiveResource
module InstanceMethods
def get(method_name, options = {})
- connection.get(custom_method_element_url(method_name, options), self.class.headers)
+ self.class.format.decode(connection.get(custom_method_element_url(method_name, options), self.class.headers).body)
end
def post(method_name, options = {}, body = nil)
diff --git a/activeresource/lib/active_resource/exceptions.rb b/activeresource/lib/active_resource/exceptions.rb
index 0f4549fd73..6b953b28ad 100644
--- a/activeresource/lib/active_resource/exceptions.rb
+++ b/activeresource/lib/active_resource/exceptions.rb
@@ -36,6 +36,9 @@ module ActiveResource
def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end
end
+ # Raised when ...
+ class MissingPrefixParam < ArgumentError; end # :nodoc:
+
# 4xx Client Error
class ClientError < ConnectionError; end # :nodoc:
diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb
index 75425c01c0..75649053d0 100644
--- a/activeresource/lib/active_resource/http_mock.rb
+++ b/activeresource/lib/active_resource/http_mock.rb
@@ -29,7 +29,8 @@ module ActiveResource
#
# In order for a mock to deliver its content, the incoming request must match by the <tt>http_method</tt>,
# +path+ and <tt>request_headers</tt>. If no match is found an InvalidRequestError exception
- # will be raised letting you know you need to create a new mock for that request.
+ # will be raised showing you what request it could not find a response for and also what requests and response
+ # pairs have been recorded so you can create a new mock for that request.
#
# ==== Example
# def setup
@@ -41,7 +42,7 @@ module ActiveResource
# mock.delete "/people/1.xml", {}, nil, 200
# end
# end
- #
+ #
# def test_get_matz
# person = Person.find(1)
# assert_equal "Matz", person.name
@@ -59,10 +60,21 @@ module ActiveResource
# end
module_eval <<-EOE, __FILE__, __LINE__ + 1
def #{method}(path, request_headers = {}, body = nil, status = 200, response_headers = {})
- @responses << [Request.new(:#{method}, path, nil, request_headers), Response.new(body || "", status, response_headers)]
+ request = Request.new(:#{method}, path, nil, request_headers)
+ response = Response.new(body || "", status, response_headers)
+
+ delete_duplicate_responses(request)
+
+ @responses << [request, response]
end
EOE
end
+
+ private
+
+ def delete_duplicate_responses(request)
+ @responses.delete_if {|r| r[0] == request }
+ end
end
class << self
@@ -77,13 +89,13 @@ module ActiveResource
# mock.get "/people/1.xml", {}, @matz
# end
# end
- #
+ #
# def test_should_request_remote_service
# person = Person.find(1) # Call the remote service
- #
+ #
# # This request object has the same HTTP method and path as declared by the mock
# expected_request = ActiveResource::Request.new(:get, "/people/1.xml")
- #
+ #
# # Assert that the mock received, and responded to, the expected request from the model
# assert ActiveResource::HttpMock.requests.include?(expected_request)
# end
@@ -97,18 +109,105 @@ module ActiveResource
@@responses ||= []
end
- # Accepts a block which declares a set of requests and responses for the HttpMock to respond to. See the main
- # ActiveResource::HttpMock description for a more detailed explanation.
- def respond_to(pairs = {}) #:yields: mock
- reset!
- responses.concat pairs.to_a
+ # Accepts a block which declares a set of requests and responses for the HttpMock to respond to in
+ # the following format:
+ #
+ # mock.http_method(path, request_headers = {}, body = nil, status = 200, response_headers = {})
+ #
+ # === Example
+ #
+ # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
+ # ActiveResource::HttpMock.respond_to do |mock|
+ # mock.post "/people.xml", {}, @matz, 201, "Location" => "/people/1.xml"
+ # mock.get "/people/1.xml", {}, @matz
+ # mock.put "/people/1.xml", {}, nil, 204
+ # mock.delete "/people/1.xml", {}, nil, 200
+ # end
+ #
+ # Alternatively, accepts a hash of <tt>{Request => Response}</tt> pairs allowing you to generate
+ # these the following format:
+ #
+ # ActiveResource::Request.new(method, path, body, request_headers)
+ # ActiveResource::Response.new(body, status, response_headers)
+ #
+ # === Example
+ #
+ # Request.new(:#{method}, path, nil, request_headers)
+ #
+ # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
+ #
+ # create_matz = ActiveResource::Request.new(:post, '/people.xml', @matz, {})
+ # created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.xml"})
+ # get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
+ # ok_response = ActiveResource::Response.new("", 200, {})
+ #
+ # pairs = {create_matz => created_response, get_matz => ok_response}
+ #
+ # ActiveResource::HttpMock.respond_to(pairs)
+ #
+ # Note, by default, every time you call +respond_to+, any previous request and response pairs stored
+ # in HttpMock will be deleted giving you a clean slate to work on.
+ #
+ # If you want to override this behaviour, pass in +false+ as the last argument to +respond_to+
+ #
+ # === Example
+ #
+ # ActiveResource::HttpMock.respond_to do |mock|
+ # mock.send(:get, "/people/1", {}, "XML1")
+ # end
+ # ActiveResource::HttpMock.responses.length #=> 1
+ #
+ # ActiveResource::HttpMock.respond_to(false) do |mock|
+ # mock.send(:get, "/people/2", {}, "XML2")
+ # end
+ # ActiveResource::HttpMock.responses.length #=> 2
+ #
+ # This also works with passing in generated pairs of requests and responses, again, just pass in false
+ # as the last argument:
+ #
+ # === Example
+ #
+ # ActiveResource::HttpMock.respond_to do |mock|
+ # mock.send(:get, "/people/1", {}, "XML1")
+ # end
+ # ActiveResource::HttpMock.responses.length #=> 1
+ #
+ # get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
+ # ok_response = ActiveResource::Response.new("", 200, {})
+ #
+ # pairs = {get_matz => ok_response}
+ #
+ # ActiveResource::HttpMock.respond_to(pairs, false)
+ # ActiveResource::HttpMock.responses.length #=> 2
+ #
+ # # If you add a response with an existing request, it will be replaced
+ #
+ # fail_response = ActiveResource::Response.new("", 404, {})
+ # pairs = {get_matz => fail_response}
+ #
+ # ActiveResource::HttpMock.respond_to(pairs, false)
+ # ActiveResource::HttpMock.responses.length #=> 2
+ #
+ def respond_to(*args) #:yields: mock
+ pairs = args.first || {}
+ reset! if args.last.class != FalseClass
+
if block_given?
yield Responder.new(responses)
else
+ delete_responses_to_replace pairs.to_a
+ responses.concat pairs.to_a
Responder.new(responses)
end
end
+ def delete_responses_to_replace(new_responses)
+ new_responses.each{|nr|
+ request_to_remove = nr[0]
+ @@responses = responses.delete_if{|r| r[0] == request_to_remove}
+ }
+ end
+
# Deletes all logged requests and responses.
def reset!
requests.clear
@@ -126,7 +225,7 @@ module ActiveResource
# if response = self.class.responses.assoc(request)
# response[1]
# else
- # raise InvalidRequestError.new("No response recorded for #{request}")
+ # raise InvalidRequestError.new("Could not find a response recorded for #{request.to_s} - Responses recorded are: - #{inspect_responses}")
# end
# end
module_eval <<-EOE, __FILE__, __LINE__ + 1
@@ -136,7 +235,7 @@ module ActiveResource
if response = self.class.responses.assoc(request)
response[1]
else
- raise InvalidRequestError.new("No response recorded for \#{request}")
+ raise InvalidRequestError.new("Could not find a response recorded for \#{request.to_s} - Responses recorded are: \#{inspect_responses}")
end
end
EOE
@@ -146,6 +245,10 @@ module ActiveResource
def initialize(site) #:nodoc:
@site = site
end
+
+ def inspect_responses #:nodoc:
+ self.class.responses.map { |r| r[0].to_s }.inspect
+ end
end
class Request
diff --git a/activeresource/lib/active_resource/schema.rb b/activeresource/lib/active_resource/schema.rb
index 5758ac9502..3fd37a9bb6 100644
--- a/activeresource/lib/active_resource/schema.rb
+++ b/activeresource/lib/active_resource/schema.rb
@@ -4,7 +4,7 @@ module ActiveResource # :nodoc:
class Schema # :nodoc:
# attributes can be known to be one of these types. They are easy to
# cast to/from.
- KNOWN_ATTRIBUTE_TYPES = %w( string integer float )
+ KNOWN_ATTRIBUTE_TYPES = %w( string text integer float decimal datetime timestamp time date binary boolean )
# An array of attribute definitions, representing the attributes that
# have been defined.
@@ -39,8 +39,6 @@ module ActiveResource # :nodoc:
# The following are the attribute types supported by Active Resource
# migrations.
- # TODO: We should eventually support all of these:
- # %w( string text integer float decimal datetime timestamp time date binary boolean ).each do |attr_type|
KNOWN_ATTRIBUTE_TYPES.each do |attr_type|
class_eval <<-EOV, __FILE__, __LINE__ + 1
def #{attr_type.to_s}(*args)
diff --git a/activeresource/lib/active_resource/validations.rb b/activeresource/lib/active_resource/validations.rb
index 026d81e44a..a373e53f11 100644
--- a/activeresource/lib/active_resource/validations.rb
+++ b/activeresource/lib/active_resource/validations.rb
@@ -6,21 +6,21 @@ module ActiveResource
end
# Active Resource validation is reported to and from this object, which is used by Base#save
- # to determine whether the object in a valid state to be saved. See usage example in Validations.
+ # to determine whether the object in a valid state to be saved. See usage example in Validations.
class Errors < ActiveModel::Errors
# Grabs errors from an array of messages (like ActiveRecord::Validations)
# The second parameter directs the errors cache to be cleared (default)
# or not (by passing true)
def from_array(messages, save_cache = false)
clear unless save_cache
- humanized_attributes = @base.attributes.keys.inject({}) { |h, attr_name| h.update(attr_name.humanize => attr_name) }
+ humanized_attributes = Hash[@base.attributes.keys.map { |attr_name| [attr_name.humanize, attr_name] }]
messages.each do |message|
attr_message = humanized_attributes.keys.detect do |attr_name|
if message[0, attr_name.size + 1] == "#{attr_name} "
add humanized_attributes[attr_name], message[(attr_name.size + 1)..-1]
end
end
-
+
self[:base] << message if attr_message.nil?
end
end
@@ -37,15 +37,15 @@ module ActiveResource
from_array array, save_cache
end
end
-
+
# Module to support validation and errors with Active Resource objects. The module overrides
- # Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned
- # in the web service response. The module also adds an +errors+ collection that mimics the interface
+ # Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned
+ # in the web service response. The module also adds an +errors+ collection that mimics the interface
# of the errors provided by ActiveRecord::Errors.
#
# ==== Example
#
- # Consider a Person resource on the server requiring both a +first_name+ and a +last_name+ with a
+ # Consider a Person resource on the server requiring both a +first_name+ and a +last_name+ with a
# <tt>validates_presence_of :first_name, :last_name</tt> declaration in the model:
#
# person = Person.new(:first_name => "Jim", :last_name => "")
@@ -55,7 +55,7 @@ module ActiveResource
# person.errors.count # => 1
# person.errors.full_messages # => ["Last name can't be empty"]
# person.errors[:last_name] # => ["can't be empty"]
- # person.last_name = "Halpert"
+ # person.last_name = "Halpert"
# person.save # => true (and person is now saved to the remote service)
#
module Validations
@@ -68,16 +68,8 @@ module ActiveResource
# Validate a resource and save (POST) it to the remote web service.
# If any local validations fail - the save (POST) will not be attempted.
- def save_with_validation(options=nil)
- perform_validation = case options
- when Hash
- options[:validate] != false
- when NilClass
- true
- else
- ActiveSupport::Deprecation.warn "save(#{options}) is deprecated, please give save(:validate => #{options}) instead", caller
- options
- end
+ def save_with_validation(options={})
+ perform_validation = options[:validate] != false
# clear the remote validations so they don't interfere with the local
# ones. Otherwise we get an endless loop and can never change the
@@ -118,7 +110,7 @@ module ActiveResource
# also any errors returned from the remote system the last time we
# saved.
# Remote errors can only be cleared by trying to re-save the resource.
- #
+ #
# ==== Examples
# my_person = Person.create(params[:person])
# my_person.valid?
diff --git a/activeresource/lib/active_resource/version.rb b/activeresource/lib/active_resource/version.rb
index 43c00e9cf1..82dcb5d575 100644
--- a/activeresource/lib/active_resource/version.rb
+++ b/activeresource/lib/active_resource/version.rb
@@ -1,10 +1,10 @@
module ActiveResource
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb
index fcb770d612..195f93f2a6 100644
--- a/activeresource/test/abstract_unit.rb
+++ b/activeresource/test/abstract_unit.rb
@@ -18,3 +18,108 @@ begin
require 'ruby-debug'
rescue LoadError
end
+
+def setup_response
+ @default_request_headers = { 'Content-Type' => 'application/xml' }
+ @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person')
+ @david = { :id => 2, :name => 'David' }.to_xml(:root => 'person')
+ @greg = { :id => 3, :name => 'Greg' }.to_xml(:root => 'person')
+ @addy = { :id => 1, :street => '12345 Street', :country => 'Australia' }.to_xml(:root => 'address')
+ @rick = { :name => "Rick", :age => 25 }.to_xml(:root => "person")
+ @joe = { 'person' => { :id => 6, :name => 'Joe' }}.to_json
+ @people = [{ :id => 1, :name => 'Matz' }, { :id => 2, :name => 'David' }].to_xml(:root => 'people')
+ @people_david = [{ :id => 2, :name => 'David' }].to_xml(:root => 'people')
+ @addresses = [{ :id => 1, :street => '12345 Street', :country => 'Australia' }].to_xml(:root => 'addresses')
+
+ # - deep nested resource -
+ # - Luis (Customer)
+ # - JK (Customer::Friend)
+ # - Mateo (Customer::Friend::Brother)
+ # - Edith (Customer::Friend::Brother::Child)
+ # - Martha (Customer::Friend::Brother::Child)
+ # - Felipe (Customer::Friend::Brother)
+ # - Bryan (Customer::Friend::Brother::Child)
+ # - Luke (Customer::Friend::Brother::Child)
+ # - Eduardo (Customer::Friend)
+ # - Sebas (Customer::Friend::Brother)
+ # - Andres (Customer::Friend::Brother::Child)
+ # - Jorge (Customer::Friend::Brother::Child)
+ # - Elsa (Customer::Friend::Brother)
+ # - Natacha (Customer::Friend::Brother::Child)
+ # - Milena (Customer::Friend::Brother)
+ #
+ @luis = {:id => 1, :name => 'Luis',
+ :friends => [{:name => 'JK',
+ :brothers => [{:name => 'Mateo',
+ :children => [{:name => 'Edith'},{:name => 'Martha'}]},
+ {:name => 'Felipe',
+ :children => [{:name => 'Bryan'},{:name => 'Luke'}]}]},
+ {:name => 'Eduardo',
+ :brothers => [{:name => 'Sebas',
+ :children => [{:name => 'Andres'},{:name => 'Jorge'}]},
+ {:name => 'Elsa',
+ :children => [{:name => 'Natacha'}]},
+ {:name => 'Milena',
+ :children => []}]}]}.to_xml(:root => 'customer')
+ # - resource with yaml array of strings; for ARs using serialize :bar, Array
+ @marty = <<-eof.strip
+ <?xml version=\"1.0\" encoding=\"UTF-8\"?>
+ <person>
+ <id type=\"integer\">5</id>
+ <name>Marty</name>
+ <colors type=\"yaml\">---
+ - \"red\"
+ - \"green\"
+ - \"blue\"
+ </colors>
+ </person>
+ eof
+
+ @startup_sound = {
+ :name => "Mac Startup Sound", :author => { :name => "Jim Reekes" }
+ }.to_xml(:root => 'sound')
+
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.get "/people/1.xml", {}, @matz
+ mock.get "/people/2.xml", {}, @david
+ mock.get "/people/5.xml", {}, @marty
+ mock.get "/people/Greg.xml", {}, @greg
+ mock.get "/people/6.json", {}, @joe
+ mock.get "/people/4.xml", {'key' => 'value'}, nil, 404
+ mock.put "/people/1.xml", {}, nil, 204
+ mock.delete "/people/1.xml", {}, nil, 200
+ mock.delete "/people/2.xml", {}, nil, 400
+ mock.get "/people/99.xml", {}, nil, 404
+ mock.post "/people.xml", {}, @rick, 201, 'Location' => '/people/5.xml'
+ mock.get "/people.xml", {}, @people
+ mock.get "/people/1/addresses.xml", {}, @addresses
+ mock.get "/people/1/addresses/1.xml", {}, @addy
+ mock.get "/people/1/addresses/2.xml", {}, nil, 404
+ mock.get "/people/2/addresses.xml", {}, nil, 404
+ mock.get "/people/2/addresses/1.xml", {}, nil, 404
+ mock.get "/people/Greg/addresses/1.xml", {}, @addy
+ mock.put "/people/1/addresses/1.xml", {}, nil, 204
+ mock.delete "/people/1/addresses/1.xml", {}, nil, 200
+ mock.post "/people/1/addresses.xml", {}, nil, 201, 'Location' => '/people/1/addresses/5'
+ mock.get "/people/1/addresses/99.xml", {}, nil, 404
+ mock.get "/people//addresses.xml", {}, nil, 404
+ mock.get "/people//addresses/1.xml", {}, nil, 404
+ mock.put "/people//addresses/1.xml", {}, nil, 404
+ mock.delete "/people//addresses/1.xml", {}, nil, 404
+ mock.post "/people//addresses.xml", {}, nil, 404
+ mock.head "/people/1.xml", {}, nil, 200
+ mock.head "/people/Greg.xml", {}, nil, 200
+ mock.head "/people/99.xml", {}, nil, 404
+ mock.head "/people/1/addresses/1.xml", {}, nil, 200
+ mock.head "/people/1/addresses/2.xml", {}, nil, 404
+ mock.head "/people/2/addresses/1.xml", {}, nil, 404
+ mock.head "/people/Greg/addresses/1.xml", {}, nil, 200
+ # customer
+ mock.get "/customers/1.xml", {}, @luis
+ # sound
+ mock.get "/sounds/1.xml", {}, @startup_sound
+ end
+
+ Person.user = nil
+ Person.password = nil
+end
diff --git a/activeresource/test/cases/authorization_test.rb b/activeresource/test/cases/authorization_test.rb
index 1a7c9ec8a4..a6797643e1 100644
--- a/activeresource/test/cases/authorization_test.rb
+++ b/activeresource/test/cases/authorization_test.rb
@@ -132,7 +132,7 @@ class AuthorizationTest < Test::Unit::TestCase
end
def test_get
- david = @authenticated_conn.get("/people/2.xml")
+ david = decode(@authenticated_conn.get("/people/2.xml"))
assert_equal "David", david["name"]
end
@@ -159,7 +159,7 @@ class AuthorizationTest < Test::Unit::TestCase
def test_get_with_digest_auth_handles_initial_401_response_and_retries
@authenticated_conn.auth_type = :digest
response = @authenticated_conn.get("/people/2.xml")
- assert_equal "David", response["name"]
+ assert_equal "David", decode(response)["name"]
end
def test_post_with_digest_auth_handles_initial_401_response_and_retries
@@ -190,11 +190,11 @@ class AuthorizationTest < Test::Unit::TestCase
def test_get_with_digest_auth_caches_nonce
@authenticated_conn.auth_type = :digest
response = @authenticated_conn.get("/people/2.xml")
- assert_equal "David", response["name"]
+ assert_equal "David", decode(response)["name"]
# There is no mock for this request with a non-cached nonce.
response = @authenticated_conn.get("/people/1.xml")
- assert_equal "Matz", response["name"]
+ assert_equal "Matz", decode(response)["name"]
end
def test_retry_on_401_only_happens_with_digest_auth
@@ -241,4 +241,8 @@ class AuthorizationTest < Test::Unit::TestCase
def response_digest_auth_header
%Q(Digest realm="RailsTestApp", qop="auth", algorithm=MD5, nonce="#{@nonce}", opaque="ef6dfb078ba22298d366f99567814ffb")
end
+
+ def decode(response)
+ @authenticated_conn.format.decode(response.body)
+ end
end
diff --git a/activeresource/test/cases/base/custom_methods_test.rb b/activeresource/test/cases/base/custom_methods_test.rb
index 2d81549a65..0fbf94bc0e 100644
--- a/activeresource/test/cases/base/custom_methods_test.rb
+++ b/activeresource/test/cases/base/custom_methods_test.rb
@@ -35,7 +35,7 @@ class CustomMethodsTest < Test::Unit::TestCase
Person.user = nil
Person.password = nil
- end
+ end
def teardown
ActiveResource::HttpMock.reset!
@@ -64,13 +64,13 @@ class CustomMethodsTest < Test::Unit::TestCase
# Test GET against an element URL
assert_equal Person.find(1).get(:shallow), {"id" => 1, "name" => 'Matz'}
assert_equal Person.find(1).get(:deep), {"id" => 1, "name" => 'Matz', "other" => 'other'}
-
+
# Test PUT against an element URL
assert_equal ActiveResource::Response.new("", 204, {}), Person.find(1).put(:promote, {:position => 'Manager'}, 'body')
-
+
# Test DELETE against an element URL
assert_equal ActiveResource::Response.new("", 200, {}), Person.find(1).delete(:deactivate)
-
+
# With nested resources
assert_equal StreetAddress.find(1, :params => { :person_id => 1 }).get(:deep),
{ "id" => 1, "street" => '12345 Street', "zip" => "27519" }
@@ -87,11 +87,11 @@ class CustomMethodsTest < Test::Unit::TestCase
# Test POST against a nested collection URL
addy = StreetAddress.new(:street => '123 Test Dr.', :person_id => 1)
- assert_equal ActiveResource::Response.new({ :street => '12345 Street' }.to_xml(:root => 'address'),
+ assert_equal ActiveResource::Response.new({ :street => '12345 Street' }.to_xml(:root => 'address'),
201, {'Location' => '/people/1/addresses/2.xml'}),
addy.post(:link)
- matz = Person.new(:id => 1, :name => 'Matz')
+ matz = Person.find(1)
assert_equal ActiveResource::Response.new(@matz, 201), matz.post(:register)
end
diff --git a/activeresource/test/cases/base/schema_test.rb b/activeresource/test/cases/base/schema_test.rb
index 136c827926..37f30e4353 100644
--- a/activeresource/test/cases/base/schema_test.rb
+++ b/activeresource/test/cases/base/schema_test.rb
@@ -8,58 +8,13 @@ require "fixtures/street_address"
########################################################################
class SchemaTest < ActiveModel::TestCase
def setup
- @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person')
- @david = { :id => 2, :name => 'David' }.to_xml(:root => 'person')
- @greg = { :id => 3, :name => 'Greg' }.to_xml(:root => 'person')
- @addy = { :id => 1, :street => '12345 Street', :country => 'Australia' }.to_xml(:root => 'address')
- @default_request_headers = { 'Content-Type' => 'application/xml' }
- @rick = { :name => "Rick", :age => 25 }.to_xml(:root => "person")
- @people = [{ :id => 1, :name => 'Matz' }, { :id => 2, :name => 'David' }].to_xml(:root => 'people')
- @people_david = [{ :id => 2, :name => 'David' }].to_xml(:root => 'people')
- @addresses = [{ :id => 1, :street => '12345 Street', :country => 'Australia' }].to_xml(:root => 'addresses')
-
- ActiveResource::HttpMock.respond_to do |mock|
- mock.get "/people/1.xml", {}, @matz
- mock.get "/people/2.xml", {}, @david
- mock.get "/people/Greg.xml", {}, @greg
- mock.get "/people/4.xml", {'key' => 'value'}, nil, 404
- mock.get "/people/5.xml", {}, @rick
- mock.put "/people/1.xml", {}, nil, 204
- mock.delete "/people/1.xml", {}, nil, 200
- mock.delete "/people/2.xml", {}, nil, 400
- mock.get "/people/99.xml", {}, nil, 404
- mock.post "/people.xml", {}, @rick, 201, 'Location' => '/people/5.xml'
- mock.get "/people.xml", {}, @people
- mock.get "/people/1/addresses.xml", {}, @addresses
- mock.get "/people/1/addresses/1.xml", {}, @addy
- mock.get "/people/1/addresses/2.xml", {}, nil, 404
- mock.get "/people/2/addresses/1.xml", {}, nil, 404
- mock.get "/people/Greg/addresses/1.xml", {}, @addy
- mock.put "/people/1/addresses/1.xml", {}, nil, 204
- mock.delete "/people/1/addresses/1.xml", {}, nil, 200
- mock.post "/people/1/addresses.xml", {}, nil, 201, 'Location' => '/people/1/addresses/5'
- mock.get "/people//addresses.xml", {}, nil, 404
- mock.get "/people//addresses/1.xml", {}, nil, 404
- mock.put "/people//addressaddresseses/1.xml", {}, nil, 404
- mock.delete "/people//addresses/1.xml", {}, nil, 404
- mock.post "/people//addresses.xml", {}, nil, 404
- mock.head "/people/1.xml", {}, nil, 200
- mock.head "/people/Greg.xml", {}, nil, 200
- mock.head "/people/99.xml", {}, nil, 404
- mock.head "/people/1/addresses/1.xml", {}, nil, 200
- mock.head "/people/1/addresses/2.xml", {}, nil, 404
- mock.head "/people/2/addresses/1.xml", {}, nil, 404
- mock.head "/people/Greg/addresses/1.xml", {}, nil, 200
- end
-
- Person.user = nil
- Person.password = nil
+ setup_response # find me in abstract_unit
end
+
def teardown
Person.schema = nil # hack to stop test bleedthrough...
end
-
#####################################################
# Passing in a schema directly and returning it
####
@@ -78,14 +33,23 @@ class SchemaTest < ActiveModel::TestCase
end
test "schema should accept a simple hash" do
- new_schema = {'age' => 'integer', 'name' => 'string'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
+
assert_nothing_raised { Person.schema = new_schema }
assert_equal new_schema, Person.schema
end
test "schema should accept a hash with simple values" do
- new_schema = {'age' => 'integer', 'name' => 'string', 'height' => 'float', 'mydatetime' => 'string'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
assert_nothing_raised { Person.schema = new_schema }
assert_equal new_schema, Person.schema
@@ -109,7 +73,12 @@ class SchemaTest < ActiveModel::TestCase
end
test "schema should accept nil and remove the schema" do
- new_schema = {'age' => 'integer', 'name' => 'string'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
+
assert_nothing_raised { Person.schema = new_schema }
assert_equal new_schema, Person.schema # sanity check
@@ -120,7 +89,12 @@ class SchemaTest < ActiveModel::TestCase
test "schema should be with indifferent access" do
- new_schema = {:age => :integer, 'name' => 'string'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
+
new_schema_syms = new_schema.keys
assert_nothing_raised { Person.schema = new_schema }
@@ -156,7 +130,12 @@ class SchemaTest < ActiveModel::TestCase
test "defining a schema should return it when asked" do
assert Person.schema.blank?, "should have a blank class schema"
- new_schema = {'name' => 'string', 'age' => 'integer', 'height' => 'float', 'weight' => 'float'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
+
assert_nothing_raised {
Person.schema = new_schema
assert_equal new_schema, Person.schema, "should have saved the schema on the class"
@@ -167,7 +146,11 @@ class SchemaTest < ActiveModel::TestCase
test "defining a schema, then fetching a model should still match the defined schema" do
# sanity checks
assert Person.schema.blank?, "should have a blank class schema"
- new_schema = {'name' => 'string', 'age' => 'integer', 'height' => 'float', 'weight' => 'float'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
matz = Person.find(1)
assert !matz.schema.blank?, "should have some sort of schema on an instance variable"
@@ -368,12 +351,16 @@ class SchemaTest < ActiveModel::TestCase
end
test "setting schema should set known attributes on class and instance" do
- new_schema = {'age' => 'integer', 'name' => 'string'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
assert_nothing_raised { Person.schema = new_schema }
- assert_equal new_schema.keys, Person.known_attributes
- assert_equal new_schema.keys, Person.new.known_attributes
+ assert_equal new_schema.keys.sort, Person.known_attributes.sort
+ assert_equal new_schema.keys.sort, Person.new.known_attributes.sort
end
test "known attributes on a fetched resource should return all the attributes of the instance" do
@@ -399,9 +386,13 @@ class SchemaTest < ActiveModel::TestCase
assert_not_equal matz.known_attributes, rick.known_attributes, "should have had different known attributes too"
end
- test "setting schema then fetching should add schema attributes to the intance attributes" do
+ test "setting schema then fetching should add schema attributes to the instance attributes" do
# an attribute in common with fetched instance and one that isn't
- new_schema = {'name' => 'string', 'my_strange_attribute' => 'string'}
+ new_schema = {'age' => 'integer', 'name' => 'string',
+ 'height' => 'float', 'bio' => 'text',
+ 'weight' => 'decimal', 'photo' => 'binary',
+ 'alive' => 'boolean', 'created_at' => 'timestamp',
+ 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'}
assert_nothing_raised { Person.schema = new_schema }
diff --git a/activeresource/test/cases/base_test.rb b/activeresource/test/cases/base_test.rb
index 91b375681b..48dacbdf67 100644
--- a/activeresource/test/cases/base_test.rb
+++ b/activeresource/test/cases/base_test.rb
@@ -5,6 +5,8 @@ require "fixtures/street_address"
require "fixtures/sound"
require "fixtures/beast"
require "fixtures/proxy"
+require "fixtures/address"
+require "fixtures/subscription_plan"
require 'active_support/json'
require 'active_support/ordered_hash'
require 'active_support/core_ext/hash/conversions'
@@ -12,101 +14,8 @@ require 'mocha'
class BaseTest < Test::Unit::TestCase
def setup
- @default_request_headers = { 'Content-Type' => 'application/xml' }
- @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person')
- @david = { :id => 2, :name => 'David' }.to_xml(:root => 'person')
- @greg = { :id => 3, :name => 'Greg' }.to_xml(:root => 'person')
- @addy = { :id => 1, :street => '12345 Street', :country => 'Australia' }.to_xml(:root => 'address')
- @rick = { :name => "Rick", :age => 25 }.to_xml(:root => "person")
- @joe = { 'person' => { :id => 6, :name => 'Joe' }}.to_json
- @people = [{ :id => 1, :name => 'Matz' }, { :id => 2, :name => 'David' }].to_xml(:root => 'people')
- @people_david = [{ :id => 2, :name => 'David' }].to_xml(:root => 'people')
- @addresses = [{ :id => 1, :street => '12345 Street', :country => 'Australia' }].to_xml(:root => 'addresses')
-
- # - deep nested resource -
- # - Luis (Customer)
- # - JK (Customer::Friend)
- # - Mateo (Customer::Friend::Brother)
- # - Edith (Customer::Friend::Brother::Child)
- # - Martha (Customer::Friend::Brother::Child)
- # - Felipe (Customer::Friend::Brother)
- # - Bryan (Customer::Friend::Brother::Child)
- # - Luke (Customer::Friend::Brother::Child)
- # - Eduardo (Customer::Friend)
- # - Sebas (Customer::Friend::Brother)
- # - Andres (Customer::Friend::Brother::Child)
- # - Jorge (Customer::Friend::Brother::Child)
- # - Elsa (Customer::Friend::Brother)
- # - Natacha (Customer::Friend::Brother::Child)
- # - Milena (Customer::Friend::Brother)
- #
- @luis = {:id => 1, :name => 'Luis',
- :friends => [{:name => 'JK',
- :brothers => [{:name => 'Mateo',
- :children => [{:name => 'Edith'},{:name => 'Martha'}]},
- {:name => 'Felipe',
- :children => [{:name => 'Bryan'},{:name => 'Luke'}]}]},
- {:name => 'Eduardo',
- :brothers => [{:name => 'Sebas',
- :children => [{:name => 'Andres'},{:name => 'Jorge'}]},
- {:name => 'Elsa',
- :children => [{:name => 'Natacha'}]},
- {:name => 'Milena',
- :children => []}]}]}.to_xml(:root => 'customer')
- # - resource with yaml array of strings; for ARs using serialize :bar, Array
- @marty = <<-eof.strip
- <?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <person>
- <id type=\"integer\">5</id>
- <name>Marty</name>
- <colors type=\"yaml\">---
- - \"red\"
- - \"green\"
- - \"blue\"
- </colors>
- </person>
- eof
-
- ActiveResource::HttpMock.respond_to do |mock|
- mock.get "/people/1.xml", {}, @matz
- mock.get "/people/2.xml", {}, @david
- mock.get "/people/6.json", {}, @joe
- mock.get "/people/5.xml", {}, @marty
- mock.get "/people/Greg.xml", {}, @greg
- mock.get "/people/4.xml", {'key' => 'value'}, nil, 404
- mock.put "/people/1.xml", {}, nil, 204
- mock.delete "/people/1.xml", {}, nil, 200
- mock.delete "/people/2.xml", {}, nil, 400
- mock.get "/people/99.xml", {}, nil, 404
- mock.post "/people.xml", {}, @rick, 201, 'Location' => '/people/5.xml'
- mock.get "/people.xml", {}, @people
- mock.get "/people/1/addresses.xml", {}, @addresses
- mock.get "/people/1/addresses/1.xml", {}, @addy
- mock.get "/people/1/addresses/2.xml", {}, nil, 404
- mock.get "/people/2/addresses/1.xml", {}, nil, 404
- mock.get "/people/Greg/addresses/1.xml", {}, @addy
- mock.put "/people/1/addresses/1.xml", {}, nil, 204
- mock.delete "/people/1/addresses/1.xml", {}, nil, 200
- mock.post "/people/1/addresses.xml", {}, nil, 201, 'Location' => '/people/1/addresses/5'
- mock.get "/people//addresses.xml", {}, nil, 404
- mock.get "/people//addresses/1.xml", {}, nil, 404
- mock.put "/people//addresses/1.xml", {}, nil, 404
- mock.delete "/people//addresses/1.xml", {}, nil, 404
- mock.post "/people//addresses.xml", {}, nil, 404
- mock.head "/people/1.xml", {}, nil, 200
- mock.head "/people/Greg.xml", {}, nil, 200
- mock.head "/people/99.xml", {}, nil, 404
- mock.head "/people/1/addresses/1.xml", {}, nil, 200
- mock.head "/people/1/addresses/2.xml", {}, nil, 404
- mock.head "/people/2/addresses/1.xml", {}, nil, 404
- mock.head "/people/Greg/addresses/1.xml", {}, nil, 200
- # customer
- mock.get "/customers/1.xml", {}, @luis
- end
-
+ setup_response # find me in abstract_unit
@original_person_site = Person.site
- Person.user = nil
- Person.password = nil
end
def teardown
@@ -554,9 +463,9 @@ class BaseTest < Test::Unit::TestCase
assert Person.collection_path(:gender => 'male', :student => true).include?('gender=male')
assert Person.collection_path(:gender => 'male', :student => true).include?('student=true')
- assert_equal '/people.xml?name[]=bob&name[]=your+uncle%2Bme&name[]=&name[]=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false])
+ assert_equal '/people.xml?name%5B%5D=bob&name%5B%5D=your+uncle%2Bme&name%5B%5D=&name%5B%5D=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false])
- assert_equal '/people.xml?struct[a][]=2&struct[a][]=1&struct[b]=fred', Person.collection_path(:struct => ActiveSupport::OrderedHash[:a, [2,1], 'b', 'fred'])
+ assert_equal '/people.xml?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => ActiveSupport::OrderedHash[:a, [2,1], 'b', 'fred'])
end
def test_custom_element_path
@@ -566,6 +475,12 @@ class BaseTest < Test::Unit::TestCase
assert_equal '/people/ann%20mary/addresses/ann%20mary.xml', StreetAddress.element_path(:'ann mary', 'person_id' => 'ann mary')
end
+ def test_custom_element_path_without_required_prefix_param
+ assert_raise ActiveResource::MissingPrefixParam do
+ StreetAddress.element_path(1)
+ end
+ end
+
def test_module_element_path
assert_equal '/sounds/1.xml', Asset::Sound.element_path(1)
end
@@ -597,13 +512,19 @@ class BaseTest < Test::Unit::TestCase
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :person_id => 1, :type => 'work')
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, 'person_id' => 1, :type => 'work')
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :type => 'work', :person_id => 1)
- assert_equal '/people/1/addresses/1.xml?type[]=work&type[]=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
+ assert_equal '/people/1/addresses/1.xml?type%5B%5D=work&type%5B%5D=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
end
def test_custom_element_path_with_prefix_and_parameters
assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, {:person_id => 1}, {:type => 'work'})
end
+ def test_custom_collection_path_without_required_prefix_param
+ assert_raise ActiveResource::MissingPrefixParam do
+ StreetAddress.collection_path
+ end
+ end
+
def test_custom_collection_path
assert_equal '/people/1/addresses.xml', StreetAddress.collection_path(:person_id => 1)
assert_equal '/people/1/addresses.xml', StreetAddress.collection_path('person_id' => 1)
@@ -651,6 +572,8 @@ class BaseTest < Test::Unit::TestCase
assert_equal Set.new([:the_param1]), person_class.prefix_parameters
person_class.prefix = "the_prefix/:the_param2"
assert_equal Set.new([:the_param2]), person_class.prefix_parameters
+ person_class.prefix = "the_prefix/:the_param1/other_prefix/:the_param2"
+ assert_equal Set.new([:the_param2, :the_param1]), person_class.prefix_parameters
end
end
@@ -713,6 +636,14 @@ class BaseTest < Test::Unit::TestCase
assert_nil p.__send__(:id_from_response, resp)
end
+ def test_load_attributes_from_response
+ p = Person.new
+ resp = ActiveResource::Response.new(nil)
+ resp['Content-Length'] = "100"
+ assert_nil p.__send__(:load_attributes_from_response, resp)
+ end
+
+
def test_create_with_custom_prefix
matzs_house = StreetAddress.new(:person_id => 1)
matzs_house.save
@@ -945,7 +876,7 @@ class BaseTest < Test::Unit::TestCase
end
########################################################################
- # Tests the more miscelaneous helper methods
+ # Tests the more miscellaneous helper methods
########################################################################
def test_exists
# Class method.
@@ -1042,6 +973,12 @@ class BaseTest < Test::Unit::TestCase
Person.element_name = old_elem_name
end
+ def test_to_xml_with_private_method_name_as_attribute
+ assert_nothing_raised(ArgumentError) {
+ Customer.new(:test => true).to_xml
+ }
+ end
+
def test_to_json
Person.include_root_in_json = true
Person.format = :json
@@ -1113,4 +1050,56 @@ class BaseTest < Test::Unit::TestCase
end
end
end
+
+ def test_with_custom_formatter
+ @addresses = [{:id => "1", :street => "1 Infinite Loop", :city => "Cupertino", :state => "CA"}].to_xml(:root => 'addresses')
+
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.get "/addresses.xml", {}, @addresses, 200
+ end
+
+ # late bind the site
+ AddressResource.site = "http://localhost"
+ addresses = AddressResource.find(:all)
+
+ assert_equal "Cupertino, CA", addresses.first.city_state
+ end
+
+ def test_create_with_custom_primary_key
+ silver_plan = {:code => "silver", :price => 5.00}.to_xml(:root => "plan")
+
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.post "/plans.xml", {}, silver_plan, 201, 'Location' => '/plans/silver.xml'
+ end
+
+ plan = SubscriptionPlan.new(:code => "silver", :price => 5.00)
+ assert plan.new?
+
+ plan.save!
+ assert !plan.new?
+ end
+
+ def test_update_with_custom_primary_key
+ silver_plan = {:code => "silver", :price => 5.00}.to_xml(:root => "plan")
+ silver_plan_updated = {:code => "silver", :price => 10.00}.to_xml(:root => "plan")
+
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.get "/plans/silver.xml", {}, silver_plan
+ mock.put "/plans/silver.xml", {}, silver_plan_updated, 201, 'Location' => '/plans/silver.xml'
+ end
+
+ plan = SubscriptionPlan.find("silver")
+ assert !plan.new?
+ assert_equal 5.00, plan.price
+
+ # update price
+ plan.price = 10.00
+ plan.save!
+ assert_equal 10.00, plan.price
+ end
+
+ def test_namespacing
+ sound = Asset::Sound.find(1)
+ assert_equal "Asset::Sound::Author", sound.author.class.to_s
+ end
end
diff --git a/activeresource/test/cases/finder_test.rb b/activeresource/test/cases/finder_test.rb
index 1f52868966..ebb783996d 100644
--- a/activeresource/test/cases/finder_test.rb
+++ b/activeresource/test/cases/finder_test.rb
@@ -8,101 +8,7 @@ require 'active_support/core_ext/hash/conversions'
class FinderTest < Test::Unit::TestCase
def setup
- # TODO: refactor/DRY this setup - it's a copy of the BaseTest setup.
- # We can probably put this into abstract_unit
- @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person')
- @david = { :id => 2, :name => 'David' }.to_xml(:root => 'person')
- @greg = { :id => 3, :name => 'Greg' }.to_xml(:root => 'person')
- @addy = { :id => 1, :street => '12345 Street' }.to_xml(:root => 'address')
- @default_request_headers = { 'Content-Type' => 'application/xml' }
- @rick = { :name => "Rick", :age => 25 }.to_xml(:root => "person")
- @people = [{ :id => 1, :name => 'Matz' }, { :id => 2, :name => 'David' }].to_xml(:root => 'people')
- @people_david = [{ :id => 2, :name => 'David' }].to_xml(:root => 'people')
- @addresses = [{ :id => 1, :street => '12345 Street' }].to_xml(:root => 'addresses')
-
- # - deep nested resource -
- # - Luis (Customer)
- # - JK (Customer::Friend)
- # - Mateo (Customer::Friend::Brother)
- # - Edith (Customer::Friend::Brother::Child)
- # - Martha (Customer::Friend::Brother::Child)
- # - Felipe (Customer::Friend::Brother)
- # - Bryan (Customer::Friend::Brother::Child)
- # - Luke (Customer::Friend::Brother::Child)
- # - Eduardo (Customer::Friend)
- # - Sebas (Customer::Friend::Brother)
- # - Andres (Customer::Friend::Brother::Child)
- # - Jorge (Customer::Friend::Brother::Child)
- # - Elsa (Customer::Friend::Brother)
- # - Natacha (Customer::Friend::Brother::Child)
- # - Milena (Customer::Friend::Brother)
- #
- @luis = {:id => 1, :name => 'Luis',
- :friends => [{:name => 'JK',
- :brothers => [{:name => 'Mateo',
- :children => [{:name => 'Edith'},{:name => 'Martha'}]},
- {:name => 'Felipe',
- :children => [{:name => 'Bryan'},{:name => 'Luke'}]}]},
- {:name => 'Eduardo',
- :brothers => [{:name => 'Sebas',
- :children => [{:name => 'Andres'},{:name => 'Jorge'}]},
- {:name => 'Elsa',
- :children => [{:name => 'Natacha'}]},
- {:name => 'Milena',
- :children => []}]}]}.to_xml(:root => 'customer')
- # - resource with yaml array of strings; for ARs using serialize :bar, Array
- @marty = <<-eof.strip
- <?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <person>
- <id type=\"integer\">5</id>
- <name>Marty</name>
- <colors type=\"yaml\">---
- - \"red\"
- - \"green\"
- - \"blue\"
- </colors>
- </person>
- eof
-
- ActiveResource::HttpMock.respond_to do |mock|
- mock.get "/people/1.xml", {}, @matz
- mock.get "/people/2.xml", {}, @david
- mock.get "/people/5.xml", {}, @marty
- mock.get "/people/Greg.xml", {}, @greg
- mock.get "/people/4.xml", {'key' => 'value'}, nil, 404
- mock.put "/people/1.xml", {}, nil, 204
- mock.delete "/people/1.xml", {}, nil, 200
- mock.delete "/people/2.xml", {}, nil, 400
- mock.get "/people/99.xml", {}, nil, 404
- mock.post "/people.xml", {}, @rick, 201, 'Location' => '/people/5.xml'
- mock.get "/people.xml", {}, @people
- mock.get "/people/1/addresses.xml", {}, @addresses
- mock.get "/people/1/addresses/1.xml", {}, @addy
- mock.get "/people/1/addresses/2.xml", {}, nil, 404
- mock.get "/people/2/addresses.xml", {}, nil, 404
- mock.get "/people/2/addresses/1.xml", {}, nil, 404
- mock.get "/people/Greg/addresses/1.xml", {}, @addy
- mock.put "/people/1/addresses/1.xml", {}, nil, 204
- mock.delete "/people/1/addresses/1.xml", {}, nil, 200
- mock.post "/people/1/addresses.xml", {}, nil, 201, 'Location' => '/people/1/addresses/5'
- mock.get "/people//addresses.xml", {}, nil, 404
- mock.get "/people//addresses/1.xml", {}, nil, 404
- mock.put "/people//addresses/1.xml", {}, nil, 404
- mock.delete "/people//addresses/1.xml", {}, nil, 404
- mock.post "/people//addresses.xml", {}, nil, 404
- mock.head "/people/1.xml", {}, nil, 200
- mock.head "/people/Greg.xml", {}, nil, 200
- mock.head "/people/99.xml", {}, nil, 404
- mock.head "/people/1/addresses/1.xml", {}, nil, 200
- mock.head "/people/1/addresses/2.xml", {}, nil, 404
- mock.head "/people/2/addresses/1.xml", {}, nil, 404
- mock.head "/people/Greg/addresses/1.xml", {}, nil, 200
- # customer
- mock.get "/customers/1.xml", {}, @luis
- end
-
- Person.user = nil
- Person.password = nil
+ setup_response # find me in abstract_unit
end
def test_find_by_id
@@ -178,7 +84,7 @@ class FinderTest < Test::Unit::TestCase
def test_find_by_id_not_found
assert_raise(ActiveResource::ResourceNotFound) { Person.find(99) }
- assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1) }
+ assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(99, :params => {:person_id => 1}) }
end
def test_find_all_sub_objects
diff --git a/activeresource/test/cases/format_test.rb b/activeresource/test/cases/format_test.rb
index c3733e13d8..fc1a7b8c6f 100644
--- a/activeresource/test/cases/format_test.rb
+++ b/activeresource/test/cases/format_test.rb
@@ -33,7 +33,7 @@ class FormatTest < Test::Unit::TestCase
ActiveResource::HttpMock.respond_to.get "/people.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@programmers)
remote_programmers = Person.find(:all)
assert_equal 2, remote_programmers.size
- assert remote_programmers.select { |p| p.name == 'David' }
+ assert remote_programmers.find { |p| p.name == 'David' }
end
end
end
diff --git a/activeresource/test/cases/http_mock_test.rb b/activeresource/test/cases/http_mock_test.rb
index 5e032d03f1..43cf5f5ef0 100644
--- a/activeresource/test/cases/http_mock_test.rb
+++ b/activeresource/test/cases/http_mock_test.rb
@@ -59,6 +59,136 @@ class HttpMockTest < ActiveSupport::TestCase
assert_equal "XML", request(method, "/people/1", FORMAT_HEADER[method] => "application/xml").body
assert_equal "Json", request(method, "/people/1", FORMAT_HEADER[method] => "application/json").body
end
+
+ test "raises InvalidRequestError if no response found for the #{method} request" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(method, "/people/1", {FORMAT_HEADER[method] => "application/xml"}, "XML")
+ end
+
+ assert_raise(::ActiveResource::InvalidRequestError) do
+ request(method, "/people/1", FORMAT_HEADER[method] => "application/json")
+ end
+ end
+
+ end
+
+ test "allows you to send in pairs directly to the respond_to method" do
+ matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
+
+ create_matz = ActiveResource::Request.new(:post, '/people.xml', matz, {})
+ created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.xml"})
+ get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
+ ok_response = ActiveResource::Response.new(matz, 200, {})
+
+ pairs = {create_matz => created_response, get_matz => ok_response}
+
+ ActiveResource::HttpMock.respond_to(pairs)
+ assert_equal 2, ActiveResource::HttpMock.responses.length
+ assert_equal "", ActiveResource::HttpMock.responses.assoc(create_matz)[1].body
+ assert_equal matz, ActiveResource::HttpMock.responses.assoc(get_matz)[1].body
+ end
+
+ test "resets all mocked responses on each call to respond_to with a block by default" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/2", {}, "XML2")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+ end
+
+ test "resets all mocked responses on each call to respond_to by passing pairs by default" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
+ get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
+ ok_response = ActiveResource::Response.new(matz, 200, {})
+ ActiveResource::HttpMock.respond_to({get_matz => ok_response})
+
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+ end
+
+ test "allows you to add new responses to the existing responses by calling a block" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ ActiveResource::HttpMock.respond_to(false) do |mock|
+ mock.send(:get, "/people/2", {}, "XML2")
+ end
+ assert_equal 2, ActiveResource::HttpMock.responses.length
+ end
+
+ test "allows you to add new responses to the existing responses by passing pairs" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
+ get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
+ ok_response = ActiveResource::Response.new(matz, 200, {})
+ ActiveResource::HttpMock.respond_to({get_matz => ok_response}, false)
+
+ assert_equal 2, ActiveResource::HttpMock.responses.length
+ end
+
+ test "allows you to replace the existing reponse with the same request by calling a block" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ ActiveResource::HttpMock.respond_to(false) do |mock|
+ mock.send(:get, "/people/1", {}, "XML2")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+ end
+
+ test "allows you to replace the existing reponse with the same request by passing pairs" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
+ get_matz = ActiveResource::Request.new(:get, '/people/1', nil)
+ ok_response = ActiveResource::Response.new(matz, 200, {})
+
+ ActiveResource::HttpMock.respond_to({get_matz => ok_response}, false)
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+ end
+
+ test "do not replace the response with the same path but different method by calling a block" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ ActiveResource::HttpMock.respond_to(false) do |mock|
+ mock.send(:put, "/people/1", {}, "XML2")
+ end
+ assert_equal 2, ActiveResource::HttpMock.responses.length
+ end
+
+ test "do not replace the response with the same path but different method by passing pairs" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ put_matz = ActiveResource::Request.new(:put, '/people/1', nil)
+ ok_response = ActiveResource::Response.new("", 200, {})
+
+ ActiveResource::HttpMock.respond_to({put_matz => ok_response}, false)
+ assert_equal 2, ActiveResource::HttpMock.responses.length
end
def request(method, path, headers = {}, body = nil)
diff --git a/activeresource/test/cases/validations_test.rb b/activeresource/test/cases/validations_test.rb
index 82546424f2..3b1caecb04 100644
--- a/activeresource/test/cases/validations_test.rb
+++ b/activeresource/test/cases/validations_test.rb
@@ -3,7 +3,7 @@ require 'fixtures/project'
require 'active_support/core_ext/hash/conversions'
# The validations are tested thoroughly under ActiveModel::Validations
-# This test case simply makes sur that they are all accessible by
+# This test case simply makes sure that they are all accessible by
# Active Resource objects.
class ValidationsTest < ActiveModel::TestCase
VALID_PROJECT_HASH = { :name => "My Project", :description => "A project" }
@@ -24,7 +24,7 @@ class ValidationsTest < ActiveModel::TestCase
assert p.save, "should have saved after fixing the validation, but had: #{p.errors.inspect}"
end
-
+
def test_fails_save!
p = new_project(:name => nil)
assert_raise(ActiveResource::ResourceInvalid) { p.save! }
@@ -36,14 +36,6 @@ class ValidationsTest < ActiveModel::TestCase
assert p.save(:validate => false)
end
- def test_deprecated_save_without_validation
- p = new_project(:name => nil)
- assert !p.save
- assert_deprecated do
- assert p.save(false)
- end
- end
-
def test_validate_callback
# we have a callback ensuring the description is longer than three letters
p = new_project(:description => 'a')
@@ -56,6 +48,12 @@ class ValidationsTest < ActiveModel::TestCase
assert p.save, "should have saved after fixing the validation, but had: #{p.errors.inspect}"
end
+ def test_client_side_validation_maximum
+ project = Project.new(:description => '123456789012345')
+ assert ! project.valid?
+ assert_equal ['is too long (maximum is 10 characters)'], project.errors[:description]
+ end
+
protected
# quickie helper to create a new project with all the required
diff --git a/activeresource/test/connection_test.rb b/activeresource/test/connection_test.rb
index a2744d7531..6e79845aa0 100644
--- a/activeresource/test/connection_test.rb
+++ b/activeresource/test/connection_test.rb
@@ -44,7 +44,7 @@ class ConnectionTest < Test::Unit::TestCase
# 401 is an unauthorized request
assert_response_raises ActiveResource::UnauthorizedAccess, 401
- # 403 is a forbidden requst (and authorizing will not help)
+ # 403 is a forbidden request (and authorizing will not help)
assert_response_raises ActiveResource::ForbiddenAccess, 403
# 404 is a missing resource.
@@ -120,7 +120,7 @@ class ConnectionTest < Test::Unit::TestCase
end
def test_get
- matz = @conn.get("/people/1.xml")
+ matz = decode(@conn.get("/people/1.xml"))
assert_equal "Matz", matz["name"]
end
@@ -131,23 +131,23 @@ class ConnectionTest < Test::Unit::TestCase
end
def test_get_with_header
- david = @conn.get("/people/2.xml", @header)
+ david = decode(@conn.get("/people/2.xml", @header))
assert_equal "David", david["name"]
end
def test_get_collection
- people = @conn.get("/people.xml")
+ people = decode(@conn.get("/people.xml"))
assert_equal "Matz", people[0]["name"]
assert_equal "David", people[1]["name"]
end
-
+
def test_get_collection_single
- people = @conn.get("/people_single_elements.xml")
+ people = decode(@conn.get("/people_single_elements.xml"))
assert_equal "Matz", people[0]["name"]
end
-
+
def test_get_collection_empty
- people = @conn.get("/people_empty_elements.xml")
+ people = decode(@conn.get("/people_empty_elements.xml"))
assert_equal [], people
end
@@ -250,4 +250,8 @@ class ConnectionTest < Test::Unit::TestCase
def handle_response(response)
@conn.__send__(:handle_response, response)
end
+
+ def decode(response)
+ @conn.format.decode(response.body)
+ end
end
diff --git a/activeresource/test/fixtures/address.rb b/activeresource/test/fixtures/address.rb
new file mode 100644
index 0000000000..7a73ecb52a
--- /dev/null
+++ b/activeresource/test/fixtures/address.rb
@@ -0,0 +1,19 @@
+# turns everything into the same object
+class AddressXMLFormatter
+ include ActiveResource::Formats::XmlFormat
+
+ def decode(xml)
+ data = ActiveResource::Formats::XmlFormat.decode(xml)
+ # process address fields
+ data.each do |address|
+ address['city_state'] = "#{address['city']}, #{address['state']}"
+ end
+ data
+ end
+
+end
+
+class AddressResource < ActiveResource::Base
+ self.element_name = "address"
+ self.format = AddressXMLFormatter.new
+end \ No newline at end of file
diff --git a/activeresource/test/fixtures/project.rb b/activeresource/test/fixtures/project.rb
index e15fa6f620..53de666601 100644
--- a/activeresource/test/fixtures/project.rb
+++ b/activeresource/test/fixtures/project.rb
@@ -1,25 +1,18 @@
# used to test validations
class Project < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
+ schema do
+ string :email
+ string :name
+ end
- validates_presence_of :name
+ validates :name, :presence => true
+ validates :description, :presence => false, :length => {:maximum => 10}
validate :description_greater_than_three_letters
# to test the validate *callback* works
def description_greater_than_three_letters
errors.add :description, 'must be greater than three letters long' if description.length < 3 unless description.blank?
end
-
-
- # stop-gap accessor to default this attribute to nil
- # Otherwise the validations fail saying that the method does not exist.
- # In future, method_missing will be updated to not explode on a known
- # attribute.
- def name
- attributes['name'] || nil
- end
- def description
- attributes['description'] || nil
- end
end
diff --git a/activeresource/test/fixtures/sound.rb b/activeresource/test/fixtures/sound.rb
index 5c0ef5d55c..d9d2b99fcd 100644
--- a/activeresource/test/fixtures/sound.rb
+++ b/activeresource/test/fixtures/sound.rb
@@ -1,5 +1,9 @@
-module Asset
+module Asset
class Sound < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
end
+
+# to test namespacing in a module
+class Author
+end \ No newline at end of file
diff --git a/activeresource/test/fixtures/subscription_plan.rb b/activeresource/test/fixtures/subscription_plan.rb
new file mode 100644
index 0000000000..e3c2dd9a74
--- /dev/null
+++ b/activeresource/test/fixtures/subscription_plan.rb
@@ -0,0 +1,5 @@
+class SubscriptionPlan < ActiveResource::Base
+ self.site = "http://37s.sunrise.i:3000"
+ self.element_name = 'plan'
+ self.primary_key = :code
+end
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
index 8485e7d46b..373236ce9a 100644
--- a/activesupport/CHANGELOG
+++ b/activesupport/CHANGELOG
@@ -1,4 +1,33 @@
-*Rails 3.0.0 [release candidate] (July 26th, 2010)*
+*Rails 3.1.0 (unreleased)*
+
+* LocalCache strategy is now a real middleware class, not an anonymous class
+posing for pictures.
+
+* ActiveSupport::Dependencies::ClassCache class has been introduced for
+holding references to reloadable classes.
+
+* ActiveSupport::Dependencies::Reference has been refactored to take direct
+advantage of the new ClassCache.
+
+* Backports Range#cover? as an alias for Range#include? in Ruby 1.8 [Diego Carrion, fxn]
+
+* Added weeks_ago and prev_week to Date/DateTime/Time. [Rob Zolkos, fxn]
+
+* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White]
+
+*Rails 3.0.2 (unreleased)*
+
+* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White]
+
+*Rails 3.0.1 (October 15, 2010)*
+
+* No Changes, just a version bump.
+
+*Rails 3.0.0 (August 29, 2010)*
+
+* Implemented String#strip_heredoc. [fxn]
+
+* Pluggable cache stores: setting config.cache_store = "custom_store" will require 'active_support/cache/custom_store' and look for the CustomStore constant. #5486 [Mike Perham]
* Removed Object#returning, Object#tap should be used instead. [Santiago Pastorino]
@@ -18,9 +47,6 @@
* Date#since, #ago, #beginning_of_day, #end_of_day, and #xmlschema honor now the user time zone if set. [Geoff Buesing]
-
-*Rails 3.0.0 [beta 4] (June 8th, 2010)*
-
* Extracted String#truncate from TextHelper#truncate [DHH]
* Ruby 1.9: support UTF-8 case folding. #4595 [Norman Clarke]
@@ -73,32 +99,23 @@
* JSON: encode objects that don't have a native JSON representation using to_hash, if available, instead of instance_values (the old fallback) or to_s (other encoders' default). Encode BigDecimal and Regexp encode as strings to conform with other encoders. Try to transcode non-UTF-8 strings. [Jeremy Kemper]
-
-*Rails 3.0.0 [beta 3] (April 13th, 2010)*
-
* HashWithIndifferentAccess: remove inherited symbolize_keys! since its keys are always strings. [Santiago Pastorino]
* Improve transliteration quality. #4374 [Norman Clarke]
* Speed up and add Ruby 1.9 support for ActiveSupport::Multibyte::Chars#tidy_bytes. #4350 [Norman Clarke]
-
-*Rails 3.0.0 [beta 2] (April 1st, 2010)*
-
* Reduced load time by deferring configuration of classes using
ActiveSupport::on_load(:component_name) [YK]
* Rename #metaclass to #singleton_class now that ruby-core has decided [JK]
-* New assertions assert_blank and assert_present. #4299 [Juanjo Bazan]
+* New assertions assert_blank and assert_present. #4299 [Juanjo Bazan]
* Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice. [Jeremy Kemper]
* JSON backend for YAJL. Preferred if available. #2666 [Brian Lopez]
-
-*Rails 3.0.0 [beta 1] (February 4, 2010)*
-
* Introduce class_attribute to declare inheritable class attributes. Writing an attribute on a subclass behaves just like overriding the superclass reader method. Unifies and replaces most usage of cattr_accessor, class_inheritable_attribute, superclass_delegating_attribute, and extlib_inheritable_attribute. [Jeremy Kemper, Yehuda Katz]
* Time#- with a DateTime argument behaves the same as with a Time argument, i.e. returns the difference between self and arg as a Float #3476 [Geoff Buesing]
@@ -243,10 +260,10 @@ ActiveSupport.escape_html_entities_in_json from true to false to match previousl
* Fix Ruby's Time marshaling bug in pre-1.9 versions of Ruby: utc instances are now correctly unmarshaled with a utc zone instead of the system local zone [#900 state:resolved] [Luca Guidi, Geoff Buesing]
* Add Array#in_groups which splits or iterates over the array in specified number of groups. #579. [Adrian Mugnolo] Example:
-
+
a = (1..10).to_a
- a.in_groups(3) #=> [[1, 2, 3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]
- a.in_groups(3, false) #=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
+ a.in_groups(3) # => [[1, 2, 3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]
+ a.in_groups(3, false) # => [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
* Fix TimeWithZone unmarshaling: coerce unmarshaled Time instances to utc, because Ruby's marshaling of Time instances doesn't respect the zone [Geoff Buesing]
@@ -331,7 +348,7 @@ ActiveSupport.escape_html_entities_in_json from true to false to match previousl
* TZInfo: Removing unneeded TimezoneProxy class [Geoff Buesing]
-* TZInfo: Removing unneeded TimezoneIndexDefinition, since we're not including Indexes::Timezones [Geoff Buesing]
+* TZInfo: Removing unneeded TimezoneIndexDefinition, since we're not including Indexes::Timezones [Geoff Buesing]
* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled [Geoff Buesing]
@@ -339,7 +356,7 @@ ActiveSupport.escape_html_entities_in_json from true to false to match previousl
* TimeWithZone#marshal_load does zone lookup via Time.get_zone, so that tzinfo/Olson identifiers are handled [Geoff Buesing]
-* Time.zone= accepts TZInfo::Timezone instances and Olson identifiers; wraps result in TimeZone instance [Geoff Buesing]
+* Time.zone= accepts TZInfo::Timezone instances and Olson identifiers; wraps result in TimeZone instance [Geoff Buesing]
* TimeWithZone time conversions don't need to be wrapped in TimeOrDateTime, because TZInfo does this internally [Geoff Buesing]
@@ -433,7 +450,7 @@ ActiveSupport.escape_html_entities_in_json from true to false to match previousl
* TimeZone#to_s uses UTC rather than GMT; reapplying change that was undone in [8679]. #1689 [Cheah Chu Yeow]
-* Time.days_in_month defaults to current year if no year is supplied as argument #10799 [Radar], uses Date.gregorian_leap? to determine leap year, and uses constant lookup to determine days in month [Geoff Buesing]
+* Time.days_in_month defaults to current year if no year is supplied as argument #10799 [Radar], uses Date.gregorian_leap? to determine leap year, and uses constant lookup to determine days in month [Geoff Buesing]
* Adding Time and DateTime #compare_with_coercion, which layers behavior on #<=> so that any combination of Time, DateTime and ActiveSupport::TimeWithZone instances can be chronologically compared [Geoff Buesing]
@@ -510,7 +527,7 @@ ActiveSupport.escape_html_entities_in_json from true to false to match previousl
* Introduce a base class for all test cases used by rails applications. ActiveSupport::TestCase [Michael Koziarski]
- The intention is to use this to reduce the amount of monkeypatching / overriding that
+ The intention is to use this to reduce the amount of monkeypatching / overriding that
is done to test/unit's classes.
* Document Enumerable and Hash #to_json. #9970 [Cheah Chu Yeow]
@@ -679,14 +696,14 @@ ActiveSupport.escape_html_entities_in_json from true to false to match previousl
<name>David</name>
<avatar type="file" name="me.jpg" content_type="image/jpg">R0lGODlhkACZAPUAAM5lcfjrtMQCG=\n</avatar>
</person>
-
+
...becomes:
-
+
attributes = { :person => { :name => "David", :avatar => #<StringIO> } }
attributes[:person][:avatar].content_type # => "image/jpg"
attributes[:person][:avatar].original_filename # => "me.jpg"
attributes[:person][:avatar].read # => binary data of the file
-
+
Which is duck-type compatible with the files that you get when doing multipart uploads through HTML.
* Improved multibyte performance by relying less on exception raising #8159 [Blaine]
@@ -889,11 +906,11 @@ public for compatibility. [Jeremy Kemper]
class Content < ActiveRecord::Base
# has a title attribute
end
-
+
class Email < ActiveRecord::Base
alias_attribute :subject, :title
end
-
+
e = Email.find(1)
e.title # => "Superstars"
e.subject # => "Superstars"
@@ -942,7 +959,7 @@ public for compatibility. [Jeremy Kemper]
* Enhance Symbol#to_proc so it works with list objects, such as multi-dimensional arrays. Closes #5295 [nov@yo.rim.or.jp]. Example:
{1 => "one", 2 => "two", 3 => "three"}.sort_by(&:first).map(&:last)
- #=> ["one", "two", "three"]
+ # => ["one", "two", "three"]
* Added Hash.create_from_xml(string) which will create a hash from a XML string and even typecast if possible [David Heinemeier Hansson]. Example:
@@ -952,9 +969,9 @@ public for compatibility. [Jeremy Kemper]
<created-at type="date">2004-10-10</created-at>
</note>
EOT
-
+
...would return:
-
+
{ :note => { :title => "This is a note", :created_at => Date.new(2004, 10, 10) } }
* Added Jim Weirich's excellent FlexMock class to vendor (Copyright 2003, 2004 by Jim Weirich (jim@weriichhouse.org)) -- it's not automatically required, though, so require 'flexmock' is still necessary [David Heinemeier Hansson]
@@ -966,28 +983,28 @@ public for compatibility. [Jeremy Kemper]
* Add OrderedHash#values. [Sam Stephenson]
* Added Array#to_s(:db) that'll produce a comma-separated list of ids [David Heinemeier Hansson]. Example:
-
+
Purchase.find(:all, :conditions => "product_id IN (#{shops.products.to_s(:db)})"
-* Normalize classify's argument to a String so that it plays nice with Symbols. [Marcel Molina Jr.]
+* Normalize classify's argument to a String so that it plays nice with Symbols. [Marcel Molina Jr.]
* Strip out leading schema name in classify. References #5139. [Michael Schoen]
* Remove Enumerable#first_match since break(value) handles the use case well enough. [Nicholas Seckar]
Enumerable#first_match was like detect, but instead of returning the matching element, the yielded value returned. For example:
-
+
user_xml = adapters(:from => User, :to => Xml).first_match do |adapter|
adapter.adapt @user
end
-
+
But this is just as easily done with:
-
+
user_xml = adapters(:from => User, :to => Xml).each do
break adapter.adapt(@user)
end
-
-* Make Array#in_groups_of just return the grouped collection if a block isn't given. [Marcel Molina Jr.]
+
+* Make Array#in_groups_of just return the grouped collection if a block isn't given. [Marcel Molina Jr.]
* Don't destroy a HashWithIndifferentAccess if symbolize_keys! or stringify_keys! is called on it. Closes #5076. [Marcel Molina Jr., guy.naor@famundo.com]
@@ -999,7 +1016,7 @@ public for compatibility. [Jeremy Kemper]
* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-* Allow default options in with_options to be overridden. Closes #4480. [murphy@cYcnus.de]
+* Allow default options in with_options to be overridden. Closes #4480. [murphy@cYcnus.de]
* Added Module#alias_method_chain [Jamis Buck]
@@ -1050,7 +1067,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
* Added Hash#to_xml and Array#to_xml that makes it much easier to produce XML from basic structures [David Heinemeier Hansson]. Examples:
{ :name => "David", :street_name => "Paulina", :age => 26, :moved_on => Date.new(2005, 11, 15) }.to_xml
-
+
...returns:
<person>
@@ -1069,7 +1086,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
ex.
- latest_transcripts.group_by(&:day).each do |day, transcripts|
+ latest_transcripts.group_by(&:day).each do |day, transcripts|
p "#{day} -> #{transcripts.map(&:class) * ', '}"
end
"2006-03-01 -> Transcript"
@@ -1093,7 +1110,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
* Add 'around' methods to Logger, to make it easy to log before and after messages for a given block as requested in #3809. [Michael Koziarski] Example:
- logger.around_info("Start rendering component (#{options.inspect}): ",
+ logger.around_info("Start rendering component (#{options.inspect}): ",
"\n\nEnd of component rendering") { yield }
* Added Time#beginning_of_quarter #3607 [cohen.jeff@gmail.com]
@@ -1111,7 +1128,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
delegate :free?, :paying?, :to => :subscription
delegate :overdue?, :to => "subscription.last_payment"
end
-
+
account.free? # => account.subscription.free?
account.overdue? # => account.subscription.last_payment.overdue?
@@ -1126,7 +1143,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
* Add Reloadable::Subclasses which handles the common case where a base class should not be reloaded, but its subclasses should be. [Nicholas Seckar]
* Further improvements to reloading code [Nicholas Seckar, Trevor Squires]
-
+
- All classes/modules which include Reloadable can define reloadable? for fine grained control of reloading
- Class.remove_class uses Module#parent to access the parent module
- Class.remove_class expanded to handle multiple classes in a single call
@@ -1138,7 +1155,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
class Setting
include Reloadable
end
-
+
Reloading a class is done by removing its constant which will cause it to be loaded again on the next reference. [David Heinemeier Hansson]
* Added auto-loading support for classes in modules, so Conductor::Migration will look for conductor/migration.rb and Conductor::Database::Settings will look for conductor/database/settings.rb [Nicholas Seckar]
@@ -1175,7 +1192,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
* Add Symbol#to_proc, which allows for, e.g. [:foo, :bar].map(&:to_s). [Marcel Molina Jr.]
* Added the following methods [Marcel Molina Jr., Sam Stephenson]:
- * Object#copy_instance_variables_from(object) to copy instance variables from one object to another
+ * Object#copy_instance_variables_from(object) to copy instance variables from one object to another
* Object#extended_by to get an instance's included/extended modules
* Object#extend_with_included_modules_from(object) to extend an instance with the modules from another instance
@@ -1226,7 +1243,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
*1.2.0* (October 16th, 2005)
-* Update Exception extension to show the first few framework frames in an application trace. [Nicholas Seckar]
+* Update Exception extension to show the first few framework frames in an application trace. [Nicholas Seckar]
* Added Exception extension to provide support for clean backtraces. [Nicholas Seckar]
@@ -1275,9 +1292,9 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
Inflector.inflections do |inflect|
inflect.plural /^(ox)$/i, '\1\2en'
inflect.singular /^(ox)en/i, '\1'
-
+
inflect.irregular 'octopus', 'octopi'
-
+
inflect.uncountable "equipment"
end
@@ -1360,9 +1377,9 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
* Added Object#suppress which allows you to make a saner choice around with exceptions to swallow #980. Example:
suppress(ZeroDivisionError) { 1/0 }
-
+
...instead of:
-
+
1/0 rescue nil # BAD, EVIL, DIRTY.
@@ -1376,7 +1393,7 @@ approximations and shouldn't be used for critical calculations. [Michael Koziars
values << 'baz'
end
end
-
+
foo # => ['bar', 'baz']
diff --git a/activesupport/MIT-LICENSE b/activesupport/MIT-LICENSE
index cd928b856d..5e8b7a9450 100644
--- a/activesupport/MIT-LICENSE
+++ b/activesupport/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2005-2010 David Heinemeier Hansson
+Copyright (c) 2005-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc
index 77b8a64304..13ca4b3bf1 100644
--- a/activesupport/README.rdoc
+++ b/activesupport/README.rdoc
@@ -14,7 +14,7 @@ The latest version of Active Support can be installed with Rubygems:
Source code can be downloaded as part of the Rails project on GitHub
-* http://github.com/rails/rails/tree/master/activesupport/
+* https://github.com/rails/rails/tree/master/activesupport/
== License
diff --git a/activesupport/Rakefile b/activesupport/Rakefile
index 8e2683ef89..d117ca6356 100644..100755
--- a/activesupport/Rakefile
+++ b/activesupport/Rakefile
@@ -1,7 +1,4 @@
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
require 'rake/testtask'
-require 'rdoc/task'
require 'rake/gempackagetask'
task :default => :test
@@ -9,6 +6,7 @@ Rake::TestTask.new do |t|
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.warning = true
+ t.verbose = true
end
namespace :test do
@@ -20,19 +18,6 @@ end
# Create compressed packages
dist_dirs = [ "lib", "test"]
-# Genereate the RDoc documentation
-
-RDoc::Task.new { |rdoc|
- rdoc.rdoc_dir = 'doc'
- rdoc.title = "Active Support -- Utility classes and standard library extensions from Rails"
- rdoc.options << '-f' << 'horo'
- rdoc.options << '--main' << 'README.rdoc'
- rdoc.options << '--charset' << 'utf-8'
- rdoc.rdoc_files.include('README.rdoc', 'CHANGELOG')
- rdoc.rdoc_files.include('lib/active_support.rb')
- rdoc.rdoc_files.include('lib/active_support/**/*.rb')
-}
-
spec = eval(File.read('activesupport.gemspec'))
Rake::GemPackageTask.new(spec) do |p|
diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables
index 51edb59c77..5fefa429df 100644
--- a/activesupport/bin/generate_tables
+++ b/activesupport/bin/generate_tables
@@ -45,7 +45,7 @@ module ActiveSupport
([0-9]+); # canonical combining class
([A-Z]+); # bidi class
(<([A-Z]*)>)? # decomposition type
- ((\ ?[0-9A-F]+)*); # decompomposition mapping
+ ((\ ?[0-9A-F]+)*); # decomposition mapping
([0-9]*); # decimal digit
([0-9]*); # digit
([^;]*); # numeric
@@ -70,7 +70,7 @@ module ActiveSupport
end
def parse_grapheme_break_property(line)
- if line =~ /^([0-9A-F\.]+)\s*;\s*([\w]+)\s*#/
+ if line =~ /^([0-9A-F.]+)\s*;\s*([\w]+)\s*#/
type = $2.downcase.intern
@ucd.boundary[type] ||= []
if $1.include? '..'
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index ba91e8bba3..6b662ac660 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -35,12 +35,14 @@ module ActiveSupport
end
require "active_support/dependencies/autoload"
+require "active_support/version"
module ActiveSupport
extend ActiveSupport::Autoload
autoload :DescendantsTracker
autoload :FileUpdateChecker
+ autoload :FileWatcher
autoload :LogSubscriber
autoload :Notifications
diff --git a/activesupport/lib/active_support/backtrace_cleaner.rb b/activesupport/lib/active_support/backtrace_cleaner.rb
index 8465bc1e10..0e6bc30fa2 100644
--- a/activesupport/lib/active_support/backtrace_cleaner.rb
+++ b/activesupport/lib/active_support/backtrace_cleaner.rb
@@ -8,7 +8,7 @@ module ActiveSupport
# 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.
#
- # Example:
+ # ==== Example:
#
# bc = BacktraceCleaner.new
# bc.add_filter { |line| line.gsub(Rails.root, '') }
diff --git a/activesupport/lib/active_support/base64.rb b/activesupport/lib/active_support/base64.rb
index b8c01628ce..35014cb3d5 100644
--- a/activesupport/lib/active_support/base64.rb
+++ b/activesupport/lib/active_support/base64.rb
@@ -7,7 +7,7 @@ module ActiveSupport
if defined? ::Base64
Base64 = ::Base64
else
- # Base64 provides utility methods for encoding and de-coding binary data
+ # Base64 provides utility methods for encoding and de-coding binary data
# using a base 64 representation. A base 64 representation of binary data
# consists entirely of printable US-ASCII characters. The Base64 module
# is included in Ruby 1.8, but has been removed in Ruby 1.9.
@@ -15,7 +15,7 @@ module ActiveSupport
# Encodes a string to its base 64 representation. Each 60 characters of
# output is separated by a newline character.
#
- # ActiveSupport::Base64.encode64("Original unencoded string")
+ # ActiveSupport::Base64.encode64("Original unencoded string")
# # => "T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==\n"
def self.encode64(data)
[data].pack("m")
@@ -23,7 +23,7 @@ module ActiveSupport
# Decodes a base 64 encoded string to its original representation.
#
- # ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==")
+ # ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==")
# # => "Original unencoded string"
def self.decode64(data)
data.unpack("m").first
diff --git a/activesupport/lib/active_support/benchmarkable.rb b/activesupport/lib/active_support/benchmarkable.rb
index ee02ecb043..df62c18f41 100644
--- a/activesupport/lib/active_support/benchmarkable.rb
+++ b/activesupport/lib/active_support/benchmarkable.rb
@@ -3,10 +3,10 @@ require 'active_support/core_ext/hash/keys'
module ActiveSupport
module Benchmarkable
- # Allows you to measure the execution time of a block
+ # 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
+ # 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 %>
@@ -23,7 +23,7 @@ module ActiveSupport
# <%= lowlevel_files_operation %>
# <% end %>
#
- # Finally, you can pass true as the third argument to silence all log activity
+ # Finally, you can pass true as the third argument to silence all log activity
# inside the block. This is great for boiling down a noisy block to just a single statement:
#
# <% benchmark "Process data files", :level => :info, :silence => true do %>
diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb
index b861a6f62a..e41731f3e7 100644
--- a/activesupport/lib/active_support/buffered_logger.rb
+++ b/activesupport/lib/active_support/buffered_logger.rb
@@ -1,3 +1,4 @@
+require 'thread'
require 'active_support/core_ext/class/attribute_accessors'
module ActiveSupport
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index 30195bdea5..10c457bb1d 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -58,7 +58,14 @@ module ActiveSupport
case store
when Symbol
store_class_name = store.to_s.camelize
- store_class = ActiveSupport::Cache.const_get(store_class_name)
+ store_class =
+ begin
+ require "active_support/cache/#{store}"
+ rescue LoadError => e
+ raise "Could not find cache store adapter for #{store} (#{e})"
+ else
+ ActiveSupport::Cache.const_get(store_class_name)
+ end
store_class.new(*parameters)
when nil
ActiveSupport::Cache::MemoryStore.new
@@ -200,26 +207,26 @@ module ActiveSupport
#
# 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 construction in which call all entries will be
+ # be specified as an option to the construction in which call all entries will be
# affected. Or it can be supplied to the +fetch+ or +write+ method for just one entry.
#
- # cache = ActiveSupport::Cache::MemoryStore.new(:expire_in => 5.minutes)
- # cache.write(key, value, :expire_in => 1.minute) # Set a lower value for 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 unver 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
+ # 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
+ # 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
+ # 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.
@@ -410,7 +417,7 @@ module ActiveSupport
raise NotImplementedError.new("#{self.class.name} does not support decrement")
end
- # Cleanup the cache by removing expired entries.
+ # Cleanup the cache by removing expired entries.
#
# Options are passed to the underlying cache implementation.
#
@@ -419,7 +426,7 @@ module ActiveSupport
raise NotImplementedError.new("#{self.class.name} does not support cleanup")
end
- # Clear the entire cache. Be careful with this method since it could
+ # 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.
@@ -473,23 +480,24 @@ module ActiveSupport
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
+ # 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:
- if key.respond_to?(:cache_key)
- key = key.cache_key.to_s
- elsif key.is_a?(Array)
+ return key.cache_key.to_s if key.respond_to?(:cache_key)
+
+ case key
+ when Array
if key.size > 1
- key.collect{|element| expanded_key(element)}.to_param
+ key = key.collect{|element| expanded_key(element)}
else
- key.first.to_param
+ key = key.first
end
- elsif key.is_a?(Hash)
- key = key.to_a.sort{|a,b| a.first.to_s <=> b.first.to_s}.collect{|k,v| "#{k}=#{v}"}.to_param
- else
- key = key.to_param
+ 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.
@@ -582,11 +590,7 @@ module ActiveSupport
# Check if the entry is expired. The +expires_in+ parameter can override the
# value set when the entry was created.
def expired?
- if @expires_in && @created_at + @expires_in <= Time.now.to_f
- true
- else
- false
- end
+ @expires_in && @created_at + @expires_in <= Time.now.to_f
end
# Set a new time when the entry will expire.
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index 84f6f29572..18182bbb40 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/file/atomic'
require 'active_support/core_ext/string/conversions'
+require 'rack/utils'
module ActiveSupport
module Cache
@@ -11,8 +12,6 @@ module ActiveSupport
attr_reader :cache_path
DIR_FORMATTER = "%03X"
- ESCAPE_FILENAME_CHARS = /[^a-z0-9_.-]/i
- UNESCAPE_FILENAME_CHARS = /%[0-9A-F]{2}/
def initialize(cache_path, options = nil)
super(options)
@@ -136,7 +135,7 @@ module ActiveSupport
# Translate a key into a file path.
def key_file_path(key)
- fname = key.to_s.gsub(ESCAPE_FILENAME_CHARS){|match| "%#{match.ord.to_s(16).upcase}"}
+ fname = Rack::Utils.escape(key)
hash = Zlib.adler32(fname)
hash, dir_1 = hash.divmod(0x1000)
dir_2 = hash.modulo(0x1000)
@@ -156,7 +155,7 @@ module ActiveSupport
# Translate a file path into a key.
def file_path_key(path)
fname = path[cache_path.size, path.size].split(File::SEPARATOR, 4).last
- fname.gsub(UNESCAPE_FILENAME_CHARS){|match| $1.ord.to_s(16)}
+ Rack::Utils.unescape(fname)
end
# Delete empty directories in the cache.
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index f32b562368..45263d482f 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -1,7 +1,7 @@
begin
require 'memcache'
rescue LoadError => e
- $stderr.puts "You don't have memcache installed in your application. Please add it to your Gemfile and run bundle install"
+ $stderr.puts "You don't have memcache-client installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
require 'digest/md5'
@@ -73,7 +73,7 @@ module ActiveSupport
def read_multi(*names)
options = names.extract_options!
options = merged_options(options)
- keys_to_names = names.inject({}){|map, name| map[escape_key(namespaced_key(name, options))] = name; map}
+ 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|
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
index 3edba52fc4..0649a058aa 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -16,7 +16,7 @@ module ActiveSupport
@data = {}
end
- # Don't allow synchronizing since it isn't thread safe,
+ # Don't allow synchronizing since it isn't thread safe,
def synchronize # :nodoc:
yield
end
@@ -50,34 +50,39 @@ module ActiveSupport
end
end
- # Middleware class can be inserted as a Rack handler to be local cache for the
- # duration of request.
- def middleware
- @middleware ||= begin
- klass = Class.new
- klass.class_eval(<<-EOS, __FILE__, __LINE__ + 1)
- class << self
- def name
- "ActiveSupport::Cache::Strategy::LocalCache"
- end
- alias :to_s :name
- end
+ #--
+ # This class wraps up local storage for middlewares. Only the middleware method should
+ # construct them.
+ class Middleware # :nodoc:
+ attr_reader :name, :thread_local_key
- def initialize(app)
- @app = app
- end
+ def initialize(name, thread_local_key)
+ @name = name
+ @thread_local_key = thread_local_key
+ @app = nil
+ end
- def call(env)
- Thread.current[:#{thread_local_key}] = LocalStore.new
- @app.call(env)
- ensure
- Thread.current[:#{thread_local_key}] = nil
- end
- EOS
- klass
+ def new(app)
+ @app = app
+ self
+ end
+
+ def call(env)
+ Thread.current[thread_local_key] = LocalStore.new
+ @app.call(env)
+ ensure
+ Thread.current[thread_local_key] = nil
end
end
+ # Middleware class can be inserted as a Rack handler to be local cache for the
+ # duration of request.
+ def middleware
+ @middleware ||= Middleware.new(
+ "ActiveSupport::Cache::Strategy::LocalCache",
+ thread_local_key)
+ end
+
def clear(options = nil) # :nodoc:
local_cache.clear(options) if local_cache
super
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 24e407c253..418102352f 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -1,31 +1,33 @@
+require 'active_support/concern'
require 'active_support/descendants_tracker'
require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/class/inheritable_attributes'
+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 hooks into the lifecycle of an object that allow you to trigger logic
- # before or after an alteration of the object state.
+ # \Callbacks are code hooks that are run at key points in an object's lifecycle.
+ # The typical use case is to have a base class define a set of callbacks relevant
+ # to the other functionality it supplies, so that subclasses can install callbacks
+ # that enhance or modify the base functionality without needing to override
+ # or redefine methods of the base class.
#
- # Mixing in this module allows you to define callbacks in your class.
+ # Mixing in this module allows you to define the events in the object's lifecycle
+ # that will support callbacks (via +ClassMethods.define_callbacks+), set the instance
+ # methods, procs, or callback objects to be called (via +ClassMethods.set_callback+),
+ # and run the installed callbacks at the appropriate times (via +run_callbacks+).
#
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :save
- # end
+ # 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 ConfigStorage < Storage
- # set_callback :save, :before, :saving_message
- # def saving_message
- # puts "saving..."
- # end
+ # ==== Example
#
- # set_callback :save, :after do |object|
- # puts "saved"
- # end
+ # class Record
+ # include ActiveSupport::Callbacks
+ # define_callbacks :save
#
# def save
# run_callbacks :save do
@@ -34,29 +36,7 @@ module ActiveSupport
# end
# end
#
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # saving...
- # - save
- # saved
- #
- # Callbacks from parent classes are inherited.
- #
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :save
- #
- # set_callback :save, :before, :prepare
- # def prepare
- # puts "preparing save"
- # end
- # end
- #
- # class ConfigStorage < Storage
+ # class PersonRecord < Record
# set_callback :save, :before, :saving_message
# def saving_message
# puts "saving..."
@@ -65,19 +45,12 @@ module ActiveSupport
# set_callback :save, :after do |object|
# puts "saved"
# end
- #
- # def save
- # run_callbacks :save do
- # puts "- save"
- # end
- # end
# end
#
- # config = ConfigStorage.new
- # config.save
+ # person = PersonRecord.new
+ # person.save
#
# Output:
- # preparing save
# saving...
# - save
# saved
@@ -89,11 +62,25 @@ module ActiveSupport
extend ActiveSupport::DescendantsTracker
end
+ # Runs the callbacks for the given event.
+ #
+ # Calls the before and around callbacks in the order they were set, yields
+ # the block (if given one), and then runs the after callbacks in reverse order.
+ # Optionally accepts a key, which will be used to compile an optimized callback
+ # method for each key. See +ClassMethods.define_callbacks+ for more information.
+ #
+ # If the callback chain was halted, returns +false+. Otherwise returns the result
+ # of the block, or +true+ if no block is given.
+ #
+ # run_callbacks :save do
+ # save
+ # end
+ #
def run_callbacks(kind, *args, &block)
send("_run_#{kind}_callbacks", *args, &block)
end
- class Callback
+ class Callback #:nodoc:#
@@_callback_sequence = 0
attr_accessor :chain, :filter, :kind, :options, :per_key, :klass, :raw_filter
@@ -178,49 +165,52 @@ module ActiveSupport
# options[0] is the compiled form of supplied conditions
# options[1] is the "end" for the conditional
#
- if @kind == :before || @kind == :around
- if @kind == :before
- # if condition # before_save :filter_name, :if => :condition
- # filter_name
- # end
- filter = <<-RUBY_EVAL
- unless halted
- result = #{@filter}
- halted = (#{chain.config[:terminator]})
- end
- RUBY_EVAL
-
- [@compiled_options[0], filter, @compiled_options[1]].compact.join("\n")
- else
- # Compile around filters with conditions into proxy methods
- # that contain the conditions.
- #
- # For `around_save :filter_name, :if => :condition':
- #
- # def _conditional_callback_save_17
- # if condition
- # filter_name do
- # yield self
- # end
- # else
- # yield self
- # end
- # end
- #
- name = "_conditional_callback_#{@kind}_#{next_id}"
- @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- def #{name}(halted)
- #{@compiled_options[0] || "if true"} && !halted
- #{@filter} do
- yield self
- end
- else
+ case @kind
+ when :before
+ # if condition # before_save :filter_name, :if => :condition
+ # filter_name
+ # end
+ filter = <<-RUBY_EVAL
+ unless halted
+ # This double assignment is to prevent warnings in 1.9.3. I would
+ # remove the `result` variable, but apparently some other
+ # generated code is depending on this variable being set sometimes
+ # and sometimes not.
+ result = result = #{@filter}
+ halted = (#{chain.config[:terminator]})
+ end
+ RUBY_EVAL
+
+ [@compiled_options[0], filter, @compiled_options[1]].compact.join("\n")
+ when :around
+ # Compile around filters with conditions into proxy methods
+ # that contain the conditions.
+ #
+ # For `around_save :filter_name, :if => :condition':
+ #
+ # def _conditional_callback_save_17
+ # if condition
+ # filter_name do
+ # yield self
+ # end
+ # else
+ # yield self
+ # end
+ # end
+ #
+ name = "_conditional_callback_#{@kind}_#{next_id}"
+ @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{name}(halted)
+ #{@compiled_options[0] || "if true"} && !halted
+ #{@filter} do
yield self
end
+ else
+ yield self
end
- RUBY_EVAL
- "#{name}(halted) do"
- end
+ end
+ RUBY_EVAL
+ "#{name}(halted) do"
end
end
@@ -229,15 +219,17 @@ module ActiveSupport
def end(key=nil, object=nil)
return if key && !object.send("_one_time_conditions_valid_#{@callback_id}?")
- if @kind == :around || @kind == :after
+ case @kind
+ when :after
# if condition # after_save :filter_name, :if => :condition
# filter_name
# end
- if @kind == :after
- [@compiled_options[0], @filter, @compiled_options[1]].compact.join("\n")
- else
- "end"
+ [@compiled_options[0], @filter, @compiled_options[1]].compact.join("\n")
+ when :around
+ <<-RUBY_EVAL
+ value
end
+ RUBY_EVAL
end
end
@@ -330,7 +322,7 @@ module ActiveSupport
end
# An Array with a compile method
- class CallbackChain < Array
+ class CallbackChain < Array #:nodoc:#
attr_reader :name, :config
def initialize(name, config)
@@ -375,20 +367,9 @@ module ActiveSupport
end
module ClassMethods
- # Make the run_callbacks :save method. The generated method takes
- # a block that it'll yield to. It'll call the before and around filters
- # in order, yield the block, and then run the after filters.
- #
- # run_callbacks :save do
- # save
- # end
- #
- # The run_callbacks :save method can optionally take a key, which
- # will be used to compile an optimized callback method for each
- # key. See #define_callbacks for more information.
- #
+ # Generate the internal runner method called by +run_callbacks+.
def __define_runner(symbol) #:nodoc:
- body = send("_#{symbol}_callbacks").compile(nil)
+ body = send("_#{symbol}_callbacks").compile
silence_warnings do
undef_method "_run_#{symbol}_callbacks" if method_defined?("_run_#{symbol}_callbacks")
@@ -435,21 +416,52 @@ module ActiveSupport
options = filters.last.is_a?(Hash) ? filters.pop : {}
filters.unshift(block) if block
- ([self] + ActiveSupport::DescendantsTracker.descendants(self)).each do |target|
+ ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
chain = target.send("_#{name}_callbacks")
- yield chain, type, filters, options
+ yield target, chain.dup, type, filters, options
target.__define_runner(name)
end
end
- # Set callbacks for a previously defined callback.
+ # Install a callback for the given event.
#
- # Syntax:
# set_callback :save, :before, :before_meth
# set_callback :save, :after, :after_meth, :if => :condition
- # set_callback :save, :around, lambda { |r| stuff; yield; stuff }
+ # set_callback :save, :around, lambda { |r| stuff; result = yield; 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+.
#
- # Use skip_callback to skip any defined one.
+ # 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.
+ # * <tt>:per_key</tt> - A hash with <tt>:if</tt> and <tt>:unless</tt> options;
+ # see "Per-key conditions" below.
+ #
+ # ===== Per-key conditions
#
# When creating or skipping callbacks, you can specify conditions that
# are always the same for a given key. For instance, in Action Pack,
@@ -459,12 +471,12 @@ module ActiveSupport
#
# becomes
#
- # dispatch_callback :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
+ # set_callback :process_action, :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
#
- # Per-Key conditions are evaluated only once per use of a given key.
+ # Per-key conditions are evaluated only once per use of a given key.
# In the case of the above example, you would do:
#
- # run_callbacks(:dispatch, action_name) { ... dispatch stuff ... }
+ # run_callbacks(:process_action, action_name) { ... dispatch stuff ... }
#
# In that case, each action_name would get its own compiled callback
# method that took into consideration the per_key conditions. This
@@ -473,27 +485,30 @@ module ActiveSupport
def set_callback(name, *filter_list, &block)
mapped = nil
- __update_callbacks(name, filter_list, block) do |chain, type, filters, options|
+ __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
filters.each do |filter|
- chain.delete_if {|c| c.matches?(type, filter) }
+ chain.delete_if {|c| c.matches?(type, filter) }
end
- options[:prepend] ? chain.unshift(*mapped) : chain.push(*mapped)
+ options[:prepend] ? chain.unshift(*(mapped.reverse)) : chain.push(*mapped)
+
+ target.send("_#{name}_callbacks=", chain)
end
end
- # Skip a previously defined callback.
+ # Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or <tt>:unless</tt>
+ # options may be passed in order to control when the callback is skipped.
#
# class Writer < Person
# skip_callback :validate, :before, :check_membership, :if => lambda { self.age > 18 }
# end
#
def skip_callback(name, *filter_list, &block)
- __update_callbacks(name, filter_list, block) do |chain, type, filters, options|
+ __update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
filters.each do |filter|
filter = chain.find {|c| c.matches?(type, filter) }
@@ -505,93 +520,98 @@ module ActiveSupport
chain.delete(filter)
end
+ target.send("_#{name}_callbacks=", chain)
end
end
- # Reset callbacks for a given type.
+ # 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")
+ chain = target.send("_#{symbol}_callbacks").dup
callbacks.each { |c| chain.delete(c) }
+ target.send("_#{symbol}_callbacks=", chain)
target.__define_runner(symbol)
end
- callbacks.clear
+ self.send("_#{symbol}_callbacks=", callbacks.dup.clear)
+
__define_runner(symbol)
end
- # Defines callbacks types:
+ # Define sets of events in the object lifecycle that support callbacks.
#
# define_callbacks :validate
+ # define_callbacks :initialize, :save, :destroy
#
- # This macro accepts the following options:
+ # ===== Options
#
- # * <tt>:terminator</tt> - Indicates when a before filter is considered
- # to halted. This is a string to be eval'ed and has the result of the
- # very filter available in the <tt>result</tt> variable:
+ # * <tt>:terminator</tt> - Determines when a before filter will halt the callback
+ # chain, preventing following callbacks from being called and the event from being
+ # triggered. This is a string to be eval'ed. The result of the callback is available
+ # in the <tt>result</tt> variable.
#
- # define_callbacks :validate, :terminator => "result == false"
+ # define_callbacks :validate, :terminator => "result == false"
#
- # In the example above, if any before validate callbacks returns +false+,
- # other callbacks are not executed. Defaults to "false", meaning no value
- # halts the chain.
+ # In this example, if any before validate callbacks returns +false+,
+ # other callbacks are not executed. Defaults to "false", meaning no value
+ # halts the chain.
#
# * <tt>:rescuable</tt> - By default, after filters are not executed if
- # the given block or a before filter raises an error. Set this option to
- # true to change this behavior.
+ # the given block or a before filter raises an error. By setting this option
+ # to <tt>true</tt> exception raised by given block is stored and after
+ # executing all the after callbacks the stored exception is raised.
#
- # * <tt>:scope</tt> - Indicates which methods should be executed when a class
- # is given as callback. Defaults to <tt>[:kind]</tt>.
+ # * <tt>:scope</tt> - Indicates which methods should be executed when an object
+ # is used as a callback.
#
- # class Audit
- # def before(caller)
- # puts 'Audit: before is called'
- # end
+ # class Audit
+ # def before(caller)
+ # puts 'Audit: before is called'
+ # end
#
- # def before_save(caller)
- # puts 'Audit: before_save is called'
- # end
- # end
+ # def before_save(caller)
+ # puts 'Audit: before_save is called'
+ # end
+ # end
#
- # class Account
- # include ActiveSupport::Callbacks
+ # class Account
+ # include ActiveSupport::Callbacks
#
- # define_callbacks :save
- # set_callback :save, :before, Audit.new
+ # define_callbacks :save
+ # set_callback :save, :before, Audit.new
#
- # def save
- # run_callbacks :save do
- # puts 'save in main'
- # end
- # end
- # end
+ # def save
+ # run_callbacks :save do
+ # puts 'save in main'
+ # end
+ # end
+ # end
#
- # In the above case whenever you save an account the method <tt>Audit#before</tt> will
- # be called. On the other hand
+ # In the above case whenever you save an account the method <tt>Audit#before</tt> will
+ # be called. On the other hand
#
- # define_callbacks :save, :scope => [:kind, :name]
+ # define_callbacks :save, :scope => [:kind, :name]
#
- # would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
- # <tt>"#{kind}_#{name}"</tt> on the given instance. In this case "kind" is "before" and
- # "name" is "save". In this context ":kind" and ":name" have special meanings: ":kind"
- # refers to the kind of callback (before/after/around) and ":name" refers to the
- # method on which callbacks are being defined.
+ # would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
+ # <tt>#{kind}_#{name}</tt> on the given instance. In this case "kind" is "before" and
+ # "name" is "save". In this context +:kind+ and +:name+ have special meanings: +:kind+
+ # refers to the kind of callback (before/after/around) and +:name+ refers to the
+ # method on which callbacks are being defined.
#
- # A declaration like
+ # A declaration like
#
- # define_callbacks :save, :scope => [:name]
+ # define_callbacks :save, :scope => [:name]
#
- # would call <tt>Audit#save</tt>.
+ # would call <tt>Audit#save</tt>.
#
def define_callbacks(*callbacks)
config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
callbacks.each do |callback|
- extlib_inheritable_reader("_#{callback}_callbacks") do
- CallbackChain.new(callback, config)
- end
+ class_attribute "_#{callback}_callbacks"
+ send("_#{callback}_callbacks=", CallbackChain.new(callback, config))
__define_runner(callback)
end
end
diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb
index 2d87e8d0e5..81fb859334 100644
--- a/activesupport/lib/active_support/concern.rb
+++ b/activesupport/lib/active_support/concern.rb
@@ -1,39 +1,109 @@
-# A typical module looks like this
-#
-# module M
-# def self.included(base)
-# base.send(:extend, ClassMethods)
-# base.send(:include, InstanceMethods)
-# scope :foo, :conditions => { :created_at => nil }
-# end
-#
-# module ClassMethods
-# def cm; puts 'I am a class method'; end
-# end
-#
-# module InstanceMethods
-# def im; puts 'I am an instance method'; end
-# end
-# end
-#
-# By using <tt>ActiveSupport::Concern</tt> the above module could instead be written as:
-#
-# module M
-# extend ActiveSupport::Concern
-#
-# included do
-# scope :foo, :conditions => { :created_at => nil }
-# end
-#
-# module ClassMethods
-# def cm; puts 'I am a class method'; end
-# end
-#
-# module InstanceMethods
-# def im; puts 'I am an instance method'; end
-# end
-# end
module ActiveSupport
+ # A typical module looks like this:
+ #
+ # module M
+ # def self.included(base)
+ # base.extend ClassMethods
+ # base.send(:include, InstanceMethods)
+ # scope :disabled, where(:disabled => true)
+ # end
+ #
+ # module ClassMethods
+ # ...
+ # end
+ #
+ # module InstanceMethods
+ # ...
+ # end
+ # end
+ #
+ # By using <tt>ActiveSupport::Concern</tt> the above module could instead be written as:
+ #
+ # require 'active_support/concern'
+ #
+ # module M
+ # extend ActiveSupport::Concern
+ #
+ # included do
+ # scope :disabled, where(:disabled => true)
+ # end
+ #
+ # module ClassMethods
+ # ...
+ # end
+ #
+ # module InstanceMethods
+ # ...
+ # 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
+ # class_eval do
+ # def self.method_injected_by_foo
+ # ...
+ # end
+ # 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)
base.instance_variable_set("@_dependencies", [])
diff --git a/activesupport/lib/active_support/configurable.rb b/activesupport/lib/active_support/configurable.rb
index f562e17c75..8c56a21ef7 100644
--- a/activesupport/lib/active_support/configurable.rb
+++ b/activesupport/lib/active_support/configurable.rb
@@ -4,18 +4,52 @@ require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/module/delegation'
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.reject {|key| respond_to?(key)})
+ end
+
+ # compiles reader methods so we don't have to go through method_missing
+ def self.compile_methods!(keys)
+ keys.each do |key|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{key}; _get(#{key.inspect}); end
+ RUBY
+ end
+ end
+ end
+
module ClassMethods
def config
- @config ||= ActiveSupport::InheritableOptions.new(superclass.respond_to?(:config) ? superclass.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.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :allowed_access
+ # end
+ #
+ # user = User.new
+ # user.allowed_access = true
+ # user.allowed_access # => true
+ #
def config_accessor(*names)
names.each do |name|
code, line = <<-RUBY, __LINE__ + 1
@@ -29,8 +63,25 @@ module ActiveSupport
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 ||= ActiveSupport::InheritableOptions.new(self.class.config)
+ @_config ||= self.class.config.inheritable_copy
end
end
-end \ No newline at end of file
+end
+
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
index 7585137aca..baefa9cae4 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -26,7 +26,7 @@ class Array
when 0
""
when 1
- self[0].to_s
+ self[0].to_s.dup
when 2
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
else
diff --git a/activesupport/lib/active_support/core_ext/array/random_access.rb b/activesupport/lib/active_support/core_ext/array/random_access.rb
index edac7278bc..ab1fa7cd5b 100644
--- a/activesupport/lib/active_support/core_ext/array/random_access.rb
+++ b/activesupport/lib/active_support/core_ext/array/random_access.rb
@@ -1,10 +1,10 @@
class Array
- # Backport of Array#sample based on Marc-Andre Lafortune's http://github.com/marcandre/backports/
- # Returns a random element or +n+ random elements from the array.
+ # Backport of Array#sample based on Marc-Andre Lafortune's https://github.com/marcandre/backports/
+ # Returns a random element or +n+ random elements from the array.
# If the array is empty and +n+ is nil, returns <tt>nil</tt>. if +n+ is passed, returns <tt>[]</tt>.
- #
- # [1,2,3,4,5,6].sample # => 4
- # [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
+ #
+ # [1,2,3,4,5,6].sample # => 4
+ # [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
# [].sample # => nil
# [].sample(3) # => []
def sample(n=nil)
@@ -24,4 +24,4 @@ class Array
result[n..size] = []
result
end unless method_defined? :sample
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/core_ext/array/wrap.rb b/activesupport/lib/active_support/core_ext/array/wrap.rb
index 06b2acd662..7fabae3138 100644
--- a/activesupport/lib/active_support/core_ext/array/wrap.rb
+++ b/activesupport/lib/active_support/core_ext/array/wrap.rb
@@ -10,7 +10,7 @@ class Array
# 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>
diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
index f7f03f4d95..080604147d 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -1,23 +1,38 @@
require 'bigdecimal'
+
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
class BigDecimal
YAML_TAG = 'tag:yaml.org,2002:float'
YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
- yaml_as YAML_TAG
-
# This emits the number without any scientific notation.
# This is better than self.to_f.to_s since it doesn't lose precision.
#
# Note that reconstituting YAML floats to native floats may lose precision.
def to_yaml(opts = {})
+ return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
+
YAML.quick_emit(nil, opts) do |out|
string = to_s
out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain)
end
end
+ def encode_with(coder)
+ string = to_s
+ coder.represent_scalar(nil, YAML_MAPPING[string] || string)
+ end
+
+ def to_d
+ self
+ end
+
DEFAULT_STRING_FORMAT = 'F'
def to_formatted_s(format = DEFAULT_STRING_FORMAT)
_original_to_s(format)
diff --git a/activesupport/lib/active_support/core_ext/cgi.rb b/activesupport/lib/active_support/core_ext/cgi.rb
deleted file mode 100644
index 7279a3d4da..0000000000
--- a/activesupport/lib/active_support/core_ext/cgi.rb
+++ /dev/null
@@ -1 +0,0 @@
-require 'active_support/core_ext/cgi/escape_skipping_slashes'
diff --git a/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb b/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb
deleted file mode 100644
index d3c3575748..0000000000
--- a/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-require 'cgi'
-
-class CGI #:nodoc:
- if RUBY_VERSION >= '1.9'
- def self.escape_skipping_slashes(str)
- str = str.join('/') if str.respond_to? :join
- str.gsub(/([^ \/a-zA-Z0-9_.-])/n) do
- "%#{$1.unpack('H2' * $1.bytesize).join('%').upcase}"
- end.tr(' ', '+')
- end
- else
- def self.escape_skipping_slashes(str)
- str = str.join('/') if str.respond_to? :join
- str.gsub(/([^ \/a-zA-Z0-9_.-])/n) do
- "%#{$1.unpack('H2').first.upcase}"
- end.tr(' ', '+')
- end
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb
index bfa57fe1f7..5414b3a18f 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute.rb
@@ -29,19 +29,19 @@ class Class
# In such cases, you don't want to do changes in places but use setters:
#
# Base.setting = []
- # Base.setting #=> []
- # Subclass.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]
+ # Base.setting # => [:foo]
+ # Subclass.setting # => [:foo]
#
# # Use setters to not propagate changes:
# Base.setting = []
# Subclass.setting += [:foo]
- # Base.setting #=> []
- # Subclass.setting #=> [:foo]
+ # Base.setting # => []
+ # Subclass.setting # => [:foo]
#
# For convenience, a query method is defined as well:
#
@@ -72,10 +72,21 @@ class Class
remove_possible_method(:#{name})
define_method(:#{name}) { val }
end
+
+ if singleton_class?
+ class_eval do
+ remove_possible_method(:#{name})
+ def #{name}
+ defined?(@#{name}) ? @#{name} : singleton_class.#{name}
+ end
+ end
+ end
+ val
end
+ remove_method :#{name} if method_defined?(:#{name})
def #{name}
- defined?(@#{name}) ? @#{name} : singleton_class.#{name}
+ defined?(@#{name}) ? @#{name} : self.class.#{name}
end
def #{name}?
@@ -86,4 +97,15 @@ class Class
attr_writer name if instance_writer
end
end
+
+ private
+ def singleton_class?
+ # in case somebody is crazy enough to overwrite allocate
+ allocate = Class.instance_method(:allocate)
+ # object.class always points to a real (non-singleton) class
+ allocate.bind(self).call.class != self
+ rescue TypeError
+ # MRI/YARV/JRuby all disallow creating new instances of a singleton class
+ true
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
index 4e35b1b488..a903735acf 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
@@ -12,8 +12,8 @@ require 'active_support/core_ext/array/extract_options'
# end
#
# Person.hair_colors = [:brown, :black, :blonde, :red]
-# Person.hair_colors #=> [:brown, :black, :blonde, :red]
-# Person.new.hair_colors #=> [:brown, :black, :blonde, :red]
+# Person.hair_colors # => [:brown, :black, :blonde, :red]
+# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
#
# To opt out of the instance writer method, pass :instance_writer => false.
# To opt out of the instance reader method, pass :instance_reader => false.
diff --git a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
index e844cf50d1..ca3db2349e 100644
--- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
+++ b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
@@ -1,13 +1,15 @@
require 'active_support/core_ext/object/duplicable'
require 'active_support/core_ext/array/extract_options'
+require 'active_support/deprecation'
# Retained for backward compatibility. Methods are now included in Class.
module ClassInheritableAttributes # :nodoc:
+ DEPRECATION_WARNING_MESSAGE = "class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first"
end
-# It is recommend to use <tt>class_attribute</tt> over methods defined in this file. Please
+# It is recommended to use <tt>class_attribute</tt> over methods defined in this file. Please
# refer to documentation for <tt>class_attribute</tt> for more information. Officially it is not
-# deprected but <tt>class_attribute</tt> is faster.
+# deprecated but <tt>class_attribute</tt> is faster.
#
# Allows attributes to be shared within an inheritance hierarchy. Each descendant gets a copy of
# their parents' attributes, instead of just a pointer to the same. This means that the child can add elements
@@ -22,8 +24,8 @@ end
# end
#
# Person.hair_colors = [:brown, :black, :blonde, :red]
-# Person.hair_colors #=> [:brown, :black, :blonde, :red]
-# Person.new.hair_colors #=> [:brown, :black, :blonde, :red]
+# Person.hair_colors # => [:brown, :black, :blonde, :red]
+# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
#
# To opt out of the instance writer method, pass :instance_writer => false.
# To opt out of the instance reader method, pass :instance_reader => false.
@@ -36,6 +38,7 @@ end
# Person.new.hair_colors # => NoMethodError
class Class # :nodoc:
def class_inheritable_reader(*syms)
+ ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE
options = syms.extract_options!
syms.each do |sym|
next if sym.is_a?(Hash)
@@ -54,6 +57,7 @@ class Class # :nodoc:
end
def class_inheritable_writer(*syms)
+ ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE
options = syms.extract_options!
syms.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@ -71,6 +75,7 @@ class Class # :nodoc:
end
def class_inheritable_array_writer(*syms)
+ ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE
options = syms.extract_options!
syms.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@ -88,6 +93,7 @@ class Class # :nodoc:
end
def class_inheritable_hash_writer(*syms)
+ ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE
options = syms.extract_options!
syms.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@ -124,6 +130,7 @@ class Class # :nodoc:
end
def write_inheritable_attribute(key, value)
+ ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE
if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES)
@inheritable_attributes = {}
end
@@ -141,10 +148,12 @@ class Class # :nodoc:
end
def read_inheritable_attribute(key)
+ ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE
inheritable_attributes[key]
end
def reset_inheritable_attributes
+ ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE
@inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES
end
@@ -158,9 +167,9 @@ class Class # :nodoc:
if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES)
new_inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES
else
- new_inheritable_attributes = inheritable_attributes.inject({}) do |memo, (key, value)|
- memo.update(key => value.duplicable? ? value.dup : value)
- end
+ new_inheritable_attributes = Hash[inheritable_attributes.map do |(key, value)|
+ [key, value.duplicable? ? value.dup : value]
+ end]
end
child.instance_variable_set('@inheritable_attributes', new_inheritable_attributes)
@@ -169,86 +178,3 @@ class Class # :nodoc:
alias inherited_without_inheritable_attributes inherited
alias inherited inherited_with_inheritable_attributes
end
-
-class Class
- # Defines class-level inheritable attribute reader. Attributes are available to subclasses,
- # each subclass has a copy of parent's attribute.
- #
- # @param *syms<Array[#to_s]> Array of attributes to define inheritable reader for.
- # @return <Array[#to_s]> Array of attributes converted into inheritable_readers.
- #
- # @api public
- #
- # @todo Do we want to block instance_reader via :instance_reader => false
- # @todo It would be preferable that we do something with a Hash passed in
- # (error out or do the same as other methods above) instead of silently
- # moving on). In particular, this makes the return value of this function
- # less useful.
- def extlib_inheritable_reader(*ivars, &block)
- options = ivars.extract_options!
-
- ivars.each do |ivar|
- self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def self.#{ivar}
- return @#{ivar} if self.object_id == #{self.object_id} || defined?(@#{ivar})
- ivar = superclass.#{ivar}
- return nil if ivar.nil? && !#{self}.instance_variable_defined?("@#{ivar}")
- @#{ivar} = ivar.duplicable? ? ivar.dup : ivar
- end
- RUBY
- unless options[:instance_reader] == false
- self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{ivar}
- self.class.#{ivar}
- end
- RUBY
- end
- instance_variable_set(:"@#{ivar}", yield) if block_given?
- end
- end
-
- # Defines class-level inheritable attribute writer. Attributes are available to subclasses,
- # each subclass has a copy of parent's attribute.
- #
- # @param *syms<Array[*#to_s, Hash{:instance_writer => Boolean}]> Array of attributes to
- # define inheritable writer for.
- # @option syms :instance_writer<Boolean> if true, instance-level inheritable attribute writer is defined.
- # @return <Array[#to_s]> An Array of the attributes that were made into inheritable writers.
- #
- # @api public
- #
- # @todo We need a style for class_eval <<-HEREDOC. I'd like to make it
- # class_eval(<<-RUBY, __FILE__, __LINE__), but we should codify it somewhere.
- def extlib_inheritable_writer(*ivars)
- options = ivars.extract_options!
-
- ivars.each do |ivar|
- self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def self.#{ivar}=(obj)
- @#{ivar} = obj
- end
- RUBY
- unless options[:instance_writer] == false
- self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{ivar}=(obj) self.class.#{ivar} = obj end
- RUBY
- end
-
- self.send("#{ivar}=", yield) if block_given?
- end
- end
-
- # Defines class-level inheritable attribute accessor. Attributes are available to subclasses,
- # each subclass has a copy of parent's attribute.
- #
- # @param *syms<Array[*#to_s, Hash{:instance_writer => Boolean}]> Array of attributes to
- # define inheritable accessor for.
- # @option syms :instance_writer<Boolean> if true, instance-level inheritable attribute writer is defined.
- # @return <Array[#to_s]> An Array of attributes turned into inheritable accessors.
- #
- # @api public
- def extlib_inheritable_accessor(*syms, &block)
- extlib_inheritable_reader(*syms)
- extlib_inheritable_writer(*syms, &block)
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb
index 3e5d1a2a42..46e9daaa8f 100644
--- a/activesupport/lib/active_support/core_ext/class/subclasses.rb
+++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb
@@ -2,49 +2,35 @@ require 'active_support/core_ext/module/anonymous'
require 'active_support/core_ext/module/reachable'
class Class #:nodoc:
- # Rubinius
- if defined?(Class.__subclasses__)
- alias :subclasses :__subclasses__
+ begin
+ ObjectSpace.each_object(Class.new) {}
def descendants
descendants = []
- __subclasses__.each do |k|
- descendants << k
- descendants.concat k.descendants
+ ObjectSpace.each_object(class << self; self; end) do |k|
+ descendants.unshift k unless k == self
end
descendants
end
- else # MRI
- begin
- ObjectSpace.each_object(Class.new) {}
-
- def descendants
- descendants = []
- ObjectSpace.each_object(class << self; self; end) do |k|
- descendants.unshift k unless k == self
- end
- descendants
- end
- rescue StandardError # JRuby
- def descendants
- descendants = []
- ObjectSpace.each_object(Class) do |k|
- descendants.unshift k if k < self
- end
- descendants.uniq!
- descendants
+ rescue StandardError # JRuby
+ def descendants
+ descendants = []
+ ObjectSpace.each_object(Class) do |k|
+ descendants.unshift k if k < self
end
+ descendants.uniq!
+ descendants
end
+ end
- # Returns an array with the direct children of +self+.
- #
- # Integer.subclasses # => [Bignum, Fixnum]
- def subclasses
- subclasses, chain = [], descendants
- chain.each do |k|
- subclasses << k unless chain.any? { |c| c > k }
- end
- subclasses
+ # Returns an array with the direct children of +self+.
+ #
+ # Integer.subclasses # => [Bignum, Fixnum]
+ def subclasses
+ subclasses, chain = [], descendants
+ chain.each do |k|
+ subclasses << k unless chain.any? { |c| c > k }
end
+ subclasses
end
end
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index c5b54318ce..724e076407 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -5,9 +5,11 @@ require 'active_support/core_ext/date/zones'
require 'active_support/core_ext/time/zones'
class Date
+ DAYS_INTO_WEEK = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6 }
+
if RUBY_VERSION < '1.9'
undef :>>
-
+
# Backported from 1.9. The one in 1.8 leads to incorrect next_month and
# friends for dates where the calendar reform is involved. It additionally
# prevents an infinite loop fixed in r27013.
@@ -34,9 +36,9 @@ class Date
::Date.current.tomorrow
end
- # Returns Time.zone.today when config.time_zone is set, otherwise just returns Date.today.
+ # Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
def current
- ::Time.zone_default ? ::Time.zone.today : ::Date.today
+ ::Time.zone ? ::Time.zone.today : ::Date.today
end
end
@@ -127,6 +129,11 @@ class Date
)
end
+ # Returns a new Date/DateTime representing the time a number of specified weeks ago.
+ def weeks_ago(weeks)
+ advance(:weeks => -weeks)
+ end
+
# Returns a new Date/DateTime representing the time a number of specified months ago.
def months_ago(months)
advance(:months => -months)
@@ -156,7 +163,7 @@ class Date
def next_year
years_since(1)
end unless method_defined?(:next_year)
-
+
# Shorthand for months_ago(1)
def prev_month
months_ago(1)
@@ -185,10 +192,15 @@ class Date
alias :sunday :end_of_week
alias :at_end_of_week :end_of_week
+ # Returns a new Date/DateTime representing the start of the given day in the previous week (default is Monday).
+ def prev_week(day = :monday)
+ result = (self - 7).beginning_of_week + DAYS_INTO_WEEK[day]
+ self.acts_like?(:time) ? result.change(:hour => 0) : result
+ end
+
# Returns a new Date/DateTime representing the start of the given day in next week (default is Monday).
def next_week(day = :monday)
- days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6}
- result = (self + 7).beginning_of_week + days_into_week[day]
+ result = (self + 7).beginning_of_week + DAYS_INTO_WEEK[day]
self.acts_like?(:time) ? result.change(:hour => 0) : result
end
diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb
index 092f936961..769ead9544 100644
--- a/activesupport/lib/active_support/core_ext/date/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date/conversions.rb
@@ -1,5 +1,5 @@
require 'date'
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
require 'active_support/core_ext/date/zones'
class Date
@@ -93,6 +93,12 @@ class Date
::DateTime.civil(year, month, day, 0, 0, 0, 0)
end if RUBY_VERSION < '1.9'
+ def iso8601
+ strftime('%F')
+ end if RUBY_VERSION < '1.9'
+
+ alias_method :rfc3339, :iso8601 if RUBY_VERSION < '1.9'
+
def xmlschema
to_time_in_current_zone.xmlschema
end
diff --git a/activesupport/lib/active_support/core_ext/date/zones.rb b/activesupport/lib/active_support/core_ext/date/zones.rb
index 3a83af6be2..a70b47b7bc 100644
--- a/activesupport/lib/active_support/core_ext/date/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date/zones.rb
@@ -2,10 +2,10 @@ require 'date'
require 'active_support/core_ext/time/zones'
class Date
- # Converts Date to a TimeWithZone in the current zone if Time.zone_default is set,
- # otherwise converts Date to a Time via Date#to_time
+ # Converts Date to a TimeWithZone in the current zone if Time.zone or Time.zone_default
+ # is set, otherwise converts Date to a Time via Date#to_time
def to_time_in_current_zone
- if ::Time.zone_default
+ if ::Time.zone
::Time.zone.local(year, month, day)
else
to_time
diff --git a/activesupport/lib/active_support/core_ext/date_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
index 1dc3933e12..48cf1a435d 100644
--- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
@@ -1,6 +1,4 @@
require 'rational' unless RUBY_VERSION >= '1.9.2'
-require 'active_support/core_ext/object/acts_like'
-require 'active_support/core_ext/time/zones'
class DateTime
class << self
@@ -9,8 +7,9 @@ class DateTime
::Time.local(2007).utc_offset.to_r / 86400
end
+ # Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise returns <tt>Time.now.to_datetime</tt>.
def current
- ::Time.zone_default ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
+ ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end
end
@@ -82,6 +81,29 @@ class DateTime
change(:hour => 23, :min => 59, :sec => 59)
end
+ # 1.9.3 defines + and - on DateTime, < 1.9.3 do not.
+ if DateTime.public_instance_methods(false).include?(:+)
+ 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
+ end
+
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0
#
# Example:
@@ -104,11 +126,7 @@ class DateTime
end
# Layers additional behavior on DateTime#<=> so that Time and ActiveSupport::TimeWithZone instances can be compared with a DateTime
- def compare_with_coercion(other)
- other = other.comparable_time if other.respond_to?(:comparable_time)
- other = other.to_datetime unless other.acts_like?(:date)
- compare_without_coercion(other)
+ def <=>(other)
+ super other.to_datetime
end
- alias_method :compare_without_coercion, :<=>
- alias_method :<=>, :compare_with_coercion
end
diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
index 47b8aa59fb..21b84b994b 100644
--- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -1,4 +1,4 @@
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
require 'active_support/core_ext/time/conversions'
require 'active_support/core_ext/date_time/calculations'
require 'active_support/values/time_zone'
@@ -9,12 +9,12 @@ class DateTime
remove_method :to_time if instance_methods.include?(:to_time)
# 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"
@@ -50,7 +50,7 @@ class DateTime
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)
@@ -66,7 +66,7 @@ class DateTime
# Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class
# If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time
def to_time
- self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec) : self
+ self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * (RUBY_VERSION < '1.9' ? 86400000000 : 1000000)) : self
end
# To be able to keep Times, Dates and DateTimes interchangeable on conversions
@@ -83,8 +83,8 @@ class DateTime
def xmlschema
strftime("%Y-%m-%dT%H:%M:%S%Z")
end unless instance_methods(false).include?(:xmlschema)
-
- # Converts self to a floating-point number of seconds since the Unix epoch
+
+ # Converts self to a floating-point number of seconds since the Unix epoch
def to_f
seconds_since_unix_epoch.to_f
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
index a7411d54ae..82a4f7ac5a 100644
--- a/activesupport/lib/active_support/core_ext/date_time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/zones.rb
@@ -9,7 +9,7 @@ class DateTime
# 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,
+ # 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
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index f76ed401cd..6d7f771b5d 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -9,7 +9,7 @@ module Enumerable
#
# Example:
#
- # latest_transcripts.group_by(&:day).each do |day, transcripts|
+ # latest_transcripts.group_by(&:day).each do |day, transcripts|
# p "#{day} -> #{transcripts.map(&:class).join(', ')}"
# end
# "2006-03-01 -> Transcript"
@@ -88,21 +88,18 @@ module Enumerable
# => { "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
- inject({}) do |accum, elem|
- accum[yield(elem)] = elem
- accum
- end
+ Hash[map { |elem| [yield(elem), elem] }]
end
-
+
# Returns true if the collection has more than 1 element. Functionally equivalent to collection.size > 1.
- # Works with a block too ala any?, so people.many? { |p| p.age > 26 } # => returns true if more than 1 person is over 26.
+ # Can be called with a block too, much like any?, so people.many? { |p| p.age > 26 } returns true if more than 1 person is over 26.
def many?(&block)
size = block_given? ? select(&block).size : self.size
size > 1
end
-
+
# The negative of the Enumerable#include?. Returns true if the collection does not include the object.
def exclude?(object)
!include?(object)
diff --git a/activesupport/lib/active_support/core_ext/float/rounding.rb b/activesupport/lib/active_support/core_ext/float/rounding.rb
index 9bdf5bba7b..0d4fb87665 100644
--- a/activesupport/lib/active_support/core_ext/float/rounding.rb
+++ b/activesupport/lib/active_support/core_ext/float/rounding.rb
@@ -16,4 +16,4 @@ class Float
precisionless_round
end
end
-end
+end if RUBY_VERSION < '1.9'
diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb
index 501483498d..fd1cda991e 100644
--- a/activesupport/lib/active_support/core_ext/hash.rb
+++ b/activesupport/lib/active_support/core_ext/hash.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/hash/conversions'
require 'active_support/core_ext/hash/deep_merge'
+require 'active_support/core_ext/hash/deep_dup'
require 'active_support/core_ext/hash/diff'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/indifferent_access'
diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb
index 2763af6121..3005fef44c 100644
--- a/activesupport/lib/active_support/core_ext/hash/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb
@@ -7,7 +7,7 @@ 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"?>
@@ -15,22 +15,34 @@ class 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. Its
- # return value becomes a new node.
- #
+ # with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
+ # callable can add nodes by using <tt>options[:builder]</tt>.
+ #
+ # "foo".to_xml(lambda { |options, key| options[:builder].b(key) })
+ # # => "<b>foo</b>"
+ #
# * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
- #
+ #
+ # class Foo
+ # def to_xml(options)
+ # options[:builder].bar "fooing!"
+ # end
+ # end
+ #
+ # {:foo => Foo.new}.to_xml(:skip_instruct => true)
+ # # => "<hash><bar>fooing!</bar></hash>"
+ #
# * Otherwise, a node with +key+ as tag is created with a string representation of
# +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
# Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is
@@ -48,9 +60,9 @@ class Hash
# "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.
@@ -108,17 +120,14 @@ class Hash
# blank or nil parsed values are represented by nil
elsif value.blank? || value['nil'] == 'true'
nil
- # If the type is the only element which makes it then
+ # 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)
elsif value['type'] && value.size == 1 && !value['type'].is_a?(::Hash)
nil
else
- xml_value = value.inject({}) do |h,(k,v)|
- h[k] = typecast_xml_value(v)
- h
- end
-
+ xml_value = Hash[value.map { |k,v| [k, typecast_xml_value(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
@@ -136,10 +145,7 @@ class Hash
def unrename_keys(params)
case params.class.to_s
when "Hash"
- params.inject({}) do |h,(k,v)|
- h[k.to_s.tr("-", "_")] = unrename_keys(v)
- h
- end
+ Hash[params.map { |k,v| [k.to_s.tr("-", "_"), unrename_keys(v)] } ]
when "Array"
params.map { |v| unrename_keys(v) }
else
diff --git a/activesupport/lib/active_support/core_ext/hash/deep_dup.rb b/activesupport/lib/active_support/core_ext/hash/deep_dup.rb
new file mode 100644
index 0000000000..447142605c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/deep_dup.rb
@@ -0,0 +1,11 @@
+class Hash
+ # Returns a deep copy of hash.
+ def deep_dup
+ duplicate = self.dup
+ duplicate.each_pair do |k,v|
+ tv = duplicate[k]
+ duplicate[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_dup : v
+ end
+ duplicate
+ 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
index 0420e206af..aad4b61e16 100644
--- a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
+++ b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
@@ -7,8 +7,6 @@ class Hash
# {:a => 1}.with_indifferent_access["a"] # => 1
#
def with_indifferent_access
- hash = ActiveSupport::HashWithIndifferentAccess.new(self)
- hash.default = self.default
- hash
+ ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
end
end
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
index 045a6944fa..d8748b1138 100644
--- a/activesupport/lib/active_support/core_ext/hash/keys.rb
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -35,11 +35,13 @@ class Hash
# as keys, this will fail.
#
# ==== Examples
- # { :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key(s): years"
- # { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key(s): name, age"
+ # { :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)
- unknown_keys = keys - [valid_keys].flatten
- raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
+ valid_keys.flatten!
+ each_key do |k|
+ raise(ArgumentError, "Unknown key: #{k}") unless valid_keys.include?(k)
+ end
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
index d7ebd5feef..01863a162b 100644
--- a/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
+++ b/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
@@ -1,27 +1,22 @@
class Hash
- # Allows for reverse merging two hashes where the keys in the calling hash take precedence over those
- # in the <tt>other_hash</tt>. This is particularly useful for initializing an option hash with default values:
+ # Merges the caller into +other_hash+. For example,
#
- # def setup(options = {})
- # options.reverse_merge! :size => 25, :velocity => 10
- # end
+ # options = options.reverse_merge(:size => 25, :velocity => 10)
#
- # Using <tt>merge</tt>, the above example would look as follows:
+ # is equivalent to
#
- # def setup(options = {})
- # { :size => 25, :velocity => 10 }.merge(options)
- # end
+ # options = {:size => 25, :velocity => 10}.merge(options)
#
- # The default <tt>:size</tt> and <tt>:velocity</tt> are only set if the +options+ hash passed in doesn't already
- # have the respective key.
+ # This is particularly useful for initializing an options hash
+ # with default values.
def reverse_merge(other_hash)
other_hash.merge(self)
end
- # Performs the opposite of <tt>merge</tt>, with the keys and values from the first hash taking precedence over the second.
- # Modifies the receiver in place.
+ # Destructive +reverse_merge+.
def reverse_merge!(other_hash)
- merge!( other_hash ){|k,o,n| o }
+ # right wins if there is no left
+ merge!( other_hash ){|key,left,right| left }
end
alias_method :reverse_update, :reverse_merge!
diff --git a/activesupport/lib/active_support/core_ext/integer/time.rb b/activesupport/lib/active_support/core_ext/integer/time.rb
index a0ccf0e971..c677400396 100644
--- a/activesupport/lib/active_support/core_ext/integer/time.rb
+++ b/activesupport/lib/active_support/core_ext/integer/time.rb
@@ -1,7 +1,7 @@
class Integer
# 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.
+ # 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.now.advance(:months => 1)
@@ -12,7 +12,7 @@ class Integer
#
# # 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:
diff --git a/activesupport/lib/active_support/core_ext/kernel/reporting.rb b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
index 7c455f66d5..37a827123a 100644
--- a/activesupport/lib/active_support/core_ext/kernel/reporting.rb
+++ b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
@@ -38,7 +38,7 @@ module Kernel
# puts 'But this will'
def silence_stream(stream)
old_stream = stream.dup
- stream.reopen(Config::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
+ stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
stream.sync = true
yield
ensure
@@ -59,4 +59,23 @@ module Kernel
raise unless exception_classes.any? { |cls| e.kind_of?(cls) }
end
end
+
+ # Captures the given stream and returns it:
+ #
+ # stream = capture(:stdout){ puts "Cool" }
+ # stream # => "Cool\n"
+ #
+ def capture(stream)
+ begin
+ stream = stream.to_s
+ eval "$#{stream} = StringIO.new"
+ yield
+ result = eval("$#{stream}").string
+ ensure
+ eval("$#{stream} = #{stream.upcase}")
+ end
+
+ result
+ end
+ alias :silence :capture
end
diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb
index a1c351bfd9..e63a0a9ed9 100644
--- a/activesupport/lib/active_support/core_ext/logger.rb
+++ b/activesupport/lib/active_support/core_ext/logger.rb
@@ -4,18 +4,17 @@ require 'active_support/core_ext/class/attribute_accessors'
class Logger #:nodoc:
def self.define_around_helper(level)
module_eval <<-end_eval, __FILE__, __LINE__ + 1
- def around_#{level}(before_message, after_message, &block) # def around_debug(before_message, after_message, &block)
- self.#{level}(before_message) # self.debug(before_message)
- return_value = block.call(self) # return_value = block.call(self)
- self.#{level}(after_message) # self.debug(after_message)
- return return_value # return return_value
- end # end
+ 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.
@@ -65,11 +64,11 @@ class Logger
formatter.datetime_format if formatter.respond_to?(:datetime_format)
end
- alias :old_formatter :formatter if method_defined?(:formatter)
- # Get the current formatter. The default formatter is a SimpleFormatter which only
- # displays the log message
- def formatter
- @formatter ||= SimpleFormatter.new
+ 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.
@@ -79,30 +78,4 @@ class Logger
"#{String === msg ? msg : msg.inspect}\n"
end
end
-
- private
- alias old_format_message format_message
-
- # Ruby 1.8.3 transposed the msg and progname arguments to format_message.
- # We can't test RUBY_VERSION because some distributions don't keep Ruby
- # and its standard library in sync, leading to installations of Ruby 1.8.2
- # with Logger from 1.8.3 and vice versa.
- if method_defined?(:formatter=)
- def format_message(severity, timestamp, progname, msg)
- formatter.call(severity, timestamp, progname, msg)
- end
- else
- def format_message(severity, timestamp, msg, progname)
- formatter.call(severity, timestamp, progname, msg)
- end
-
- attr_writer :formatter
- public :formatter=
-
- alias old_format_datetime format_datetime
- def format_datetime(datetime) datetime end
-
- alias old_msg2str msg2str
- def msg2str(msg) msg end
- end
end
diff --git a/activesupport/lib/active_support/core_ext/module/anonymous.rb b/activesupport/lib/active_support/core_ext/module/anonymous.rb
index df25a09ec9..3982c9c586 100644
--- a/activesupport/lib/active_support/core_ext/module/anonymous.rb
+++ b/activesupport/lib/active_support/core_ext/module/anonymous.rb
@@ -19,6 +19,6 @@ class Module
def anonymous?
# Uses blank? because the name of an anonymous class is an empty
# string in 1.8, and nil in 1.9.
- name.blank?
+ name.blank?
end
end
diff --git a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb
index 28ac89dab9..e3259a0a84 100644
--- a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb
+++ b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb
@@ -2,30 +2,29 @@ class Module
# Declare an attribute accessor with an initial default return value.
#
# To give attribute <tt>:age</tt> the initial value <tt>25</tt>:
- #
+ #
# class Person
# attr_accessor_with_default :age, 25
# end
#
- # some_person.age
- # => 25
- # some_person.age = 26
- # some_person.age
- # => 26
+ # person = Person.new
+ # person.age # => 25
+ #
+ # person.age = 26
+ # person.age # => 26
#
# To give attribute <tt>:element_name</tt> a dynamic default value, evaluated
# in scope of self:
#
- # attr_accessor_with_default(:element_name) { name.underscore }
+ # attr_accessor_with_default(:element_name) { name.underscore }
#
- def attr_accessor_with_default(sym, default = nil, &block)
- raise 'Default value or block required' unless !default.nil? || block
- define_method(sym, block_given? ? block : Proc.new { default })
+ def attr_accessor_with_default(sym, default = Proc.new)
+ define_method(sym, block_given? ? default : Proc.new { default })
module_eval(<<-EVAL, __FILE__, __LINE__ + 1)
- def #{sym}=(value) # def age=(value)
- class << self; attr_reader :#{sym} end # class << self; attr_reader :age end
- @#{sym} = value # @age = value
- end # end
+ def #{sym}=(value) # def age=(value)
+ class << self; attr_accessor :#{sym} end # class << self; attr_accessor :age end
+ @#{sym} = value # @age = value
+ end # end
EVAL
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
index 28bc30ae26..00db75bfec 100644
--- a/activesupport/lib/active_support/core_ext/module/attr_internal.rb
+++ b/activesupport/lib/active_support/core_ext/module/attr_internal.rb
@@ -1,16 +1,12 @@
class Module
# Declares an attribute reader backed by an internally-named instance variable.
def attr_internal_reader(*attrs)
- attrs.each do |attr|
- module_eval "def #{attr}() #{attr_internal_ivar_name(attr)} end", __FILE__, __LINE__
- end
+ 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 do |attr|
- module_eval "def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end", __FILE__, __LINE__
- end
+ attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
end
# Declares an attribute reader and writer backed by an internally-named instance
@@ -29,4 +25,15 @@ class Module
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
index 2d88cb57e5..871f5cef3b 100644
--- a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
+++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
@@ -11,7 +11,7 @@ class Module
@@#{sym}
end
EOS
-
+
unless options[:instance_reader] == false
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index 40a1866428..3a7652f5bf 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -113,7 +113,7 @@ class Module
raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
end
- prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_"
+ prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_" || ''
file, line = caller.first.split(':', 2)
line = line.to_i
diff --git a/activesupport/lib/active_support/core_ext/module/deprecation.rb b/activesupport/lib/active_support/core_ext/module/deprecation.rb
index 5a5b4e3f80..9c169a2598 100644
--- a/activesupport/lib/active_support/core_ext/module/deprecation.rb
+++ b/activesupport/lib/active_support/core_ext/module/deprecation.rb
@@ -1,3 +1,5 @@
+require 'active_support/deprecation'
+
class Module
# Declare that a method has been deprecated.
# deprecate :foo
diff --git a/activesupport/lib/active_support/core_ext/module/remove_method.rb b/activesupport/lib/active_support/core_ext/module/remove_method.rb
index b8c01aca0e..07d7c9b018 100644
--- a/activesupport/lib/active_support/core_ext/module/remove_method.rb
+++ b/activesupport/lib/active_support/core_ext/module/remove_method.rb
@@ -3,7 +3,7 @@ class Module
remove_method(method)
rescue NameError
end
-
+
def redefine_method(method, &block)
remove_possible_method(method)
define_method(method, &block)
diff --git a/activesupport/lib/active_support/core_ext/module/synchronization.rb b/activesupport/lib/active_support/core_ext/module/synchronization.rb
index de76a069d6..ed16c2f71b 100644
--- a/activesupport/lib/active_support/core_ext/module/synchronization.rb
+++ b/activesupport/lib/active_support/core_ext/module/synchronization.rb
@@ -1,11 +1,12 @@
+require 'thread'
require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/array/extract_options'
class Module
# Synchronize access around a method, delegating synchronization to a
- # particular mutex. A mutex (either a Mutex, or any object that responds to
+ # particular mutex. A mutex (either a Mutex, or any object that responds to
# #synchronize and yields to a block) must be provided as a final :with option.
- # The :with option should be a symbol or string, and can represent a method,
+ # The :with option should be a symbol or string, and can represent a method,
# constant, or instance or class variable.
# Example:
# class SharedCache
diff --git a/activesupport/lib/active_support/core_ext/numeric/time.rb b/activesupport/lib/active_support/core_ext/numeric/time.rb
index d1062805c5..e73915ffcf 100644
--- a/activesupport/lib/active_support/core_ext/numeric/time.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/time.rb
@@ -3,7 +3,7 @@ require 'active_support/duration'
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.
+ # 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.now.advance(:months => 1)
@@ -14,7 +14,7 @@ class Numeric
#
# # 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:
@@ -25,8 +25,8 @@ class Numeric
# # equivalent to 365.25.days.to_f.from_now
# 1.year.to_f.from_now
#
- # In such cases, Ruby's core
- # Date[http://stdlib.rubyonrails.org/libdoc/date/rdoc/index.html] and
+ # In such cases, Ruby's core
+ # Date[http://stdlib.rubyonrails.org/libdoc/date/rdoc/index.html] and
# Time[http://stdlib.rubyonrails.org/libdoc/time/rdoc/index.html] should be used for precision
# date and time arithmetic
def seconds
@@ -37,13 +37,13 @@ class Numeric
def minutes
ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
end
- alias :minute :minutes
-
+ 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
@@ -53,14 +53,14 @@ class Numeric
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.now)
+ def ago(time = ::Time.current)
time - self
end
@@ -68,7 +68,7 @@ class Numeric
alias :until :ago
# Reads best with argument: 10.minutes.since(time)
- def since(time = ::Time.now)
+ def since(time = ::Time.current)
time + self
end
diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb
index d671da6711..790a26f5c1 100644
--- a/activesupport/lib/active_support/core_ext/object.rb
+++ b/activesupport/lib/active_support/core_ext/object.rb
@@ -2,7 +2,6 @@ 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/try'
-require 'active_support/core_ext/object/returning'
require 'active_support/core_ext/object/conversions'
require 'active_support/core_ext/object/instance_variables'
diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb
index eb99bb1a36..d0c1ea8326 100644
--- a/activesupport/lib/active_support/core_ext/object/blank.rb
+++ b/activesupport/lib/active_support/core_ext/object/blank.rb
@@ -13,11 +13,11 @@ class Object
respond_to?(:empty?) ? empty? : !self
end
- # An object is present if it's not blank.
+ # An object is present if it's not <tt>blank?</tt>.
def present?
!blank?
end
-
+
# Returns object if it's #present? otherwise returns nil.
# object.presence is equivalent to object.present? ? object : nil.
#
diff --git a/activesupport/lib/active_support/core_ext/object/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
index 866317b17a..eda9694614 100644
--- a/activesupport/lib/active_support/core_ext/object/instance_variables.rb
+++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
@@ -7,13 +7,10 @@ class Object
# @x, @y = x, y
# end
# end
- #
+ #
# C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
def instance_values #:nodoc:
- instance_variables.inject({}) do |values, name|
- values[name.to_s[1..-1]] = instance_variable_get(name)
- values
- end
+ Hash[instance_variables.map { |name| [name.to_s[1..-1], instance_variable_get(name)] }]
end
# Returns an array of instance variable names including "@". They are strings
@@ -24,7 +21,7 @@ class Object
# @x, @y = x, y
# end
# end
- #
+ #
# C.new(0, 1).instance_variable_names # => ["@y", "@x"]
if RUBY_VERSION >= '1.9'
def instance_variable_names
@@ -33,35 +30,4 @@ class Object
else
alias_method :instance_variable_names, :instance_variables
end
-
- # Copies the instance variables of +object+ into +self+.
- #
- # Instance variable names in the +exclude+ array are ignored. If +object+
- # responds to <tt>protected_instance_variables</tt> the ones returned are
- # also ignored. For example, Rails controllers implement that method.
- #
- # In both cases strings and symbols are understood, and they have to include
- # the at sign.
- #
- # class C
- # def initialize(x, y, z)
- # @x, @y, @z = x, y, z
- # end
- #
- # def protected_instance_variables
- # %w(@z)
- # end
- # end
- #
- # a = C.new(0, 1, 2)
- # b = C.new(3, 4, 5)
- #
- # a.copy_instance_variables_from(b, [:@y])
- # # a is now: @x = 3, @y = 1, @z = 2
- def copy_instance_variables_from(object, exclude = []) #:nodoc:
- exclude += object.protected_instance_variables if object.respond_to? :protected_instance_variables
-
- vars = object.instance_variables.map(&:to_s) - exclude.map(&:to_s)
- vars.each { |name| instance_variable_set(name, object.instance_variable_get(name)) }
- end
end
diff --git a/activesupport/lib/active_support/core_ext/object/returning.rb b/activesupport/lib/active_support/core_ext/object/returning.rb
deleted file mode 100644
index 07250b2a27..0000000000
--- a/activesupport/lib/active_support/core_ext/object/returning.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-class Object
- # Returns +value+ after yielding +value+ to the block. This simplifies the
- # process of constructing an object, performing work on the object, and then
- # returning the object from a method. It is a Ruby-ized realization of the K
- # combinator, courtesy of Mikael Brockman.
- #
- # ==== Examples
- #
- # # Without returning
- # def foo
- # values = []
- # values << "bar"
- # values << "baz"
- # return values
- # end
- #
- # foo # => ['bar', 'baz']
- #
- # # returning with a local variable
- # def foo
- # returning values = [] do
- # values << 'bar'
- # values << 'baz'
- # end
- # end
- #
- # foo # => ['bar', 'baz']
- #
- # # returning with a block argument
- # def foo
- # returning [] do |values|
- # values << 'bar'
- # values << 'baz'
- # end
- # end
- #
- # foo # => ['bar', 'baz']
- def returning(value)
- ActiveSupport::Deprecation.warn('Object#returning has been deprecated in favor of Object#tap.', caller)
- yield(value)
- value
- end
-end \ No newline at end of file
diff --git a/activesupport/lib/active_support/core_ext/object/to_param.rb b/activesupport/lib/active_support/core_ext/object/to_param.rb
index f2e7c2351e..e5f81078ee 100644
--- a/activesupport/lib/active_support/core_ext/object/to_param.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_param.rb
@@ -1,5 +1,3 @@
-
-
class Object
# Alias of <tt>to_s</tt>.
def to_param
@@ -34,16 +32,24 @@ class Array
end
class Hash
- # Converts a hash into a string suitable for use as a URL query string. An optional <tt>namespace</tt> can be
- # passed to enclose the param names (see example below).
+ # 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"
#
- # ==== Examples
- # { :name => 'David', :nationality => 'Danish' }.to_param # => "name=David&nationality=Danish"
+ # The string pairs "key=value" that conform the query string
+ # are sorted lexicographically in ascending order.
#
- # { :name => 'David', :nationality => 'Danish' }.to_param('user') # => "user[name]=David&user[nationality]=Danish"
+ # 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 * '&'
+ 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
index c9981895b4..3f1540f685 100644
--- a/activesupport/lib/active_support/core_ext/object/to_query.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_query.rb
@@ -7,7 +7,7 @@ class Object
# Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.
def to_query(key)
require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
- "#{CGI.escape(key.to_s).gsub(/%(5B|5D)/n) { [$1].pack('H*') }}=#{CGI.escape(to_param.to_s)}"
+ "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}"
end
end
@@ -15,7 +15,7 @@ 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[]=Rails&hobbies[]=coding"
+ # ['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 '&'
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index a1c63a0e54..04619124a1 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -5,6 +5,8 @@ class Object
# *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
# and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
#
+ # If try is called without a method to call, it will yield any given block with the object.
+ #
# ==== Examples
#
# Without try
@@ -18,15 +20,18 @@ class Object
# +try+ also accepts arguments and/or a block, for the method it is trying
# Person.try(:find, 1)
# @people.try(:collect) {|p| p.name}
+ #
+ # Without a method argument try will yield to the block unless the receiver is nil.
+ # @person.try { |p| "#{p.first_name} #{p.last_name}" }
#--
- # This method definition below is for rdoc purposes only. The alias_method call
- # below overrides it as an optimization since +try+ behaves like +Object#send+,
- # unless called on +NilClass+.
- def try(method, *args, &block)
- send(method, *args, &block)
+ # +try+ behaves like +Object#send+, unless called on +NilClass+.
+ def try(*a, &b)
+ if a.empty? && block_given?
+ yield self
+ else
+ __send__(*a, &b)
+ end
end
- remove_method :try
- alias_method :try, :__send__
end
class NilClass #:nodoc:
diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb
index 3209cf7f11..c23afabfdb 100644
--- a/activesupport/lib/active_support/core_ext/object/with_options.rb
+++ b/activesupport/lib/active_support/core_ext/object/with_options.rb
@@ -7,13 +7,27 @@ class Object
# provided. Each method called on the block variable must take an options
# hash as its final argument.
#
- # with_options :order => 'created_at', :class_name => 'Comment' do |post|
- # post.has_many :comments, :conditions => ['approved = ?', true], :dependent => :delete_all
- # post.has_many :unapproved_comments, :conditions => ['approved = ?', false]
- # post.has_many :all_comments
+ # Without with_options, this code contains duplication:
+ #
+ # class Account < ActiveRecord::Base
+ # has_many :customers, :dependent => :destroy
+ # has_many :products, :dependent => :destroy
+ # has_many :invoices, :dependent => :destroy
+ # has_many :expenses, :dependent => :destroy
+ # end
+ #
+ # Using with_options, we can remove the duplication:
+ #
+ # class Account < ActiveRecord::Base
+ # with_options :dependent => :destroy do |assoc|
+ # assoc.has_many :customers
+ # assoc.has_many :products
+ # assoc.has_many :invoices
+ # assoc.has_many :expenses
+ # end
# end
#
- # Can also be used with an explicit receiver:
+ # It can also be used with an explicit receiver:
#
# map.with_options :controller => "people" do |people|
# people.connect "/people", :action => "index"
diff --git a/activesupport/lib/active_support/core_ext/range.rb b/activesupport/lib/active_support/core_ext/range.rb
index c0736f3a44..2428a02242 100644
--- a/activesupport/lib/active_support/core_ext/range.rb
+++ b/activesupport/lib/active_support/core_ext/range.rb
@@ -2,3 +2,4 @@ require 'active_support/core_ext/range/blockless_step'
require 'active_support/core_ext/range/conversions'
require 'active_support/core_ext/range/include_range'
require 'active_support/core_ext/range/overlaps'
+require 'active_support/core_ext/range/cover'
diff --git a/activesupport/lib/active_support/core_ext/range/conversions.rb b/activesupport/lib/active_support/core_ext/range/conversions.rb
index 11a7ff66de..544e63132d 100644
--- a/activesupport/lib/active_support/core_ext/range/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/range/conversions.rb
@@ -6,7 +6,7 @@ class Range
# Gives a human readable format of the range.
#
# ==== Example
- #
+ #
# [1..100].to_formatted_s # => "1..100"
def to_formatted_s(format = :default)
if formatter = RANGE_FORMATS[format]
diff --git a/activesupport/lib/active_support/core_ext/range/cover.rb b/activesupport/lib/active_support/core_ext/range/cover.rb
new file mode 100644
index 0000000000..3a182cddd2
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/cover.rb
@@ -0,0 +1,3 @@
+class Range
+ alias_method(:cover?, :include?) unless instance_methods.include?(:cover?)
+end
diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb
index d8d1f9436e..8fb8c31ade 100644
--- a/activesupport/lib/active_support/core_ext/string.rb
+++ b/activesupport/lib/active_support/core_ext/string.rb
@@ -9,4 +9,5 @@ require 'active_support/core_ext/string/behavior'
require 'active_support/core_ext/string/interpolation'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/string/exclude'
-require 'active_support/core_ext/string/encoding' \ No newline at end of file
+require 'active_support/core_ext/string/encoding'
+require 'active_support/core_ext/string/strip'
diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb
index 64bc8f6cea..c0d5cdf2d5 100644
--- a/activesupport/lib/active_support/core_ext/string/access.rb
+++ b/activesupport/lib/active_support/core_ext/string/access.rb
@@ -4,27 +4,27 @@ class String
unless '1.9'.respond_to?(:force_encoding)
# Returns the character at the +position+ treating the string as an array (where 0 is the first character).
#
- # Examples:
+ # Examples:
# "hello".at(0) # => "h"
# "hello".at(4) # => "o"
# "hello".at(10) # => ERROR if < 1.9, nil in 1.9
def at(position)
mb_chars[position, 1].to_s
end
-
+
# Returns the remaining of the string from the +position+ treating the string as an array (where 0 is the first character).
#
- # Examples:
+ # Examples:
# "hello".from(0) # => "hello"
# "hello".from(2) # => "llo"
# "hello".from(10) # => "" if < 1.9, nil in 1.9
def from(position)
mb_chars[position..-1].to_s
end
-
+
# Returns the beginning of the string up to the +position+ treating the string as an array (where 0 is the first character).
#
- # Examples:
+ # Examples:
# "hello".to(0) # => "h"
# "hello".to(2) # => "hel"
# "hello".to(10) # => "hello"
@@ -34,7 +34,7 @@ class String
# Returns the first character of the string or the first +limit+ characters.
#
- # Examples:
+ # Examples:
# "hello".first # => "h"
# "hello".first(2) # => "he"
# "hello".first(10) # => "hello"
@@ -50,7 +50,7 @@ class String
# Returns the last character of the string or the last +limit+ characters.
#
- # Examples:
+ # Examples:
# "hello".last # => "o"
# "hello".last(2) # => "lo"
# "hello".last(10) # => "hello"
diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb
index e15a1df9c9..d478ee0ef6 100644
--- a/activesupport/lib/active_support/core_ext/string/filters.rb
+++ b/activesupport/lib/active_support/core_ext/string/filters.rb
@@ -25,13 +25,13 @@ class String
# "Once upon a time in a world far far away".truncate(27)
# # => "Once upon a time in a wo..."
#
- # The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
- # for a total length not exceeding <tt>:length</tt>:
+ # Pass a <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..."
#
- # Pass a <tt>:separator</tt> to truncate +text+ at a natural break:
+ # 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)"
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb
index 32913a06ad..2f0676f567 100644
--- a/activesupport/lib/active_support/core_ext/string/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -1,7 +1,9 @@
require 'active_support/inflector/methods'
require 'active_support/inflector/inflections'
+require 'active_support/inflector/transliterate'
+
# String inflections define new methods on the String class to transform names for different purposes.
-# For instance, you can figure out the name of a database from the name of a class.
+# For instance, you can figure out the name of a table from the name of a class.
#
# "ScaleScore".tableize # => "scale_scores"
#
@@ -72,7 +74,7 @@ class String
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.
#
# "ActiveRecord".underscore # => "active_record"
@@ -97,7 +99,7 @@ class String
end
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
- #
+ #
# ==== Examples
#
# class Person
@@ -105,10 +107,10 @@ class String
# "#{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 = '-')
@@ -138,11 +140,11 @@ class String
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" # => "Employee salary"
+ # "employee_salary" # => "Employee salary"
# "author_id" # => "Author"
def humanize
ActiveSupport::Inflector.humanize(self)
diff --git a/activesupport/lib/active_support/core_ext/string/multibyte.rb b/activesupport/lib/active_support/core_ext/string/multibyte.rb
index 0b974f5e0a..41de4d6435 100644
--- a/activesupport/lib/active_support/core_ext/string/multibyte.rb
+++ b/activesupport/lib/active_support/core_ext/string/multibyte.rb
@@ -9,7 +9,7 @@ class String
#
# In Ruby 1.8 and older 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 encapsuled string.
+ # 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"
diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb
index b53929c2a3..addd4dab95 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -24,6 +24,7 @@ class ERB
end
end
+ # Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
remove_method(:h)
alias h html_escape
@@ -32,15 +33,23 @@ class ERB
singleton_class.send(:remove_method, :html_escape)
module_function :html_escape
- # A utility method for escaping HTML entities in JSON strings.
- # This method is also aliased as <tt>j</tt>.
+ # 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}
+ #
+ # This method is also aliased as +j+, and available as a helper
+ # in Rails templates:
#
- # In your ERb templates, use this method to escape any HTML entities:
# <%=j @person.to_json %>
#
- # ==== Example:
- # puts json_escape("is a > 0 & a < 10?")
- # # => is a \u003E 0 \u0026 a \u003C 10?
def json_escape(s)
s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] }
end
@@ -92,7 +101,13 @@ module ActiveSupport #:nodoc:
self
end
+ def encode_with(coder)
+ coder.represent_scalar nil, to_str
+ end
+
def to_yaml(*args)
+ return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
+
to_str.to_yaml(*args)
end
end
diff --git a/activesupport/lib/active_support/core_ext/string/strip.rb b/activesupport/lib/active_support/core_ext/string/strip.rb
new file mode 100644
index 0000000000..086c610976
--- /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/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index 90b6cd3685..7e134db118 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -1,7 +1,4 @@
require 'active_support/duration'
-require 'active_support/core_ext/date/acts_like'
-require 'active_support/core_ext/date/calculations'
-require 'active_support/core_ext/date_time/conversions'
class Time
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
@@ -22,7 +19,7 @@ class Time
# 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
+ # 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)
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.
@@ -41,9 +38,9 @@ class Time
time_with_datetime_fallback(:local, *args)
end
- # Returns <tt>Time.zone.now</tt> when <tt>config.time_zone</tt> is set, otherwise just returns <tt>Time.now</tt>.
+ # Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
def current
- ::Time.zone_default ? ::Time.zone.now : ::Time.now
+ ::Time.zone ? ::Time.zone.now : ::Time.now
end
end
@@ -92,12 +89,12 @@ class Time
options[:weeks], partial_weeks = options[:weeks].divmod(1)
options[:days] = (options[:days] || 0) + 7 * partial_weeks
end
-
+
unless options[:days].nil?
options[:days], partial_days = options[:days].divmod(1)
options[:hours] = (options[: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[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600
@@ -117,6 +114,11 @@ class Time
end
alias :in :since
+ # Returns a new Time representing the time a number of specified weeks ago.
+ def weeks_ago(weeks)
+ advance(:weeks => -weeks)
+ end
+
# Returns a new Time representing the time a number of specified months ago
def months_ago(months)
advance(:months => -months)
@@ -172,6 +174,11 @@ class Time
end
alias :at_end_of_week :end_of_week
+ # Returns a new Time representing the start of the given day in the previous week (default is Monday).
+ def prev_week(day = :monday)
+ ago(1.week).beginning_of_week.since(DAYS_INTO_WEEK[day].day).change(:hour => 0)
+ end
+
# Returns a new Time representing the start of the given day in next week (default is Monday).
def next_week(day = :monday)
since(1.week).beginning_of_week.since(DAYS_INTO_WEEK[day].day).change(:hour => 0)
@@ -273,14 +280,8 @@ class Time
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
# can be chronologically compared with a Time
def compare_with_coercion(other)
- # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do <=> comparison
- other = other.comparable_time if other.respond_to?(:comparable_time)
- if other.acts_like?(:date)
- # other is a Date/DateTime, so coerce self #to_datetime and hand off to DateTime#<=>
- to_datetime.compare_without_coercion(other)
- else
- compare_without_coercion(other)
- end
+ # we're avoiding Time#to_datetime cause it's expensive
+ other.is_a?(Time) ? compare_without_coercion(other.to_time) : to_datetime <=> other
end
alias_method :compare_without_coercion, :<=>
alias_method :<=>, :compare_with_coercion
diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb
index 86103ebce2..d9d5e02778 100644
--- a/activesupport/lib/active_support/core_ext/time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -1,4 +1,4 @@
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
require 'active_support/core_ext/time/publicize_conversion_methods'
require 'active_support/values/time_zone'
@@ -19,8 +19,8 @@ class Time
#
# time = Time.now # => Thu Jan 18 06:10:17 CST 2007
#
- # time.to_formatted_s(:time) # => "06:10:17"
- # time.to_s(:time) # => "06:10:17"
+ # 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"
@@ -46,7 +46,7 @@ class Time
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"
@@ -55,31 +55,9 @@ class Time
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
end
- # Converts a Time object to a Date, dropping hour, minute, and second precision.
- #
- # my_time = Time.now # => Mon Nov 12 22:59:51 -0500 2007
- # my_time.to_date # => Mon, 12 Nov 2007
- #
- # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
- # your_time.to_date # => Tue, 13 Jan 2009
- def to_date
- ::Date.new(year, month, day)
- end unless method_defined?(:to_date)
-
# A method to keep Time, Date and DateTime instances interchangeable on conversions.
# In this case, it simply returns +self+.
def to_time
self
end unless method_defined?(:to_time)
-
- # Converts a Time instance to a Ruby DateTime instance, preserving UTC offset.
- #
- # my_time = Time.now # => Mon Nov 12 23:04:21 -0500 2007
- # my_time.to_datetime # => Mon, 12 Nov 2007 23:04:21 -0500
- #
- # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
- # your_time.to_datetime # => Tue, 13 Jan 2009 13:13:03 -0500
- def to_datetime
- ::DateTime.civil(year, month, day, hour, min, sec, Rational(utc_offset, 86400))
- end unless method_defined?(:to_datetime)
end
diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb
index 6b9ee84d5c..ff90d7ca58 100644
--- a/activesupport/lib/active_support/core_ext/time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/time/zones.rb
@@ -4,13 +4,13 @@ class Time
class << self
attr_accessor :zone_default
- # Returns the TimeZone for the current request, if this has been set (via Time.zone=).
+ # 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.
+ # Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
#
# This method accepts any of the following:
#
@@ -19,14 +19,18 @@ class Time
# * A TZInfo::Timezone object.
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
#
- # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis -- <tt>current_user.time_zone</tt>
- # just needs to return a string identifying the user's preferred TimeZone:
+ # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
+ # <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
#
# class ApplicationController < ActionController::Base
- # before_filter :set_time_zone
+ # around_filter :set_time_zone
#
# def set_time_zone
- # Time.zone = current_user.time_zone
+ # old_time_zone = Time.zone
+ # Time.zone = current_user.time_zone if logged_in?
+ # yield
+ # ensure
+ # Time.zone = old_time_zone
# end
# end
def zone=(time_zone)
@@ -63,7 +67,7 @@ class Time
# 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,
+ # 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
diff --git a/activesupport/lib/active_support/core_ext/uri.rb b/activesupport/lib/active_support/core_ext/uri.rb
index b7fe0a6209..ee991e3439 100644
--- a/activesupport/lib/active_support/core_ext/uri.rb
+++ b/activesupport/lib/active_support/core_ext/uri.rb
@@ -20,3 +20,11 @@ if RUBY_VERSION >= '1.9'
end
end
end
+
+module URI
+ class << self
+ def parser
+ @parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 2b80bd214f..dc10f78104 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -5,6 +5,7 @@ require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/module/introspection'
require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/module/deprecation'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/name_error'
@@ -47,9 +48,6 @@ module ActiveSupport #:nodoc:
mattr_accessor :autoloaded_constants
self.autoloaded_constants = []
- mattr_accessor :references
- self.references = {}
-
# An array of constant names that need to be unloaded on every request. Used
# to allow arbitrary constants to be marked for unloading.
mattr_accessor :explicitly_unloadable_constants
@@ -63,58 +61,78 @@ module ActiveSupport #:nodoc:
mattr_accessor :log_activity
self.log_activity = false
- class WatchStack < Array
+ # 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 < Hash
+ # @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
- @mutex = Mutex.new
+ @watching = []
+ super { |h,k| h[k] = [] }
end
- def self.locked(*methods)
- methods.each { |m| class_eval "def #{m}(*) lock { super } end", __FILE__, __LINE__ }
- end
+ # return a list of new constants found since the last call to watch_namespaces
+ def new_constants
+ constants = []
- locked :concat, :each, :delete_if, :<<
+ # 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 = self[namespace].last
- def new_constants_for(frames)
- constants = []
- frames.each do |mod_name, prior_constants|
- mod = Inflector.constantize(mod_name) if Dependencies.qualified_const_defined?(mod_name)
+ mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
next unless mod.is_a?(Module)
- new_constants = mod.local_constant_names - prior_constants
-
- # If we are checking for constants under, say, :Object, nested under something
- # else that is checking for constants also under :Object, make sure the
- # parent knows that we have found, and taken care of, the constant.
- #
- # In particular, this means that since Kernel.require discards the constants
- # it finds, parents will be notified that about those constants, and not
- # consider them "new". As a result, they will not be added to the
- # autoloaded_constants list.
- each do |key, value|
- value.concat(new_constants) if key == mod_name
+ # Get a list of the constants that were added
+ new_constants = mod.local_constant_names - 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.
+ self[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 << ([mod_name, suffix] - ["Object"]).join("::")
+ 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 add_modules(modules)
- list = modules.map do |desc|
- name = Dependencies.to_constant_name(desc)
- consts = Dependencies.qualified_const_defined?(name) ?
- Inflector.constantize(name).local_constant_names : []
- [name, consts]
+ 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_constant_names : []
+
+ watching << module_name
+ self[module_name] << original_constants
end
- concat(list)
- list
+ @watching << watching
end
- def lock
- @mutex.synchronize { yield self }
+ def pop_modules(modules)
+ modules.each { |mod| self[mod].pop }
end
end
@@ -146,7 +164,7 @@ module ActiveSupport #:nodoc:
def const_missing(const_name, nesting = nil)
klass_name = name.presence || "Object"
- if !nesting
+ unless nesting
# We'll assume that the nesting of Foo::Bar is ["Foo::Bar", "Foo"]
# even though it might not be, such as in the case of
# class Foo::Bar; Baz; end
@@ -311,7 +329,7 @@ module ActiveSupport #:nodoc:
if load?
log "loading #{file_name}"
- # Enable warnings iff this file has not been loaded before and
+ # 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?
@@ -491,7 +509,12 @@ module ActiveSupport #:nodoc:
end
# Remove the constants that have been autoloaded, and those that have been
- # marked for unloading.
+ # 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
@@ -499,31 +522,76 @@ module ActiveSupport #:nodoc:
explicitly_unloadable_constants.each { |const| remove_constant const }
end
- class Reference
- @@constants = Hash.new { |h, k| h[k] = Inflector.constantize(k) }
+ class ClassCache
+ def initialize
+ @store = Hash.new { |h, k| h[k] = Inflector.constantize(k) }
+ end
- attr_reader :name
+ def empty?
+ @store.empty?
+ end
- def initialize(name)
- @name = name.to_s
- @@constants[@name] = name if name.respond_to?(:name)
+ def key?(key)
+ @store.key?(key)
end
- def get
- @@constants[@name]
+ def []=(key, value)
+ return unless key.respond_to?(:name)
+
+ raise(ArgumentError, 'anonymous classes cannot be cached') if key.name.blank?
+
+ @store[key.name] = value
end
- def self.clear!
- @@constants.clear
+ def [](key)
+ key = key.name if key.respond_to?(:name)
+
+ @store[key]
+ end
+ alias :get :[]
+
+ class Getter # :nodoc:
+ def initialize(name)
+ @name = name
+ end
+
+ def get
+ Reference.get @name
+ end
+ deprecate :get
+ end
+
+ def new(name)
+ self[name] = name
+ Getter.new(name)
+ end
+ deprecate :new
+
+ def store(name)
+ self[name] = name
+ self
+ end
+
+ def clear!
+ @store.clear
end
end
+ Reference = ClassCache.new
+
def ref(name)
- references[name] ||= Reference.new(name)
+ Reference.new(name)
+ end
+ deprecate :ref
+
+ # Store a reference to a class +klass+.
+ def reference(klass)
+ Reference.store klass
end
+ # Get the reference for class named +name+.
def constantize(name)
- ref(name).get
+ Reference.get(name)
end
# Determine if the given constant has been automatically loaded.
@@ -563,14 +631,15 @@ module ActiveSupport #:nodoc:
# and will be removed immediately.
def new_constants_in(*descs)
log_call(*descs)
- watch_frames = constant_watch_stack.add_modules(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_for(watch_frames)
+ new_constants = constant_watch_stack.new_constants
log "New constants: #{new_constants * ', '}"
return new_constants unless aborting
@@ -580,9 +649,6 @@ module ActiveSupport #:nodoc:
end
return []
- ensure
- # Remove the stack frames that we added.
- watch_frames.each {|f| constant_watch_stack.delete(f) } if watch_frames.present?
end
class LoadingModule #:nodoc:
@@ -618,6 +684,8 @@ module ActiveSupport #:nodoc:
parent = Inflector.constantize(names * '::')
log "removing constant #{const}"
+ constantized = constantize(const)
+ constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
parent.instance_eval { remove_const to_remove }
return true
@@ -625,7 +693,7 @@ module ActiveSupport #:nodoc:
protected
def log_call(*args)
- if logger && log_activity
+ if log_activity?
arg_str = args.collect { |arg| arg.inspect } * ', '
/in `([a-z_\?\!]+)'/ =~ caller(1).first
selector = $1 || '<unknown>'
@@ -634,9 +702,11 @@ module ActiveSupport #:nodoc:
end
def log(msg)
- if logger && log_activity
- logger.debug "Dependencies: #{msg}"
- end
+ logger.debug "Dependencies: #{msg}" if log_activity?
+ end
+
+ def log_activity?
+ logger && log_activity
end
end
end
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index e1b8211d68..ce0775a690 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -4,12 +4,12 @@ require 'active_support/deprecation/method_wrappers'
require 'active_support/deprecation/proxy_wrappers'
module ActiveSupport
- module Deprecation #:nodoc:
+ module Deprecation
class << self
# The version the deprecated behavior will be removed, by default.
attr_accessor :deprecation_horizon
end
- self.deprecation_horizon = '3.0'
+ self.deprecation_horizon = '3.1'
# By default, warnings are not silenced and debugging is off.
self.silenced = false
diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb
index f54f65dcf0..da4af339fc 100644
--- a/activesupport/lib/active_support/deprecation/behaviors.rb
+++ b/activesupport/lib/active_support/deprecation/behaviors.rb
@@ -7,10 +7,17 @@ module ActiveSupport
# Whether to print a backtrace along with the warning.
attr_accessor :debug
+ # Returns the set behaviour or if one isn't set, defaults to +:stderr+
def behavior
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
end
+ # Sets the behaviour to the specified value. Can be a single value or an array.
+ #
+ # Examples
+ #
+ # ActiveSupport::Deprecation.behavior = :stderr
+ # ActiveSupport::Deprecation.behavior = [:stderr, :log]
def behavior=(behavior)
@behavior = Array.wrap(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
end
diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
index deb33ab702..a65fcafb44 100644
--- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
+++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
@@ -1,4 +1,4 @@
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
module ActiveSupport
module Deprecation
@@ -58,7 +58,7 @@ module ActiveSupport
end
end
- class DeprecatedConstantProxy < DeprecationProxy #:nodoc:
+ class DeprecatedConstantProxy < DeprecationProxy #:nodoc:all
def initialize(old_const, new_const)
@old_const = old_const
@new_const = new_const
diff --git a/activesupport/lib/active_support/deprecation/reporting.rb b/activesupport/lib/active_support/deprecation/reporting.rb
index 49d58cd3a1..ced08b8783 100644
--- a/activesupport/lib/active_support/deprecation/reporting.rb
+++ b/activesupport/lib/active_support/deprecation/reporting.rb
@@ -3,6 +3,12 @@ module ActiveSupport
class << self
attr_accessor :silenced
+ # Outputs a deprecation warning to the output configured by <tt>ActiveSupport::Deprecation.behavior</tt>
+ #
+ # Example:
+ #
+ # ActiveSupport::Deprecation.warn("something broke!")
+ # #=> "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
def warn(message = nil, callstack = caller)
return if silenced
deprecation_message(callstack, message).tap do |m|
@@ -46,10 +52,14 @@ module ActiveSupport
end
def extract_callstack(callstack)
- if md = callstack.first.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
- md.captures
- else
- callstack.first
+ 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
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 7da357730b..00c67a470d 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -3,7 +3,7 @@ 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
+ # Provides accurate date and time measurements using Date#advance and
# Time#advance, respectively. It mainly supports the methods on Numeric.
# Example:
#
@@ -80,6 +80,10 @@ module ActiveSupport
parts.to_sentence(:locale => :en)
end
+ def as_json(options = nil) #:nodoc:
+ to_i
+ end
+
protected
def sum(sign, time = ::Time.current) #:nodoc:
@@ -99,7 +103,7 @@ module ActiveSupport
private
def method_missing(method, *args, &block) #:nodoc:
- value.send(method, *args)
+ 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
index cd658fe173..a97e9d7daf 100644
--- a/activesupport/lib/active_support/file_update_checker.rb
+++ b/activesupport/lib/active_support/file_update_checker.rb
@@ -8,7 +8,7 @@ module ActiveSupport
# I18n.reload!
# end
#
- # ActionDispatch::Callbacks.to_prepare do
+ # ActionDispatch::Reloader.to_prepare do
# i18n_reloader.execute_if_updated
# end
#
diff --git a/activesupport/lib/active_support/file_watcher.rb b/activesupport/lib/active_support/file_watcher.rb
new file mode 100644
index 0000000000..81e63e76a7
--- /dev/null
+++ b/activesupport/lib/active_support/file_watcher.rb
@@ -0,0 +1,36 @@
+module ActiveSupport
+ class FileWatcher
+ class Backend
+ def initialize(path, watcher)
+ @watcher = watcher
+ @path = path
+ end
+
+ def trigger(files)
+ @watcher.trigger(files)
+ end
+ end
+
+ def initialize
+ @regex_matchers = {}
+ end
+
+ def watch(pattern, &block)
+ @regex_matchers[pattern] = block
+ end
+
+ def trigger(files)
+ trigger_files = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } }
+
+ files.each do |file, state|
+ @regex_matchers.each do |pattern, block|
+ trigger_files[block][state] << file if pattern === file
+ end
+ end
+
+ trigger_files.each do |block, payload|
+ block.call payload
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb
index 35a50e9a77..62f9c9aa2e 100644
--- a/activesupport/lib/active_support/gzip.rb
+++ b/activesupport/lib/active_support/gzip.rb
@@ -5,6 +5,10 @@ module ActiveSupport
# A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip.
module Gzip
class Stream < StringIO
+ def initialize(*)
+ super
+ set_encoding "BINARY" if "".encoding_aware?
+ end
def close; rewind; end
end
@@ -22,4 +26,4 @@ module ActiveSupport
output.string
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index eec5d4cf47..79a0de7940 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -1,8 +1,7 @@
-require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/hash/keys'
# This class has dubious semantics and we only have it so that
-# people can write params[:key] instead of params['key']
+# people can write <tt>params[:key]</tt> instead of <tt>params['key']</tt>
# and they get the same value for both keys.
module ActiveSupport
@@ -28,6 +27,12 @@ module ActiveSupport
end
end
+ def self.new_from_hash_copying_default(hash)
+ new(hash).tap do |new_hash|
+ new_hash.default = hash.default
+ end
+ end
+
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
alias_method :regular_update, :update unless method_defined?(:regular_update)
@@ -40,6 +45,8 @@ module ActiveSupport
regular_writer(convert_key(key), convert_value(value))
end
+ alias_method :store, :[]=
+
# Updates the instantized hash with values from the second:
#
# hash_1 = HashWithIndifferentAccess.new
@@ -90,7 +97,9 @@ module ActiveSupport
# Returns an exact copy of the hash.
def dup
- HashWithIndifferentAccess.new(self)
+ self.class.new(self).tap do |new_hash|
+ new_hash.default = default
+ end
end
# Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
@@ -100,9 +109,9 @@ module ActiveSupport
end
# Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
- # This overloaded definition prevents returning a regular hash, if reverse_merge is called on a HashWithDifferentAccess.
+ # This overloaded definition prevents returning a regular hash, if reverse_merge is called on a <tt>HashWithDifferentAccess</tt>.
def reverse_merge(other_hash)
- super other_hash.with_indifferent_access
+ super self.class.new_from_hash_copying_default(other_hash)
end
def reverse_merge!(other_hash)
@@ -131,11 +140,10 @@ module ActiveSupport
end
def convert_value(value)
- case value
- when Hash
- value.with_indifferent_access
- when Array
- value.collect { |e| e.is_a?(Hash) ? e.with_indifferent_access : e }
+ if value.class == Hash
+ self.class.new_from_hash_copying_default(value)
+ elsif value.is_a?(Array)
+ value.dup.replace(value.map { |e| convert_value(e) })
else
value
end
diff --git a/activesupport/lib/active_support/i18n.rb b/activesupport/lib/active_support/i18n.rb
index 45b9d20c01..00ea8813dd 100644
--- a/activesupport/lib/active_support/i18n.rb
+++ b/activesupport/lib/active_support/i18n.rb
@@ -1,9 +1,9 @@
begin
require 'i18n'
+ require 'active_support/lazy_load_hooks'
rescue LoadError => e
$stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
-ActiveSupport.run_load_hooks(:i18n)
diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb
index db09919fd3..a25e951080 100644
--- a/activesupport/lib/active_support/i18n_railtie.rb
+++ b/activesupport/lib/active_support/i18n_railtie.rb
@@ -14,19 +14,34 @@ module I18n
@reloader ||= ActiveSupport::FileUpdateChecker.new([]){ I18n.reload! }
end
- # Add I18n::Railtie.reloader to ActionDispatch callbacks. Since, at this
+ # Add <tt>I18n::Railtie.reloader</tt> to ActionDispatch callbacks. Since, at this
# point, no path was added to the reloader, I18n.reload! is not triggered
# on to_prepare callbacks. This will only happen on the config.after_initialize
# callback below.
initializer "i18n.callbacks" do
- ActionDispatch::Callbacks.to_prepare do
+ ActionDispatch::Reloader.to_prepare do
I18n::Railtie.reloader.execute_if_updated
end
end
- # Set the i18n configuration only after initialization since a lot of
+ # Set the i18n configuration after initialization since a lot of
# configuration is still usually done in application initializers.
config.after_initialize do |app|
+ I18n::Railtie.initialize_i18n(app)
+ end
+
+ # Trigger i18n config before any eager loading has happened
+ # so it's ready if any classes require it when eager loaded
+ config.before_eager_load do |app|
+ I18n::Railtie.initialize_i18n(app)
+ end
+
+ protected
+
+ # Setup i18n configuration
+ def self.initialize_i18n(app)
+ return if @i18n_inited
+
fallbacks = app.config.i18n.delete(:fallbacks)
app.config.i18n.each do |setting, value|
@@ -44,9 +59,9 @@ module I18n
reloader.paths.concat I18n.load_path
reloader.execute_if_updated
- end
- protected
+ @i18n_inited = true
+ end
def self.include_fallbacks_module
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
@@ -66,7 +81,7 @@ module I18n
I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
end
-
+
def self.validate_fallbacks(fallbacks)
case fallbacks
when ActiveSupport::OrderedOptions
@@ -78,4 +93,4 @@ module I18n
end
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index e7b5387ed7..06ceccdb22 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/activesupport/lib/active_support/inflections.rb
@@ -4,10 +4,12 @@ module ActiveSupport
inflect.plural(/s$/i, 's')
inflect.plural(/(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
+ inflect.plural(/(octop|vir)i$/i, '\1i')
inflect.plural(/(alias|status)$/i, '\1es')
inflect.plural(/(bu)s$/i, '\1ses')
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
+ inflect.plural(/([ti])a$/i, '\1a')
inflect.plural(/sis$/i, 'ses')
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
@@ -15,7 +17,9 @@ module ActiveSupport
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
inflect.plural(/([m|l])ouse$/i, '\1ice')
+ inflect.plural(/([m|l])ice$/i, '\1ice')
inflect.plural(/^(ox)$/i, '\1en')
+ inflect.plural(/^(oxen)$/i, '\1')
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/s$/i, '')
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
index 3caf78bc7d..e136e4c5b3 100644
--- a/activesupport/lib/active_support/inflector/inflections.rb
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -148,7 +148,7 @@ module ActiveSupport
def singularize(word)
result = word.to_s.dup
- if inflections.uncountables.any? { |inflection| result =~ /#{inflection}\Z/i }
+ if inflections.uncountables.any? { |inflection| result =~ /\b(#{inflection})\Z/i }
result
else
inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
diff --git a/activesupport/lib/active_support/inflector/transliterate.rb b/activesupport/lib/active_support/inflector/transliterate.rb
index bccc5425a6..40e7a0e389 100644
--- a/activesupport/lib/active_support/inflector/transliterate.rb
+++ b/activesupport/lib/active_support/inflector/transliterate.rb
@@ -1,5 +1,6 @@
# encoding: utf-8
require 'active_support/core_ext/string/multibyte'
+require 'active_support/i18n'
module ActiveSupport
module Inflector
diff --git a/activesupport/lib/active_support/json/backends/jsongem.rb b/activesupport/lib/active_support/json/backends/jsongem.rb
index cfe28d7bb9..533ba25da3 100644
--- a/activesupport/lib/active_support/json/backends/jsongem.rb
+++ b/activesupport/lib/active_support/json/backends/jsongem.rb
@@ -26,7 +26,11 @@ module ActiveSupport
when nil
nil
when DATE_REGEX
- DateTime.parse(data)
+ begin
+ DateTime.parse(data)
+ rescue ArgumentError
+ data
+ end
when Array
data.map! { |d| convert_dates_from(d) }
when Hash
diff --git a/activesupport/lib/active_support/json/backends/yajl.rb b/activesupport/lib/active_support/json/backends/yajl.rb
index 64e50e0d87..58818658c7 100644
--- a/activesupport/lib/active_support/json/backends/yajl.rb
+++ b/activesupport/lib/active_support/json/backends/yajl.rb
@@ -23,7 +23,11 @@ module ActiveSupport
when nil
nil
when DATE_REGEX
- DateTime.parse(data)
+ begin
+ DateTime.parse(data)
+ rescue ArgumentError
+ data
+ end
when Array
data.map! { |d| convert_dates_from(d) }
when Hash
diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb
index 4cb9d01077..e25e29d36b 100644
--- a/activesupport/lib/active_support/json/backends/yaml.rb
+++ b/activesupport/lib/active_support/json/backends/yaml.rb
@@ -7,14 +7,21 @@ module ActiveSupport
ParseError = ::StandardError
extend self
+ EXCEPTIONS = [::ArgumentError] # :nodoc:
+ begin
+ require 'psych'
+ EXCEPTIONS << Psych::SyntaxError
+ rescue LoadError
+ end
+
# Parses a JSON string or IO and converts it into an object
def decode(json)
if json.respond_to?(:read)
json = json.read
end
YAML.load(convert_json_to_yaml(json))
- rescue ArgumentError
- raise ParseError, "Invalid JSON string"
+ rescue *EXCEPTIONS => e
+ raise ParseError, "Invalid JSON string: '%s'" % json
end
protected
@@ -22,21 +29,21 @@ module ActiveSupport
def convert_json_to_yaml(json) #:nodoc:
require 'strscan' unless defined? ::StringScanner
scanner, quoting, marks, pos, times = ::StringScanner.new(json), false, [], nil, []
- while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/)
+ while scanner.scan_until(/(\\['"]|['":,\\]|\\.|[\]])/)
case char = scanner[1]
when '"', "'"
if !quoting
quoting = char
pos = scanner.pos
elsif quoting == char
- if json[pos..scanner.pos-2] =~ DATE_REGEX
+ if valid_date?(json[pos..scanner.pos-2])
# found a date, track the exact positions of the quotes so we can
# overwrite them with spaces later.
- times << pos << scanner.pos
+ times << pos
end
quoting = false
end
- when ":",","
+ when ":",",", "]"
marks << scanner.pos - 1 unless quoting
when "\\"
scanner.skip(/\\/)
@@ -47,7 +54,9 @@ module ActiveSupport
json.gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do
ustr = $1
if ustr.start_with?('u')
- [ustr[1..-1].to_i(16)].pack("U")
+ char = [ustr[1..-1].to_i(16)].pack("U")
+ # "\n" needs extra escaping due to yaml formatting
+ char == "\n" ? "\\n" : char
elsif ustr == '\\'
'\\\\'
else
@@ -61,14 +70,18 @@ module ActiveSupport
left_pos.each_with_index do |left, i|
scanner.pos = left.succ
chunk = scanner.peek(right_pos[i] - scanner.pos + 1)
- # overwrite the quotes found around the dates with spaces
- while times.size > 0 && times[0] <= right_pos[i]
- chunk[times.shift - scanner.pos - 1] = ' '
+ if ActiveSupport.parse_json_times
+ # overwrite the quotes found around the dates with spaces
+ while times.size > 0 && times[0] <= right_pos[i]
+ chunk.insert(times.shift - scanner.pos - 1, '! ')
+ end
end
chunk.gsub!(/\\([\\\/]|u[[:xdigit:]]{4})/) do
ustr = $1
if ustr.start_with?('u')
- [ustr[1..-1].to_i(16)].pack("U")
+ char = [ustr[1..-1].to_i(16)].pack("U")
+ # "\n" needs extra escaping due to yaml formatting
+ char == "\n" ? "\\n" : char
elsif ustr == '\\'
'\\\\'
else
@@ -83,6 +96,16 @@ module ActiveSupport
output
end
end
+
+ private
+ def valid_date?(date_string)
+ begin
+ date_string =~ DATE_REGEX && DateTime.parse(date_string)
+ rescue ArgumentError
+ false
+ end
+ end
+
end
end
end
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 2f9588e0f4..82b8a7e148 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -23,7 +23,7 @@ module ActiveSupport
module JSON
# matches YAML-formatted dates
- DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
+ DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
def self.encode(value, options = nil)
@@ -41,9 +41,26 @@ module ActiveSupport
@seen = []
end
- def encode(value)
+ def encode(value, use_options = true)
check_for_circular_references(value) do
- value.as_json(options).encode_json(self)
+ 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)
+ check_for_circular_references(value) do
+ value.as_json(options_for(value))
+ 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
end
end
@@ -136,6 +153,12 @@ class Object
end
end
+class Struct
+ def as_json(options = nil) #:nodoc:
+ Hash[members.zip(values)]
+ end
+end
+
class TrueClass
AS_JSON = ActiveSupport::JSON::Variable.new('true').freeze
def as_json(options = nil) AS_JSON end #:nodoc:
@@ -186,13 +209,22 @@ module Enumerable
end
class Array
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) "[#{map { |v| encoder.encode(v) } * ','}]" end #:nodoc:
+ 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) }
+ 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:
- if options
+ # create a subset of the hash by applying :only or :except
+ subset = if options
if attrs = options[:only]
slice(*Array.wrap(attrs))
elsif attrs = options[:except]
@@ -203,10 +235,21 @@ class Hash
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)
+ result = self.is_a?(ActiveSupport::OrderedHash) ? ActiveSupport::OrderedHash : Hash
+ result[subset.map { |k, v| [k.to_s, encoder.as_json(v)] }]
end
def encode_json(encoder)
- "{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v)}" } * ','}}"
+ # 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
diff --git a/activesupport/lib/active_support/lazy_load_hooks.rb b/activesupport/lib/active_support/lazy_load_hooks.rb
index ef43fc0431..82507c1e03 100644
--- a/activesupport/lib/active_support/lazy_load_hooks.rb
+++ b/activesupport/lib/active_support/lazy_load_hooks.rb
@@ -1,21 +1,21 @@
-# lazy_load_hooks allows rails to lazily load a lot of components and thus making the app boot faster. Because of
+# 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
+# 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.
+# 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)
+# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
#
module ActiveSupport
@load_hooks = Hash.new {|h,k| h[k] = [] }
diff --git a/activesupport/lib/active_support/locale/en.yml b/activesupport/lib/active_support/locale/en.yml
index 8f08f37a70..a1499bcc90 100644
--- a/activesupport/lib/active_support/locale/en.yml
+++ b/activesupport/lib/active_support/locale/en.yml
@@ -7,10 +7,10 @@ en:
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]
@@ -27,7 +27,7 @@ en:
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
-
+
# Used in array.to_sentence.
support:
array:
diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb
index 83930b3f0d..10675edac5 100644
--- a/activesupport/lib/active_support/log_subscriber.rb
+++ b/activesupport/lib/active_support/log_subscriber.rb
@@ -4,7 +4,7 @@ require 'active_support/core_ext/class/attribute'
module ActiveSupport
# ActiveSupport::LogSubscriber is an object set to consume ActiveSupport::Notifications
# with solely purpose of logging. The log subscriber dispatches notifications to a
- # regirested object based on its given namespace.
+ # registered object based on its given namespace.
#
# An example would be Active Record log subscriber responsible for logging queries:
#
@@ -16,12 +16,12 @@ module ActiveSupport
# end
# end
#
- # And it's finally registed as:
+ # 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 ActiveRecord::LogSubscriber definition.
+ # 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
@@ -31,23 +31,10 @@ module ActiveSupport
# all logs when the request finishes (via action_dispatch.callback notification) in
# a Rails environment.
class LogSubscriber
- mattr_accessor :colorize_logging
- self.colorize_logging = true
-
- class_attribute :logger
-
- class << self
- remove_method :logger
- end
-
- def self.logger
- @logger ||= Rails.logger if defined?(Rails)
- end
-
# Embed in a String to clear all previous ANSI sequences.
CLEAR = "\e[0m"
BOLD = "\e[1m"
-
+
# Colors
BLACK = "\e[30m"
RED = "\e[31m"
@@ -58,32 +45,44 @@ module ActiveSupport
CYAN = "\e[36m"
WHITE = "\e[37m"
- def self.attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications)
- log_subscribers << log_subscriber
- @@flushable_loggers = nil
+ mattr_accessor :colorize_logging
+ self.colorize_logging = true
+
+ class_attribute :logger
+
+ class << self
+ remove_method :logger
+ def logger
+ @logger ||= Rails.logger if defined?(Rails)
+ end
+
+ def attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications)
+ log_subscribers << log_subscriber
+ @@flushable_loggers = nil
- log_subscriber.public_methods(false).each do |event|
- next if 'call' == event.to_s
+ log_subscriber.public_methods(false).each do |event|
+ next if 'call' == event.to_s
- notifier.subscribe("#{event}.#{namespace}", log_subscriber)
+ notifier.subscribe("#{event}.#{namespace}", log_subscriber)
+ end
end
- end
- def self.log_subscribers
- @@log_subscribers ||= []
- end
+ def log_subscribers
+ @@log_subscribers ||= []
+ end
- def self.flushable_loggers
- @@flushable_loggers ||= begin
- loggers = log_subscribers.map(&:logger)
- loggers.uniq!
- loggers.select { |l| l.respond_to?(:flush) }
+ def flushable_loggers
+ @@flushable_loggers ||= begin
+ loggers = log_subscribers.map(&:logger)
+ loggers.uniq!
+ loggers.select { |l| l.respond_to?(:flush) }
+ end
end
- end
- # Flush all log_subscribers' logger.
- def self.flush_all!
- flushable_loggers.each(&:flush)
+ # Flush all log_subscribers' logger.
+ def flush_all!
+ flushable_loggers.each(&:flush)
+ end
end
def call(message, *args)
diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb
index 9e52cb97a9..392e33edbc 100644
--- a/activesupport/lib/active_support/log_subscriber/test_helper.rb
+++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb
@@ -12,7 +12,7 @@ module ActiveSupport
# def setup
# ActiveRecord::LogSubscriber.attach_to(:active_record)
# end
- #
+ #
# def test_basic_query_logging
# Developer.all
# wait
@@ -23,11 +23,11 @@ module ActiveSupport
# 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 is reponsible for setting
+ # 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 do not send anything to your output), and you can collect them
+ # 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.
#
@@ -38,13 +38,14 @@ module ActiveSupport
ActiveSupport::LogSubscriber.colorize_logging = false
+ @old_notifier = ActiveSupport::Notifications.notifier
set_logger(@logger)
ActiveSupport::Notifications.notifier = @notifier
end
def teardown
set_logger(nil)
- ActiveSupport::Notifications.notifier = nil
+ ActiveSupport::Notifications.notifier = @old_notifier
end
class MockLogger
diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb
index 9fb506fea1..0a7bcd5bb8 100644
--- a/activesupport/lib/active_support/memoizable.rb
+++ b/activesupport/lib/active_support/memoizable.rb
@@ -95,6 +95,8 @@ module ActiveSupport
#
if private_method_defined?(#{original_method.inspect}) # if private_method_defined?(:_unmemoized_mime_type)
private #{symbol.inspect} # private :mime_type
+ elsif protected_method_defined?(#{original_method.inspect}) # elsif protected_method_defined?(:_unmemoized_mime_type)
+ protected #{symbol.inspect} # protected :mime_type
end # end
EOS
end
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
index 51fa626b45..4f7cd12d48 100644
--- a/activesupport/lib/active_support/message_encryptor.rb
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -2,12 +2,12 @@ require 'openssl'
require 'active_support/base64'
module ActiveSupport
- # MessageEncryptor is a simple way to encrypt values which get stored somewhere
+ # 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 MessageVerifier, but where you don't
+ # This can be used in situations similar to the <tt>MessageVerifier</tt>, but where you don't
# want users to be able to determine the value of the payload.
class MessageEncryptor
class InvalidMessage < StandardError; end
@@ -17,53 +17,53 @@ module ActiveSupport
@secret = secret
@cipher = cipher
end
-
+
def encrypt(value)
cipher = new_cipher
# Rely on OpenSSL for the initialization vector
iv = cipher.random_iv
-
- cipher.encrypt
+
+ cipher.encrypt
cipher.key = @secret
cipher.iv = iv
-
- encrypted_data = cipher.update(Marshal.dump(value))
+
+ encrypted_data = cipher.update(Marshal.dump(value))
encrypted_data << cipher.final
[encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--")
end
-
+
def decrypt(encrypted_message)
cipher = new_cipher
encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)}
-
+
cipher.decrypt
cipher.key = @secret
cipher.iv = iv
decrypted_data = cipher.update(encrypted_data)
decrypted_data << cipher.final
-
+
Marshal.load(decrypted_data)
rescue OpenSSLCipherError, TypeError
raise InvalidMessage
end
-
+
def encrypt_and_sign(value)
verifier.generate(encrypt(value))
end
-
+
def decrypt_and_verify(value)
decrypt(verifier.verify(value))
end
-
-
-
- private
+
+
+
+ private
def new_cipher
OpenSSL::Cipher::Cipher.new(@cipher)
end
-
+
def verifier
MessageVerifier.new(@secret)
end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index 6c46b68eaf..8f3946325a 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -2,30 +2,30 @@ require 'active_support/base64'
require 'active_support/core_ext/object/blank'
module ActiveSupport
- # MessageVerifier makes it easy to generate and verify messages which are signed
+ # +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
- #
+ #
class MessageVerifier
class InvalidSignature < StandardError; end
-
+
def initialize(secret, digest = 'SHA1')
@secret = secret
@digest = digest
end
-
+
def verify(signed_message)
raise InvalidSignature if signed_message.blank?
@@ -36,12 +36,12 @@ module ActiveSupport
raise InvalidSignature
end
end
-
+
def generate(value)
data = ActiveSupport::Base64.encode64s(Marshal.dump(value))
"#{data}--#{generate_digest(data)}"
end
-
+
private
# constant-time comparison algorithm to prevent timing attacks
def secure_compare(a, b)
diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb
index 8ffdf5a1bf..57e8e24bf4 100644
--- a/activesupport/lib/active_support/multibyte.rb
+++ b/activesupport/lib/active_support/multibyte.rb
@@ -6,7 +6,7 @@ module ActiveSupport #:nodoc:
autoload :EncodingError, 'active_support/multibyte/exceptions'
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.
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index 019fb2df06..f9607f1aaf 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -64,7 +64,7 @@ module ActiveSupport #:nodoc:
# 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?(method, include_private=false)
- super || @wrapped_string.respond_to?(method, include_private) || false
+ super || @wrapped_string.respond_to?(method, include_private)
end
# Enable more predictable duck-typing on String-like classes. See Object#acts_like?.
@@ -270,13 +270,14 @@ module ActiveSupport #:nodoc:
@wrapped_string[*args] = replace_by
else
result = Unicode.u_unpack(@wrapped_string)
- if args[0].is_a?(Fixnum)
+ case args.first
+ when Fixnum
raise IndexError, "index #{args[0]} out of string" if args[0] >= result.length
min = args[0]
max = args[1].nil? ? min : (min + args[1] - 1)
range = Range.new(min, max)
replace_by = [replace_by].pack('U') if replace_by.is_a?(Fixnum)
- elsif args.first.is_a?(Range)
+ when Range
raise RangeError, "#{args[0]} out of range" if args[0].min >= result.length
range = args[0]
else
@@ -437,7 +438,7 @@ module ActiveSupport #:nodoc:
begin
@wrapped_string[0...byte_offset].unpack('U*').length
- rescue ArgumentError => e
+ rescue ArgumentError
byte_offset -= 1
retry
end
diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb
index 1139783b65..513f83e445 100644
--- a/activesupport/lib/active_support/multibyte/unicode.rb
+++ b/activesupport/lib/active_support/multibyte/unicode.rb
@@ -247,7 +247,7 @@ module ActiveSupport
if is_unused || is_restricted
bytes[i] = tidy_byte(byte)
elsif is_cont
- # Not expecting contination byte? Clean up. Otherwise, now expect one less.
+ # 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
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index fd79188ba4..77696eb1db 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -44,8 +44,11 @@ module ActiveSupport
@instrumenters = Hash.new { |h,k| h[k] = notifier.listening?(k) }
class << self
- attr_writer :notifier
- delegate :publish, :to => :notifier
+ attr_accessor :notifier
+
+ def publish(name, *args)
+ notifier.publish(name, *args)
+ end
def instrument(name, payload = {})
if @instrumenters[name]
@@ -61,18 +64,16 @@ module ActiveSupport
end
end
- def unsubscribe(*args)
- notifier.unsubscribe(*args)
+ def unsubscribe(args)
+ notifier.unsubscribe(args)
@instrumenters.clear
end
- def notifier
- @notifier ||= Fanout.new
- end
-
def instrumenter
Thread.current[:"instrumentation_#{notifier.object_id}"] ||= Instrumenter.new(notifier)
end
end
+
+ self.notifier = Fanout.new
end
end
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 2e8d538d0b..fbc40d1b69 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -1,3 +1,8 @@
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
YAML.add_builtin_type("omap") do |type, val|
@@ -8,21 +13,29 @@ module ActiveSupport
# The order of iteration over hashes in Ruby 1.8 is undefined. For example, you do not know the
# order in which +keys+ will return keys, or +each+ yield pairs. <tt>ActiveSupport::OrderedHash</tt>
# implements a hash that preserves insertion order, as in Ruby 1.9:
- #
+ #
# oh = ActiveSupport::OrderedHash.new
# oh[:a] = 1
# oh[:b] = 2
# oh.keys # => [:a, :b], this order is guaranteed
- #
+ #
# <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts with other implementations.
class OrderedHash < ::Hash #:nodoc:
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 to_yaml(opts = {})
+ if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
+ return super
+ end
+
YAML.quick_emit(self, opts) do |out|
- out.seq(taguri, to_yaml_style) do |seq|
+ out.seq(taguri) do |seq|
each do |k, v|
seq.add(k => v)
end
@@ -79,7 +92,7 @@ module ActiveSupport
end
def []=(key, value)
- @keys << key if !has_key?(key)
+ @keys << key unless has_key?(key)
super
end
@@ -124,19 +137,27 @@ module ActiveSupport
end
def each_key
+ return to_enum(:each_key) unless block_given?
@keys.each { |key| yield key }
+ self
end
def each_value
+ return to_enum(:each_value) unless block_given?
@keys.each { |key| yield self[key]}
+ self
end
def each
+ return to_enum(:each) unless block_given?
@keys.each {|key| yield [key, self[key]]}
+ self
end
alias_method :each_pair, :each
+ alias_method :select, :find_all
+
def clear
super
@keys.clear
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
index 7fc2b45b51..8d8e6ebc58 100644
--- a/activesupport/lib/active_support/ordered_options.rb
+++ b/activesupport/lib/active_support/ordered_options.rb
@@ -1,23 +1,26 @@
require 'active_support/ordered_hash'
# Usually key value pairs are handled something like this:
-#
-# h = ActiveSupport::OrderedOptions.new
+#
+# h = {}
# h[:boy] = 'John'
# h[:girl] = 'Mary'
# h[:boy] # => 'John'
# h[:girl] # => 'Mary'
-#
-# Using <tt>OrderedOptions</tt> above code could be reduced to:
+#
+# Using <tt>OrderedOptions</tt>, the above code could be reduced to:
#
# h = ActiveSupport::OrderedOptions.new
# h.boy = 'John'
# h.girl = 'Mary'
# h.boy # => 'John'
# h.girl # => 'Mary'
-#
+#
module ActiveSupport #:nodoc:
class OrderedOptions < OrderedHash
+ alias_method :_get, :[] # preserve the original #[] method
+ protected :_get # make it protected
+
def []=(key, value)
super(key.to_sym, value)
end
@@ -28,7 +31,7 @@ module ActiveSupport #:nodoc:
def method_missing(name, *args)
if name.to_s =~ /(.*)=$/
- self[$1.to_sym] = args.first
+ self[$1] = args.first
else
self[name]
end
@@ -36,8 +39,19 @@ module ActiveSupport #:nodoc:
end
class InheritableOptions < OrderedOptions
- def initialize(parent)
- super() { |h,k| parent[k] }
+ 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/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
index cd6f92cdfe..0f4a06468a 100644
--- a/activesupport/lib/active_support/rescuable.rb
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -47,6 +47,7 @@ module ActiveSupport
# exception.record.new_record? ? ...
# end
# end
+ #
def rescue_from(*klasses, &block)
options = klasses.extract_options!
diff --git a/activesupport/lib/active_support/secure_random.rb b/activesupport/lib/active_support/secure_random.rb
index 73344498cb..368954907f 100644
--- a/activesupport/lib/active_support/secure_random.rb
+++ b/activesupport/lib/active_support/secure_random.rb
@@ -46,8 +46,10 @@ module ActiveSupport
# p SecureRandom.random_bytes(10) # => "\016\t{\370g\310pbr\301"
# p SecureRandom.random_bytes(10) # => "\323U\030TO\234\357\020\a\337"
# ...
+ #
module SecureRandom
- # SecureRandom.random_bytes generates a random binary string.
+
+ # Generates a random binary string.
#
# The argument n specifies the length of the result string.
#
@@ -56,6 +58,7 @@ module ActiveSupport
#
# If secure random number generator is not available,
# NotImplementedError is raised.
+ #
def self.random_bytes(n=nil)
n ||= 16
@@ -92,7 +95,7 @@ module ActiveSupport
end
end
- if !defined?(@has_win32)
+ unless defined?(@has_win32)
begin
require 'Win32API'
@@ -124,7 +127,7 @@ module ActiveSupport
raise NotImplementedError, "No random device"
end
- # SecureRandom.hex generates a random hex string.
+ # Generates a random hex string.
#
# The argument n specifies the length of the random length.
# The length of the result string is twice of n.
@@ -134,11 +137,12 @@ module ActiveSupport
#
# If secure random number generator is not available,
# NotImplementedError is raised.
+ #
def self.hex(n=nil)
random_bytes(n).unpack("H*")[0]
end
- # SecureRandom.base64 generates a random base64 string.
+ # Generates a random base64 string.
#
# The argument n specifies the length of the random length.
# The length of the result string is about 4/3 of n.
@@ -148,11 +152,12 @@ module ActiveSupport
#
# If secure random number generator is not available,
# NotImplementedError is raised.
+ #
def self.base64(n=nil)
[random_bytes(n)].pack("m*").delete("\n")
end
- # SecureRandom.random_number generates a random number.
+ # Generates a random number.
#
# If an positive integer is given as n,
# SecureRandom.random_number returns an integer:
@@ -161,6 +166,7 @@ module ActiveSupport
# If 0 is given or an argument is not given,
# SecureRandom.random_number returns an float:
# 0.0 <= SecureRandom.random_number() < 1.0.
+ #
def self.random_number(n=0)
if 0 < n
hex = n.to_s(16)
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index ed8c02ba3e..fb52fc7083 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -24,8 +24,7 @@ module ActiveSupport
else
Assertion = Test::Unit::AssertionFailedError
- require 'active_support/testing/default'
- include ActiveSupport::Testing::Default
+ undef :default_test
end
$tags = {}
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
index 33793f0688..a4e0361a32 100644
--- a/activesupport/lib/active_support/testing/assertions.rb
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -63,19 +63,21 @@ module ActiveSupport
def assert_no_difference(expression, message = nil, &block)
assert_difference expression, 0, message, &block
end
-
+
# Test if an expression is blank. Passes if object.blank? is true.
#
# assert_blank [] # => true
- def assert_blank(object)
- assert object.blank?, "#{object.inspect} is not blank"
+ def assert_blank(object, message=nil)
+ message ||= "#{object.inspect} is not blank"
+ assert object.blank?, message
end
-
+
# Test if an expression is not blank. Passes if object.present? is true.
#
# assert_present {:data => 'x' } # => true
- def assert_present(object)
- assert object.present?, "#{object.inspect} is blank"
+ def assert_present(object, message=nil)
+ message ||= "#{object.inspect} is blank"
+ assert object.present?, message
end
end
end
diff --git a/activesupport/lib/active_support/testing/declarative.rb b/activesupport/lib/active_support/testing/declarative.rb
index 70a6c2ca60..1c05d45888 100644
--- a/activesupport/lib/active_support/testing/declarative.rb
+++ b/activesupport/lib/active_support/testing/declarative.rb
@@ -1,10 +1,10 @@
module ActiveSupport
module Testing
module Declarative
-
+
def self.extended(klass)
klass.class_eval do
-
+
unless method_defined?(:describe)
def self.describe(text)
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
@@ -14,9 +14,9 @@ module ActiveSupport
RUBY_EVAL
end
end
-
+
end
- end
+ end
unless defined?(Spec)
# test "verify something" do
diff --git a/activesupport/lib/active_support/testing/default.rb b/activesupport/lib/active_support/testing/default.rb
deleted file mode 100644
index a0bd6303c7..0000000000
--- a/activesupport/lib/active_support/testing/default.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-module ActiveSupport
- module Testing
- module Default #:nodoc:
- # Placeholder so test/unit ignores test cases without any tests.
- def default_test
- end
- end
- end
-end
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
index d629f6f2b7..6b29ba4c10 100644
--- a/activesupport/lib/active_support/testing/isolation.rb
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -34,7 +34,7 @@ module ActiveSupport
module Isolation
def self.forking_env?
- !ENV["NO_FORK"] && ((Config::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
+ !ENV["NO_FORK"] && ((RbConfig::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
end
def self.included(base)
diff --git a/activesupport/lib/active_support/testing/pending.rb b/activesupport/lib/active_support/testing/pending.rb
index 21134ff9e2..3d119e2fba 100644
--- a/activesupport/lib/active_support/testing/pending.rb
+++ b/activesupport/lib/active_support/testing/pending.rb
@@ -1,5 +1,5 @@
# Some code from jeremymcanally's "pending"
-# http://github.com/jeremymcanally/pending/tree/master
+# https://github.com/jeremymcanally/pending/tree/master
module ActiveSupport
module Testing
@@ -25,13 +25,13 @@ module ActiveSupport
failed = true
end
- flunk("<#{description}> did not fail.") unless failed
+ flunk("<#{description}> did not fail.") unless failed
end
caller[0] =~ (/(.*):(.*):in `(.*)'/)
@@pending_cases << "#{$3} at #{$1}, line #{$2}"
print "P"
-
+
@@at_exit ||= begin
at_exit do
puts "\nPending Cases:"
@@ -42,7 +42,7 @@ module ActiveSupport
end
end
end
-
+
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb
index f7ddf6421d..8c91a061fb 100644
--- a/activesupport/lib/active_support/testing/performance.rb
+++ b/activesupport/lib/active_support/testing/performance.rb
@@ -58,16 +58,16 @@ begin
metric.send(mode) { __send__ @method_name }
rescue ::Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
- rescue StandardError, ScriptError
- add_error($!)
+ rescue StandardError, ScriptError => e
+ add_error(e)
ensure
begin
teardown
run_callbacks :teardown, :enumerator => :reverse_each
rescue ::Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
- rescue StandardError, ScriptError
- add_error($!)
+ rescue StandardError, ScriptError => e
+ add_error(e)
end
end
@@ -401,7 +401,7 @@ begin
Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME)
# Ruby 1.9 with GC::Profiler
- if GC.respond_to?(:total_time)
+ if defined?(GC::Profiler) && GC::Profiler.respond_to?(:total_time)
def measure
GC::Profiler.total_time
end
diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb
index b2d9ddfeb7..22e41fa905 100644
--- a/activesupport/lib/active_support/testing/setup_and_teardown.rb
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -31,14 +31,14 @@ module ActiveSupport
def run(runner)
result = '.'
begin
- _run_setup_callbacks do
+ run_callbacks :setup do
result = super
end
rescue Exception => e
result = runner.puke(self.class, method_name, e)
ensure
begin
- _run_teardown_callbacks
+ run_callbacks :teardown
rescue Exception => e
result = runner.puke(self.class, method_name, e)
end
@@ -62,7 +62,7 @@ module ActiveSupport
begin
begin
- _run_setup_callbacks do
+ run_callbacks :setup do
setup
__send__(@method_name)
mocha_verify(mocha_counter) if mocha_counter
@@ -77,7 +77,7 @@ module ActiveSupport
ensure
begin
teardown
- _run_teardown_callbacks
+ run_callbacks :teardown
rescue Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue Exception => e
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index ad6c3de1f5..c66aa78ce8 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -18,7 +18,7 @@ module ActiveSupport
#
# 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.
+ # TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangeable.
# Examples:
#
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
@@ -32,11 +32,12 @@ module ActiveSupport
# t > Time.utc(1999) # => true
# t.is_a?(Time) # => true
# t.is_a?(ActiveSupport::TimeWithZone) # => true
+ #
class TimeWithZone
def self.name
'Time' # Report class name as 'Time' to thwart type checking
end
-
+
include Comparable
attr_reader :time_zone
@@ -72,7 +73,7 @@ module ActiveSupport
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your system's <tt>ENV['TZ']</tt> zone
def localtime
- utc.getlocal
+ utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal
end
alias_method :getlocal, :localtime
@@ -127,6 +128,7 @@ module ActiveSupport
# # 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
@@ -135,14 +137,20 @@ module ActiveSupport
end
end
- def to_yaml(options = {})
- if options.kind_of?(YAML::Emitter)
- utc.to_yaml(options)
+ def encode_with(coder)
+ if coder.respond_to?(:represent_object)
+ coder.represent_object(nil, utc)
else
- time.to_yaml(options).gsub('Z', formatted_offset(true, 'Z'))
+ coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
end
end
+ def to_yaml(options = {})
+ return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
+
+ utc.to_yaml(options)
+ end
+
def httpdate
utc.httpdate
end
@@ -273,7 +281,7 @@ module ActiveSupport
# A TimeWithZone acts like a Time, so just return +self+.
def to_time
- self
+ utc
end
def to_datetime
diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb
index 9d2cf13260..690fc7f0fc 100644
--- a/activesupport/lib/active_support/version.rb
+++ b/activesupport/lib/active_support/version.rb
@@ -1,10 +1,10 @@
module ActiveSupport
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activesupport/lib/active_support/whiny_nil.rb b/activesupport/lib/active_support/whiny_nil.rb
index 91ddef2619..bcedbfd57a 100644
--- a/activesupport/lib/active_support/whiny_nil.rb
+++ b/activesupport/lib/active_support/whiny_nil.rb
@@ -37,7 +37,7 @@ class NilClass
# Raises a RuntimeError when you attempt to call +id+ on +nil+.
def id
- raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller
+ raise RuntimeError, "Called id for nil, which would mistakenly be #{object_id} -- if you really wanted the id of nil, use object_id", caller
end
private
diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb
index 352172027b..cddfcddb57 100644
--- a/activesupport/lib/active_support/xml_mini.rb
+++ b/activesupport/lib/active_support/xml_mini.rb
@@ -25,7 +25,7 @@ module ActiveSupport
DEFAULT_ENCODINGS = {
"binary" => "base64"
- } unless defined?(TYPE_NAMES)
+ } unless defined?(DEFAULT_ENCODINGS)
TYPE_NAMES = {
"Symbol" => "symbol",
@@ -126,9 +126,11 @@ module ActiveSupport
end
def rename_key(key, options = {})
- camelize = options.has_key?(:camelize) && options[:camelize]
+ camelize = options[:camelize]
dasherize = !options.has_key?(:dasherize) || options[:dasherize]
- key = key.camelize if camelize
+ if camelize
+ key = true == camelize ? key.camelize : key.camelize(camelize)
+ end
key = _dasherize(key) if dasherize
key
end
diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb
index 7fdcb11465..16570c6aea 100644
--- a/activesupport/lib/active_support/xml_mini/libxml.rb
+++ b/activesupport/lib/active_support/xml_mini/libxml.rb
@@ -1,5 +1,6 @@
require 'libxml'
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini LibXML implementation
module ActiveSupport
diff --git a/activesupport/lib/active_support/xml_mini/libxmlsax.rb b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
index fe2c1b9349..2536b1f33e 100644
--- a/activesupport/lib/active_support/xml_mini/libxmlsax.rb
+++ b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
@@ -1,5 +1,6 @@
require 'libxml'
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini LibXML implementation using a SAX-based parser
module ActiveSupport
@@ -82,4 +83,4 @@ module ActiveSupport
end
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb
index e03a744257..04ec9e8ab8 100644
--- a/activesupport/lib/active_support/xml_mini/nokogiri.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb
@@ -5,6 +5,7 @@ rescue LoadError => e
raise e
end
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini Nokogiri implementation
module ActiveSupport
diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
index 38c8685390..93fd3dfe57 100644
--- a/activesupport/lib/active_support/xml_mini/nokogirisax.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
@@ -5,6 +5,7 @@ rescue LoadError => e
raise e
end
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini Nokogiri implementation using a SAX-based parser
module ActiveSupport
@@ -38,8 +39,7 @@ module ActiveSupport
end
def start_element(name, attrs = [])
- new_hash = { CONTENT_KEY => '' }
- new_hash[attrs.shift] = attrs.shift while attrs.length > 0
+ new_hash = { CONTENT_KEY => '' }.merge(Hash[attrs])
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
case current_hash[name]
diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb
index a58f22ee5d..a13ad10118 100644
--- a/activesupport/lib/active_support/xml_mini/rexml.rb
+++ b/activesupport/lib/active_support/xml_mini/rexml.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini ReXML implementation
module ActiveSupport
@@ -19,7 +20,7 @@ module ActiveSupport
if !data.respond_to?(:read)
data = StringIO.new(data || '')
end
-
+
char = data.getc
if char.nil?
{}
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
index 6db21f9e12..0382739871 100644
--- a/activesupport/test/abstract_unit.rb
+++ b/activesupport/test/abstract_unit.rb
@@ -10,8 +10,19 @@ end
lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
-require 'test/unit'
require 'active_support/core_ext/kernel/reporting'
+
+require 'active_support/core_ext/string/encoding'
+if "ruby".encoding_aware?
+ # 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
+end
+
+require 'test/unit'
require 'empty_bool'
silence_warnings { require 'mocha' }
diff --git a/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb b/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
index 77ea230d2c..57a13d89ea 100644
--- a/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
+++ b/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
@@ -1,7 +1,7 @@
class ClassFolder
class NestedClass
end
-
+
class SiblingClass
end
end
diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb
index 97c0ef14db..8d1b1c02c6 100644
--- a/activesupport/test/buffered_logger_test.rb
+++ b/activesupport/test/buffered_logger_test.rb
@@ -115,11 +115,9 @@ class BufferedLoggerTest < Test::Unit::TestCase
def test_should_create_the_log_directory_if_it_doesnt_exist
tmp_directory = File.join(File.dirname(__FILE__), "tmp")
log_file = File.join(tmp_directory, "development.log")
- assert !File.exist?(tmp_directory)
+ FileUtils.rm_rf(tmp_directory)
@logger = Logger.new(log_file)
assert File.exist?(tmp_directory)
- ensure
- FileUtils.rm_rf(tmp_directory)
end
def test_logger_should_maintain_separate_buffers_for_each_thread
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index b79a7bbaec..e5668e29d7 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -356,9 +356,13 @@ 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_equal false, @cache.exist?("foo")
assert_equal true, @cache.exist?("fu")
+ assert_equal false, @cache.exist?("foo/bar")
+ assert_equal true, @cache.exist?("fu/baz")
end
end
@@ -509,6 +513,11 @@ class FileStoreTest < ActiveSupport::TestCase
assert_nil old_cache.read('foo')
end
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
end
class MemoryStoreTest < ActiveSupport::TestCase
@@ -649,12 +658,12 @@ class CacheStoreLoggerTest < ActiveSupport::TestCase
def test_logging
@cache.fetch('foo') { 'bar' }
- assert @buffer.string.present?
+ assert_present @buffer.string
end
def test_mute_logging
@cache.mute { @cache.fetch('foo') { 'bar' } }
- assert @buffer.string.blank?
+ assert_blank @buffer.string
end
end
@@ -670,12 +679,12 @@ class CacheEntryTest < ActiveSupport::TestCase
def test_expired
entry = ActiveSupport::Cache::Entry.new("value")
- assert_equal false, entry.expired?
+ assert !entry.expired?, 'entry not expired'
entry = ActiveSupport::Cache::Entry.new("value", :expires_in => 60)
- assert_equal false, entry.expired?
+ assert !entry.expired?, 'entry not expired'
time = Time.now + 61
Time.stubs(:now).returns(time)
- assert_equal true, entry.expired?
+ assert entry.expired?, 'entry is expired'
end
def test_compress_values
diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb
index 8caf000c5d..d569cbb4fb 100644
--- a/activesupport/test/callback_inheritance_test.rb
+++ b/activesupport/test/callback_inheritance_test.rb
@@ -70,7 +70,7 @@ class EmptyParent
end
def dispatch
- _run_dispatch_callbacks
+ run_callbacks :dispatch
self
end
end
@@ -82,6 +82,30 @@ class EmptyChild < EmptyParent
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 < Test::Unit::TestCase
def setup
@index = GrandParent.new("index").dispatch
@@ -147,4 +171,10 @@ class DynamicInheritedCallbacks < Test::Unit::TestCase
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
index 70a2950f9b..816dcad968 100644
--- a/activesupport/test/callbacks_test.rb
+++ b/activesupport/test/callbacks_test.rb
@@ -3,6 +3,27 @@ require 'test/unit'
require 'active_support'
module CallbacksTest
+ class Phone
+ include ActiveSupport::Callbacks
+ define_callbacks :save, :rescuable => true
+
+ set_callback :save, :before, :before_save1
+ set_callback :save, :after, :after_save1
+
+ def before_save1; self.history << :before; end
+ def after_save1; self.history << :after; end
+
+ def save
+ run_callbacks :save do
+ raise 'boom'
+ end
+ end
+
+ def history
+ @history ||= []
+ end
+ end
+
class Record
include ActiveSupport::Callbacks
@@ -149,6 +170,27 @@ module CallbacksTest
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 < Test::Unit::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 }
@@ -257,6 +299,32 @@ module CallbacksTest
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
@@ -296,6 +364,14 @@ module CallbacksTest
], around.history
end
end
+
+ class AroundCallbackResultTest < Test::Unit::TestCase
+ def test_save_around
+ around = AroundPersonResult.new
+ around.save
+ assert_equal :running, around.result
+ end
+ end
class SkipCallbacksTest < Test::Unit::TestCase
def test_skip_person
@@ -317,6 +393,14 @@ module CallbacksTest
end
class CallbacksTest < Test::Unit::TestCase
+ def test_save_phone
+ phone = Phone.new
+ assert_raise RuntimeError do
+ phone.save
+ end
+ assert_equal [:before, :after], phone.history
+ end
+
def test_save_person
person = Person.new
assert_equal [], person.history
@@ -352,6 +436,8 @@ module CallbacksTest
end
end
+
+
class ResetCallbackTest < Test::Unit::TestCase
def test_save_conditional_person
person = CleanPerson.new
@@ -524,4 +610,31 @@ module CallbacksTest
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 < Test::Unit::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, :block],
+ [:after_save, :block],
+ [:after_save, :object],
+ [:after_save, :proc],
+ [:after_save, :string],
+ [:after_save, :symbol]
+ ], writer.history
+ end
+ end
+
end
diff --git a/activesupport/test/class_cache_test.rb b/activesupport/test/class_cache_test.rb
new file mode 100644
index 0000000000..8445af8d25
--- /dev/null
+++ b/activesupport/test/class_cache_test.rb
@@ -0,0 +1,108 @@
+require 'abstract_unit'
+require 'active_support/dependencies'
+
+module ActiveSupport
+ module Dependencies
+ class ClassCacheTest < ActiveSupport::TestCase
+ def setup
+ @cache = ClassCache.new
+ end
+
+ def test_empty?
+ assert @cache.empty?
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert !@cache.empty?
+ end
+
+ def test_clear!
+ assert @cache.empty?
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert !@cache.empty?
+ @cache.clear!
+ assert @cache.empty?
+ end
+
+ def test_set_key
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert @cache.key?(ClassCacheTest.name)
+ end
+
+ def test_set_rejects_strings
+ @cache[ClassCacheTest.name] = ClassCacheTest
+ assert @cache.empty?
+ end
+
+ def test_get_with_class
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert_equal ClassCacheTest, @cache[ClassCacheTest]
+ end
+
+ def test_get_with_name
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert_equal ClassCacheTest, @cache[ClassCacheTest.name]
+ end
+
+ def test_get_constantizes
+ assert @cache.empty?
+ assert_equal ClassCacheTest, @cache[ClassCacheTest.name]
+ end
+
+ def test_get_is_an_alias
+ assert_equal @cache[ClassCacheTest], @cache.get(ClassCacheTest.name)
+ end
+
+ def test_new
+ assert_deprecated do
+ @cache.new ClassCacheTest
+ end
+ assert @cache.key?(ClassCacheTest.name)
+ end
+
+ def test_new_rejects_strings
+ assert_deprecated do
+ @cache.new ClassCacheTest.name
+ end
+ assert !@cache.key?(ClassCacheTest.name)
+ end
+
+ def test_new_rejects_strings
+ @cache.store ClassCacheTest.name
+ assert !@cache.key?(ClassCacheTest.name)
+ end
+
+ def test_store_returns_self
+ x = @cache.store ClassCacheTest
+ assert_equal @cache, x
+ end
+
+ def test_new_returns_proxy
+ v = nil
+ assert_deprecated do
+ v = @cache.new ClassCacheTest.name
+ end
+
+ assert_deprecated do
+ assert_equal ClassCacheTest, v.get
+ end
+ end
+
+ def test_anonymous_class_fail
+ assert_raises(ArgumentError) do
+ assert_deprecated do
+ @cache.new Class.new
+ end
+ end
+
+ assert_raises(ArgumentError) do
+ x = Class.new
+ @cache[x] = x
+ end
+
+ assert_raises(ArgumentError) do
+ x = Class.new
+ @cache.store x
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/test/clean_backtrace_test.rb b/activesupport/test/clean_backtrace_test.rb
index 86838a7f9a..32e346bb48 100644
--- a/activesupport/test/clean_backtrace_test.rb
+++ b/activesupport/test/clean_backtrace_test.rb
@@ -5,7 +5,7 @@ class BacktraceCleanerFilterTest < ActiveSupport::TestCase
@bc = ActiveSupport::BacktraceCleaner.new
@bc.add_filter { |line| line.gsub("/my/prefix", '') }
end
-
+
test "backtrace should not contain prefix when it has been filtered out" do
assert_equal "/my/class.rb", @bc.clean([ "/my/prefix/my/class.rb" ]).first
end
@@ -14,14 +14,14 @@ class BacktraceCleanerFilterTest < ActiveSupport::TestCase
@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
-
+
test "backtrace should filter all lines in a backtrace" do
assert_equal \
- ["/my/class.rb", "/my/module.rb"],
+ ["/my/class.rb", "/my/module.rb"],
@bc.clean([ "/my/prefix/my/class.rb", "/my/prefix/my/module.rb" ])
end
end
@@ -31,10 +31,10 @@ class BacktraceCleanerSilencerTest < ActiveSupport::TestCase
@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" ],
+ [ "/other/class.rb" ],
@bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb" ])
end
end
@@ -45,7 +45,7 @@ class BacktraceCleanerFilterAndSilencerTest < ActiveSupport::TestCase
@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
diff --git a/activesupport/test/clean_logger_test.rb b/activesupport/test/clean_logger_test.rb
index 6c4ec5ac46..2cc46904b4 100644
--- a/activesupport/test/clean_logger_test.rb
+++ b/activesupport/test/clean_logger_test.rb
@@ -41,7 +41,7 @@ class CleanLoggerTest < Test::Unit::TestCase
assert_equal "error\nfatal\nerror\nfatal\nunsilenced\n", @out.string
end
-
+
def test_datetime_format
@logger.formatter = Logger::Formatter.new
@logger.datetime_format = "%Y-%m-%d"
@@ -49,7 +49,7 @@ class CleanLoggerTest < Test::Unit::TestCase
assert_equal "%Y-%m-%d", @logger.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
diff --git a/activesupport/test/configurable_test.rb b/activesupport/test/configurable_test.rb
index cef67e3cf9..2b28e61815 100644
--- a/activesupport/test/configurable_test.rb
+++ b/activesupport/test/configurable_test.rb
@@ -21,6 +21,12 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert_equal({ :foo => :bar }, Parent.config)
end
+ test "adds a configuration hash to a module as well" do
+ mixin = Module.new { include ActiveSupport::Configurable }
+ mixin.config.foo = :bar
+ assert_equal({ :foo => :bar }, mixin.config)
+ end
+
test "configuration hash is inheritable" do
assert_equal :bar, Child.config.foo
assert_equal :bar, Parent.config.foo
@@ -39,4 +45,22 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert_equal :baz, instance.config.foo
assert_equal :bar, Parent.config.foo
end
-end \ No newline at end of file
+
+ test "configuration is crystalizeable" do
+ parent = Class.new { include ActiveSupport::Configurable }
+ child = Class.new(parent)
+
+ parent.config.bar = :foo
+ assert !parent.config.respond_to?(:bar)
+ assert !child.config.respond_to?(:bar)
+ assert !child.new.config.respond_to?(:bar)
+
+ parent.config.compile_methods!
+ assert_equal :foo, parent.config.bar
+ assert_equal :foo, child.new.config.bar
+
+ assert_respond_to parent.config, :bar
+ assert_respond_to child.config, :bar
+ assert_respond_to child.new.config, :bar
+ end
+end
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
index 009a254c64..d7ab3ce605 100644
--- a/activesupport/test/core_ext/array_ext_test.rb
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -18,10 +18,10 @@ class ArrayExtAccessTests < Test::Unit::TestCase
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
@@ -82,6 +82,11 @@ class ArrayExtToSentenceTests < Test::Unit::TestCase
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
@@ -319,7 +324,7 @@ class ArrayExtractOptionsTests < Test::Unit::TestCase
assert_equal({}, options)
assert_equal [hash], array
end
-
+
def test_extract_options_extracts_extractable_subclass
hash = ExtractableHashSubclass.new
hash[:foo] = 1
@@ -370,14 +375,14 @@ class ArrayExtRandomTests < ActiveSupport::TestCase
assert_equal 2, s.size
assert_equal 1, (a-s).size
assert_equal [], a-(0..20).sum{a.sample(2)}
-
+
o = Object.new
def o.to_int; 1; end
assert_equal [0], [0].sample(o)
-
+
o = Object.new
assert_raises(TypeError) { [0].sample(o) }
-
+
o = Object.new
def o.to_int; ''; end
assert_raises(TypeError) { [0].sample(o) }
diff --git a/activesupport/test/core_ext/bigdecimal.rb b/activesupport/test/core_ext/bigdecimal.rb
deleted file mode 100644
index 9faad9146f..0000000000
--- a/activesupport/test/core_ext/bigdecimal.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'abstract_unit'
-
-class BigDecimalTest < Test::Unit::TestCase
- def test_to_yaml
- assert_equal("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml)
- assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml)
- assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml)
- assert_equal("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml)
- end
-end \ No newline at end of file
diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb
new file mode 100644
index 0000000000..b38e08a9f4
--- /dev/null
+++ b/activesupport/test/core_ext/bigdecimal_test.rb
@@ -0,0 +1,17 @@
+require 'abstract_unit'
+require 'bigdecimal'
+require 'active_support/core_ext/big_decimal'
+
+class BigDecimalTest < Test::Unit::TestCase
+ def test_to_yaml
+ assert_match("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml)
+ assert_match("--- .Inf\n", BigDecimal.new('Infinity').to_yaml)
+ assert_match("--- .NaN\n", BigDecimal.new('NaN').to_yaml)
+ assert_match("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml)
+ end
+
+ def test_to_d
+ bd = BigDecimal.new '10'
+ assert_equal bd, bd.to_d
+ end
+end
diff --git a/activesupport/test/core_ext/cgi_ext_test.rb b/activesupport/test/core_ext/cgi_ext_test.rb
deleted file mode 100644
index c80362e382..0000000000
--- a/activesupport/test/core_ext/cgi_ext_test.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-require 'abstract_unit'
-require 'active_support/core_ext/cgi'
-
-class EscapeSkippingSlashesTest < Test::Unit::TestCase
- def test_array
- assert_equal 'hello/world', CGI.escape_skipping_slashes(%w(hello world))
- assert_equal 'hello+world/how/are/you', CGI.escape_skipping_slashes(['hello world', 'how', 'are', 'you'])
- end
-
- def test_typical
- assert_equal 'hi', CGI.escape_skipping_slashes('hi')
- assert_equal 'hi/world', CGI.escape_skipping_slashes('hi/world')
- assert_equal 'hi/world+you+funky+thing', CGI.escape_skipping_slashes('hi/world you funky thing')
- end
-end
diff --git a/activesupport/test/core_ext/class/attribute_accessor_test.rb b/activesupport/test/core_ext/class/attribute_accessor_test.rb
index 2c896d0cdb..456f4b7948 100644
--- a/activesupport/test/core_ext/class/attribute_accessor_test.rb
+++ b/activesupport/test/core_ext/class/attribute_accessor_test.rb
@@ -10,27 +10,27 @@ class ClassAttributeAccessorTest < Test::Unit::TestCase
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)
diff --git a/activesupport/test/core_ext/class/attribute_test.rb b/activesupport/test/core_ext/class/attribute_test.rb
index 24aa5c0eba..d58b60482b 100644
--- a/activesupport/test/core_ext/class/attribute_test.rb
+++ b/activesupport/test/core_ext/class/attribute_test.rb
@@ -65,4 +65,9 @@ class ClassAttributeTest < ActiveSupport::TestCase
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/class_inheritable_attributes_test.rb b/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb
index 63ea46b564..020dfce56a 100644
--- a/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb
+++ b/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb
@@ -3,9 +3,14 @@ require 'active_support/core_ext/class/inheritable_attributes'
class ClassInheritableAttributesTest < Test::Unit::TestCase
def setup
+ ActiveSupport::Deprecation.silenced = true
@klass = Class.new
end
+ def teardown
+ ActiveSupport::Deprecation.silenced = false
+ end
+
def test_reader_declaration
assert_nothing_raised do
@klass.class_inheritable_reader :a
@@ -21,7 +26,7 @@ class ClassInheritableAttributesTest < Test::Unit::TestCase
assert_respond_to @klass.new, :a=
end
end
-
+
def test_writer_declaration_without_instance_writer
assert_nothing_raised do
@klass.class_inheritable_writer :a, :instance_writer => false
@@ -39,7 +44,7 @@ class ClassInheritableAttributesTest < Test::Unit::TestCase
assert_respond_to @klass.new, :a=
end
end
-
+
def test_accessor_declaration_without_instance_writer
assert_nothing_raised do
@klass.class_inheritable_accessor :a, :instance_writer => false
@@ -176,37 +181,37 @@ class ClassInheritableAttributesTest < Test::Unit::TestCase
assert_equal 'b', @klass.b
assert_equal 'B', @sub.b
end
-
+
def test_array_inheritance
@klass.class_inheritable_accessor :a
@klass.a = []
@sub = eval("class SubbyArray < @klass; end; SubbyArray")
-
+
assert_equal [], @klass.a
assert_equal [], @sub.a
-
+
@sub.a << :first
-
+
assert_equal [:first], @sub.a
assert_equal [], @klass.a
end
-
+
def test_array_inheritance_
@klass.class_inheritable_accessor :a
@klass.a = {}
@sub = eval("class SubbyHash < @klass; end; SubbyHash")
-
+
assert_equal Hash.new, @klass.a
assert_equal Hash.new, @sub.a
-
+
@sub.a[:first] = :first
-
+
assert_equal 1, @sub.a.keys.size
assert_equal 0, @klass.a.keys.size
end
-
+
def test_reset_inheritable_attributes
@klass.class_inheritable_accessor :a
@klass.a = 'a'
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index 59c168d33d..d81693209f 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -26,7 +26,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal year, Date.new(year).to_time(format).year
end
end
- end
+ end
end
def test_to_datetime
@@ -110,6 +110,14 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(2005,1,1).to_s, Date.new(2005,2,22).beginning_of_year.to_s
end
+ def test_weeks_ago
+ assert_equal Date.new(2005,5,10), Date.new(2005,5,17).weeks_ago(1)
+ assert_equal Date.new(2005,5,10), Date.new(2005,5,24).weeks_ago(2)
+ assert_equal Date.new(2005,5,10), Date.new(2005,5,31).weeks_ago(3)
+ assert_equal Date.new(2005,5,10), Date.new(2005,6,7).weeks_ago(4)
+ assert_equal Date.new(2006,12,31), Date.new(2007,2,4).weeks_ago(5)
+ end
+
def test_months_ago
assert_equal Date.new(2005,5,5), Date.new(2005,6,5).months_ago(1)
assert_equal Date.new(2004,11,5), Date.new(2005,6,5).months_ago(7)
@@ -219,6 +227,14 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
+ def test_prev_week
+ assert_equal Date.new(2005,5,9), Date.new(2005,5,17).prev_week
+ assert_equal Date.new(2006,12,25), Date.new(2007,1,7).prev_week
+ assert_equal Date.new(2010,2,12), Date.new(2010,2,19).prev_week(:friday)
+ assert_equal Date.new(2010,2,13), Date.new(2010,2,19).prev_week(:saturday)
+ assert_equal Date.new(2010,2,27), Date.new(2010,3,4).prev_week(:saturday)
+ end
+
def test_next_week
assert_equal Date.new(2005,2,28), Date.new(2005,2,22).next_week
assert_equal Date.new(2005,3,4), Date.new(2005,2,22).next_week(:friday)
@@ -242,17 +258,16 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
def test_yesterday_constructor
assert_equal Date.current - 1, Date.yesterday
end
-
- def test_yesterday_constructor_when_zone_default_is_not_set
+
+ def test_yesterday_constructor_when_zone_is_not_set
with_env_tz 'UTC' do
with_tz_default do
- Time.stubs(:now).returns Time.local(2000, 1, 1)
- assert_equal Date.new(1999, 12, 31), Date.yesterday
+ assert_equal(Date.today - 1, Date.yesterday)
end
end
end
- def test_yesterday_constructor_when_zone_default_is_set
+ def test_yesterday_constructor_when_zone_is_set
with_env_tz 'UTC' do
with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
Time.stubs(:now).returns Time.local(2000, 1, 1)
@@ -265,16 +280,15 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.current + 1, Date.tomorrow
end
- def test_tomorrow_constructor_when_zone_default_is_not_set
+ def test_tomorrow_constructor_when_zone_is_not_set
with_env_tz 'UTC' do
with_tz_default do
- Time.stubs(:now).returns Time.local(1999, 12, 31)
- assert_equal Date.new(2000, 1, 1), Date.tomorrow
+ assert_equal(Date.today + 1, Date.tomorrow)
end
end
end
- def test_tomorrow_constructor_when_zone_default_is_set
+ def test_tomorrow_constructor_when_zone_is_set
with_env_tz 'UTC' do
with_tz_default ActiveSupport::TimeZone['Europe/Paris'] do # UTC +1
Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
@@ -286,8 +300,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
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_default_is_set
+
+ def test_since_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -300,8 +314,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
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_default_is_set
+
+ def test_ago_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -314,8 +328,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
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_default_is_set
+
+ def test_beginning_of_day_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -328,8 +342,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
def test_end_of_day
assert_equal Time.local(2005,2,21,23,59,59,999999.999), Date.new(2005,2,21).end_of_day
end
-
- def test_end_of_day_when_zone_default_is_set
+
+ def test_end_of_day_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -338,7 +352,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
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)
@@ -350,8 +364,8 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
end
-
- def test_xmlschema_when_zone_default_is_set
+
+ def test_xmlschema_when_zone_is_set
with_env_tz 'UTC' do
with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema)
@@ -360,6 +374,16 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
+ if RUBY_VERSION < '1.9'
+ def test_rfc3339
+ assert_equal('1980-02-28', Date.new(1980, 2, 28).rfc3339)
+ end
+
+ def test_iso8601
+ assert_equal('1980-02-28', Date.new(1980, 2, 28).iso8601)
+ end
+ end
+
def test_today
Date.stubs(:current).returns(Date.new(2000, 1, 1))
assert_equal false, Date.new(1999, 12, 31).today?
@@ -381,23 +405,20 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal true, Date.new(2000,1,2).future?
end
- def test_current_returns_date_today_when_zone_default_not_set
+ def test_current_returns_date_today_when_zone_not_set
with_env_tz 'US/Central' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
- assert_equal Date.new(1999, 12, 31), Date.today
- assert_equal Date.new(1999, 12, 31), Date.current
+ assert_equal Date.today, Date.current
end
end
- def test_current_returns_time_zone_today_when_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_current_returns_time_zone_today_when_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Central' do
- Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
- assert_equal Date.new(1999, 12, 31), Date.today
- assert_equal Date.new(2000, 1, 1), Date.current
+ assert_equal ::Time.zone.today, Date.current
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_date_advance_should_not_change_passed_options_hash
@@ -415,11 +436,11 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def with_tz_default(tz = nil)
- old_tz = Time.zone_default
- Time.zone_default = tz
+ old_tz = Time.zone
+ Time.zone = tz
yield
ensure
- Time.zone_default = old_tz
+ Time.zone = old_tz
end
end
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index e8506f5222..456736cbad 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -38,6 +38,8 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 0, 0).to_time
# DateTimes with offsets other than 0 are returned unaltered
assert_equal DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)), DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).to_time
+ # Fractional seconds are preserved
+ assert_equal Time.utc(2005, 2, 21, 10, 11, 12, 256), DateTime.new(2005, 2, 21, 10, 11, 12 + Rational(256, 1000000), 0).to_time
end
def test_civil_from_format
@@ -92,6 +94,14 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal DateTime.civil(2005,1,1,0,0,0), DateTime.civil(2005,2,22,10,10,10).beginning_of_year
end
+ def test_weeks_ago
+ assert_equal DateTime.civil(2005,5,29,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(1)
+ assert_equal DateTime.civil(2005,5,1,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(5)
+ assert_equal DateTime.civil(2005,4,24,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(6)
+ assert_equal DateTime.civil(2005,2,27,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(14)
+ assert_equal DateTime.civil(2004,12,25,10), DateTime.civil(2005,1,1,10,0,0).weeks_ago(1)
+ end
+
def test_months_ago
assert_equal DateTime.civil(2005,5,5,10), DateTime.civil(2005,6,5,10,0,0).months_ago(1)
assert_equal DateTime.civil(2004,11,5,10), DateTime.civil(2005,6,5,10,0,0).months_ago(7)
@@ -196,6 +206,14 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 22, 58, 59).advance(:months => 1, :hours => 1, :minutes => 1, :seconds => 1)
end
+ def test_prev_week
+ assert_equal DateTime.civil(2005,2,21), DateTime.civil(2005,3,1,15,15,10).prev_week
+ assert_equal DateTime.civil(2005,2,22), DateTime.civil(2005,3,1,15,15,10).prev_week(:tuesday)
+ assert_equal DateTime.civil(2005,2,25), DateTime.civil(2005,3,1,15,15,10).prev_week(:friday)
+ assert_equal DateTime.civil(2006,10,30), DateTime.civil(2006,11,6,0,0,0).prev_week
+ assert_equal DateTime.civil(2006,11,15), DateTime.civil(2006,11,23,0,0,0).prev_week(:wednesday)
+ end
+
def test_next_week
assert_equal DateTime.civil(2005,2,28), DateTime.civil(2005,2,22,15,15,10).next_week
assert_equal DateTime.civil(2005,3,4), DateTime.civil(2005,2,22,15,15,10).next_week(:friday)
@@ -242,7 +260,7 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
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?
@@ -264,21 +282,21 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal true, DateTime.civil(2005,2,10,20,30,46).future?
end
- def test_current_returns_date_today_when_zone_default_not_set
+ def test_current_returns_date_today_when_zone_is_not_set
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
end
- def test_current_returns_time_zone_today_when_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_current_returns_time_zone_today_when_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_current_without_time_zone
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index 710c221fac..c0b529d9f8 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'active_support/time'
+require 'active_support/json'
class DurationTest < ActiveSupport::TestCase
def test_is_a
@@ -53,8 +54,8 @@ class DurationTest < ActiveSupport::TestCase
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
- flunk("ArgumentError should be raised, but we got #{$!.class} instead")
+ rescue Exception => e
+ flunk("ArgumentError should be raised, but we got #{e.class} instead")
end
end
@@ -88,8 +89,8 @@ class DurationTest < ActiveSupport::TestCase
assert_in_delta((7 * 24 * 1.7).hours.ago(t), 1.7.weeks.ago(t), 1)
end
- def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
- Time.zone_default = nil
+ def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set
+ Time.zone = nil
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
@@ -101,8 +102,8 @@ class DurationTest < ActiveSupport::TestCase
end
end
- def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
@@ -115,20 +116,32 @@ class DurationTest < ActiveSupport::TestCase
assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
-
+
def test_adding_hours_across_dst_boundary
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')
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index 4650b796b6..4655bfe519 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -89,7 +89,7 @@ class EnumerableTests < Test::Unit::TestCase
assert ![ 1, 2 ].many? {|x| x > 1 }
assert [ 1, 2, 2 ].many? {|x| x > 1 }
end
-
+
def test_exclude?
assert [ 1 ].exclude?(2)
assert ![ 1 ].exclude?(1)
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 5d9846a216..a0479d45ac 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -4,8 +4,18 @@ require 'bigdecimal'
require 'active_support/core_ext/string/access'
require 'active_support/ordered_hash'
require 'active_support/core_ext/object/conversions'
+require 'active_support/inflections'
class HashExtTest < Test::Unit::TestCase
+ class IndifferentHash < HashWithIndifferentAccess
+ end
+
+ class SubclassingArray < Array
+ end
+
+ class SubclassingHash < Hash
+ end
+
def setup
@strings = { 'a' => 1, 'b' => 2 }
@symbols = { :a => 1, :b => 2 }
@@ -99,6 +109,11 @@ class HashExtTest < Test::Unit::TestCase
assert_equal @strings, @mixed.with_indifferent_access.dup.stringify_keys!
end
+ def test_hash_subclass
+ flash = { "foo" => SubclassingHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
+ assert_kind_of SubclassingHash, flash["foo"]
+ end
+
def test_indifferent_assorted
@strings = @strings.with_indifferent_access
@symbols = @symbols.with_indifferent_access
@@ -248,6 +263,20 @@ class HashExtTest < Test::Unit::TestCase
hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
assert_equal "1", hash[:urls][:url].first[:address]
end
+
+ def test_should_preserve_array_subclass_when_value_is_array
+ array = SubclassingArray.new
+ array << { "address" => "1" }
+ hash = { "urls" => { "url" => array }}.with_indifferent_access
+ assert_equal SubclassingArray, hash[:urls][:url].class
+ end
+
+ def test_should_preserve_array_class_when_hash_value_is_frozen_array
+ array = SubclassingArray.new
+ array << { "address" => "1" }
+ 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
@@ -267,7 +296,6 @@ class HashExtTest < Test::Unit::TestCase
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"}}
@@ -276,13 +304,24 @@ class HashExtTest < Test::Unit::TestCase
['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(s): failore") do
+ 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
@@ -316,6 +355,31 @@ class HashExtTest < Test::Unit::TestCase
assert_equal expected, hash_1
end
+ def test_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_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_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_reverse_merge
defaults = { :a => "x", :b => "y", :c => 10 }.freeze
options = { :a => 1, :b => 2 }
@@ -462,20 +526,24 @@ class HashExtToParamTests < Test::Unit::TestCase
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', ActiveSupport::OrderedHash[:hello, "world", "say_bye", true].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', ActiveSupport::OrderedHash[10, 20, 30, 40, 50, 60].to_param
+ assert_equal '10=20&30=40&50=60', {10 => 20, 30 => 40, 50 => 60}.to_param
end
def test_to_param_hash
- assert_equal 'custom=param-1&custom2=param2-1', ActiveSupport::OrderedHash[ToParam.new('custom'), ToParam.new('param'), ToParam.new('custom2'), ToParam.new('param2')].to_param
+ assert_equal 'custom2=param2-1&custom=param-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', ActiveSupport::OrderedHash[*%w(b 1 c 0 a 2)].to_param
+ end
end
class HashToXmlTest < Test::Unit::TestCase
@@ -511,6 +579,13 @@ class HashToXmlTest < Test::Unit::TestCase
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)
@@ -640,12 +715,12 @@ class HashToXmlTest < Test::Unit::TestCase
EOT
expected_topic_hash = {
- :title => nil,
+ :title => nil,
:id => nil,
:approved => nil,
:written_on => nil,
:viewed_at => nil,
- :content => nil,
+ :content => nil,
:parent_id => nil
}.stringify_keys
@@ -723,7 +798,7 @@ class HashToXmlTest < Test::Unit::TestCase
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>
@@ -839,13 +914,13 @@ class HashToXmlTest < Test::Unit::TestCase
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
@@ -854,7 +929,7 @@ class HashToXmlTest < Test::Unit::TestCase
:image => {'type' => 'ProductImage', 'filename' => 'image.gif' },
}.stringify_keys
- assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
+ assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
end
def test_should_use_default_value_for_unknown_key
@@ -888,41 +963,41 @@ class HashToXmlTest < Test::Unit::TestCase
assert_equal expected, hash.to_xml(@xml_options)
end
end
-
- def test_empty_string_works_for_typecast_xml_value
+
+ def test_empty_string_works_for_typecast_xml_value
assert_nothing_raised do
Hash.__send__(:typecast_xml_value, "")
end
end
-
+
def test_escaping_to_xml
- hash = {
- :bare_string => 'First & Last Name',
+ hash = {
+ :bare_string => 'First & Last Name',
:pre_escaped_string => 'First &amp; Last Name'
}.stringify_keys
-
+
expected_xml = '<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>'
assert_equal expected_xml, hash.to_xml(@xml_options)
end
-
+
def test_unescaping_from_xml
xml_string = '<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>'
- expected_hash = {
- :bare_string => 'First & Last Name',
+ expected_hash = {
+ :bare_string => 'First & Last Name',
:pre_escaped_string => 'First &amp; 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',
+ hash = {
+ :bare_string => 'First & Last Name',
:pre_escaped_string => 'First &amp; Last Name'
}.stringify_keys
assert_equal hash, Hash.from_xml(hash.to_xml(@xml_options))['person']
end
-
+
def test_datetime_xml_type_with_utc_time
alert_xml = <<-XML
<alert>
@@ -933,7 +1008,7 @@ class HashToXmlTest < Test::Unit::TestCase
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>
@@ -944,7 +1019,7 @@ class HashToXmlTest < Test::Unit::TestCase
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>
diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb
index c22af89918..ede9b0a6aa 100644
--- a/activesupport/test/core_ext/kernel_test.rb
+++ b/activesupport/test/core_ext/kernel_test.rb
@@ -46,22 +46,27 @@ class KernelTest < Test::Unit::TestCase
o = Object.new
assert_equal class << o; self end, o.singleton_class
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'}
+ end
end
-class KernelSupressTest < Test::Unit::TestCase
+class KernelSuppressTest < Test::Unit::TestCase
def test_reraise
assert_raise(LoadError) do
suppress(ArgumentError) { raise LoadError }
end
end
- def test_supression
+ def test_suppression
suppress(ArgumentError) { raise ArgumentError }
suppress(LoadError) { raise LoadError }
suppress(LoadError, ArgumentError) { raise LoadError }
diff --git a/activesupport/test/core_ext/module/anonymous_test.rb b/activesupport/test/core_ext/module/anonymous_test.rb
index 7a78a3b012..cb556af772 100644
--- a/activesupport/test/core_ext/module/anonymous_test.rb
+++ b/activesupport/test/core_ext/module/anonymous_test.rb
@@ -6,7 +6,7 @@ class AnonymousTest < ActiveSupport::TestCase
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?
diff --git a/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb b/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb
index 7c0d0bb242..b9b60c4d6d 100644
--- a/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb
+++ b/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb
@@ -7,25 +7,25 @@ class AttrAccessorWithDefaultTest < Test::Unit::TestCase
def helper
'helper'
end
- end
+ end
@instance = @target.new
end
-
+
def test_default_arg
@target.attr_accessor_with_default :foo, :bar
assert_equal(:bar, @instance.foo)
@instance.foo = nil
assert_nil(@instance.foo)
end
-
+
def test_default_proc
@target.attr_accessor_with_default(:foo) {helper.upcase}
assert_equal('HELPER', @instance.foo)
@instance.foo = nil
assert_nil(@instance.foo)
end
-
+
def test_invalid_args
- assert_raise(RuntimeError) {@target.attr_accessor_with_default :foo}
+ assert_raise(ArgumentError) {@target.attr_accessor_with_default :foo}
end
end
diff --git a/activesupport/test/core_ext/module/attribute_accessor_test.rb b/activesupport/test/core_ext/module/attribute_accessor_test.rb
index 67fcd437d0..118fb070a0 100644
--- a/activesupport/test/core_ext/module/attribute_accessor_test.rb
+++ b/activesupport/test/core_ext/module/attribute_accessor_test.rb
@@ -32,7 +32,7 @@ class ModuleAttributeAccessorTest < Test::Unit::TestCase
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)
diff --git a/activesupport/test/core_ext/module/attribute_aliasing_test.rb b/activesupport/test/core_ext/module/attribute_aliasing_test.rb
index f17d031662..065c3531e0 100644
--- a/activesupport/test/core_ext/module/attribute_aliasing_test.rb
+++ b/activesupport/test/core_ext/module/attribute_aliasing_test.rb
@@ -44,14 +44,14 @@ class AttributeAliasingTest < Test::Unit::TestCase
# 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?
diff --git a/activesupport/test/core_ext/module/reachable_test.rb b/activesupport/test/core_ext/module/reachable_test.rb
index 72892b77d5..80eb31a5c4 100644
--- a/activesupport/test/core_ext/module/reachable_test.rb
+++ b/activesupport/test/core_ext/module/reachable_test.rb
@@ -6,33 +6,33 @@ class AnonymousTest < ActiveSupport::TestCase
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)
+ self.class.send(:remove_const, :M)
eval "class C; end"
eval "module M; end"
-
+
assert C.reachable?
assert M.reachable?
assert !c.reachable?
diff --git a/activesupport/test/core_ext/module/synchronization_test.rb b/activesupport/test/core_ext/module/synchronization_test.rb
index eb850893f0..6c407e2260 100644
--- a/activesupport/test/core_ext/module/synchronization_test.rb
+++ b/activesupport/test/core_ext/module/synchronization_test.rb
@@ -1,3 +1,4 @@
+require 'thread'
require 'abstract_unit'
require 'active_support/core_ext/class/attribute_accessors'
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index 5d9cdf22c2..a95cf1591f 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -26,14 +26,10 @@ module Yz
end
end
-class De
-end
-
Somewhere = Struct.new(:street, :city)
Someone = Struct.new(:name, :place) do
delegate :street, :city, :to_f, :to => :place
- delegate :state, :to => :@place
delegate :upcase, :to => "place.city"
end
@@ -47,6 +43,14 @@ Project = Struct.new(:description, :person) do
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 Name
delegate :upcase, :to => :@full_name
@@ -97,6 +101,11 @@ class ModuleTest < Test::Unit::TestCase
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
diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb
index 992ec60302..3a2452b4b0 100644
--- a/activesupport/test/core_ext/numeric_ext_test.rb
+++ b/activesupport/test/core_ext/numeric_ext_test.rb
@@ -38,7 +38,7 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase
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)
@@ -49,16 +49,16 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal @dtnow.advance(:months => -1), 1.month.until(@dtnow)
assert_equal @dtnow.advance(:years => 20), 20.years.since(@dtnow)
end
-
+
def test_duration_addition
assert_equal @now.advance(:days => 1).advance(:months => 1), (1.day + 1.month).since(@now)
assert_equal @now.advance(:days => 7), (1.week + 5.seconds - 5.seconds).since(@now)
assert_equal @now.advance(:years => 2), (4.years - 2.years).since(@now)
assert_equal @dtnow.advance(:days => 1).advance(:months => 1), (1.day + 1.month).since(@dtnow)
assert_equal @dtnow.advance(:days => 7), (1.week + 5.seconds - 5.seconds).since(@dtnow)
- assert_equal @dtnow.advance(:years => 2), (4.years - 2.years).since(@dtnow)
+ assert_equal @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
@@ -69,25 +69,63 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal @dtnow.advance(:days => 15), @dtnow + 15.days
assert_equal @dtnow.advance(:months => 1), @dtnow + 1.month
end
-
+
def test_chaining_duration_operations
assert_equal @now.advance(:days => 2).advance(:months => -3), @now + 2.days - 3.months
assert_equal @now.advance(:days => 1).advance(:months => 2), @now + 1.day + 2.months
assert_equal @dtnow.advance(:days => 2).advance(:months => -3), @dtnow + 2.days - 3.months
- assert_equal @dtnow.advance(:days => 1).advance(:months => 2), @dtnow + 1.day + 2.months
+ assert_equal @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)
+ 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 < Test::Unit::TestCase
@@ -102,12 +140,12 @@ class NumericExtDateTest < Test::Unit::TestCase
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
@@ -132,7 +170,7 @@ class NumericExtSizeTest < Test::Unit::TestCase
assert_equal right, left
end
end
-
+
def test_units_as_bytes_independently
assert_equal 3145728, 3.megabytes
assert_equal 3145728, 3.megabyte
diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb
index e28b4cd493..84da52f4bf 100644
--- a/activesupport/test/core_ext/object/to_query_test.rb
+++ b/activesupport/test/core_ext/object/to_query_test.rb
@@ -18,22 +18,22 @@ class ToQueryTest < Test::Unit::TestCase
end
def test_nested_conversion
- assert_query_equal 'person[login]=seckar&person[name]=Nicholas',
+ assert_query_equal 'person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas',
:person => ActiveSupport::OrderedHash[:login, 'seckar', :name, 'Nicholas']
end
def test_multiple_nested
- assert_query_equal 'account[person][id]=20&person[id]=10',
+ assert_query_equal 'account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10',
ActiveSupport::OrderedHash[:account, {:person => {:id => 20}}, :person, {:id => 10}]
end
def test_array_values
- assert_query_equal 'person[id][]=10&person[id][]=20',
+ assert_query_equal 'person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20',
:person => {:id => [10, 20]}
end
def test_array_values_are_not_sorted
- assert_query_equal 'person[id][]=20&person[id][]=10',
+ assert_query_equal 'person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10',
:person => {:id => [20, 10]}
end
diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb
index 6588f2e345..5d68b198f2 100644
--- a/activesupport/test/core_ext/object_and_class_ext_test.rb
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -28,18 +28,6 @@ module Nested
end
end
-module Bar
- def bar; end
-end
-
-module Baz
- def baz; end
-end
-
-class Foo
- include Bar
-end
-
class ObjectTests < ActiveSupport::TestCase
class DuckTime
def acts_like_time?
@@ -82,37 +70,6 @@ class ObjectInstanceVariableTest < Test::Unit::TestCase
assert_equal %w(@bar @baz), @source.instance_variable_names.sort
end
- def test_copy_instance_variables_from_without_explicit_excludes
- assert_equal [], @dest.instance_variables
- @dest.copy_instance_variables_from(@source)
-
- assert_equal %w(@bar @baz), @dest.instance_variables.sort.map(&:to_s)
- %w(@bar @baz).each do |name|
- assert_equal @source.instance_variable_get(name).object_id,
- @dest.instance_variable_get(name).object_id
- end
- end
-
- def test_copy_instance_variables_from_with_explicit_excludes
- @dest.copy_instance_variables_from(@source, ['@baz'])
- assert !@dest.instance_variable_defined?('@baz')
- assert_equal 'bar', @dest.instance_variable_get('@bar')
- end
-
- def test_copy_instance_variables_automatically_excludes_protected_instance_variables
- @source.instance_variable_set(:@quux, 'quux')
- class << @source
- def protected_instance_variables
- ['@bar', :@quux]
- end
- end
-
- @dest.copy_instance_variables_from(@source)
- assert !@dest.instance_variable_defined?('@bar')
- assert !@dest.instance_variable_defined?('@quux')
- assert_equal 'baz', @dest.instance_variable_get('@baz')
- end
-
def test_instance_values
object = Object.new
object.instance_variable_set :@a, 1
@@ -144,7 +101,7 @@ class ObjectTryTest < Test::Unit::TestCase
assert !@string.respond_to?(method)
assert_raise(NoMethodError) { @string.try(method) }
end
-
+
def test_valid_method
assert_equal 5, @string.try(:size)
end
@@ -165,4 +122,14 @@ class ObjectTryTest < Test::Unit::TestCase
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
end
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
index 5701eeef28..1424fa4aca 100644
--- a/activesupport/test/core_ext/range_ext_test.rb
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -62,4 +62,16 @@ class RangeTest < Test::Unit::TestCase
(1..10).step(2) {|i| array << i }
assert_equal [1,3,5,7,9], array
end
+
+ if RUBY_VERSION < '1.9'
+ def test_cover
+ assert((1..3).cover?(2))
+ assert !(1..3).cover?(4)
+ end
+ else
+ def test_cover_is_not_override
+ range = (1..3)
+ assert range.method(:include?) != range.method(:cover?)
+ end
+ end
end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index affa1b5e18..bb865cae91 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -6,10 +6,42 @@ require 'inflector_test_cases'
require 'active_support/core_ext/string'
require 'active_support/time'
require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/string/strip'
class StringInflectionsTest < Test::Unit::TestCase
include InflectorTestCases
+ 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)
@@ -218,7 +250,7 @@ class StringInflectionsTest < Test::Unit::TestCase
# And changes the original string:
assert_equal original, expected
end
-
+
def test_truncate
assert_equal "Hello World!", "Hello World!".truncate(12)
assert_equal "Hello Wor...", "Hello World!!".truncate(12)
@@ -289,75 +321,6 @@ class CoreExtStringMultibyteTest < ActiveSupport::TestCase
end
end
-=begin
- string.rb - Interpolation for String.
-
- Copyright (C) 2005-2009 Masao Mutoh
-
- You may redistribute it and/or modify it under the same
- license terms as Ruby.
-=end
-class TestGetTextString < Test::Unit::TestCase
- def test_sprintf
- assert_equal("foo is a number", "%{msg} is a number" % {:msg => "foo"})
- assert_equal("bar is a number", "%s is a number" % ["bar"])
- assert_equal("bar is a number", "%s is a number" % "bar")
- assert_equal("1, test", "%{num}, %{record}" % {:num => 1, :record => "test"})
- assert_equal("test, 1", "%{record}, %{num}" % {:num => 1, :record => "test"})
- assert_equal("1, test", "%d, %s" % [1, "test"])
- assert_equal("test, 1", "%2$s, %1$d" % [1, "test"])
- assert_raise(ArgumentError) { "%-%" % [1] }
- end
-
- def test_percent
- assert_equal("% 1", "%% %<num>d" % {:num => 1.0})
- assert_equal("%{num} %<num>d 1", "%%{num} %%<num>d %<num>d" % {:num => 1})
- end
-
- def test_sprintf_percent_in_replacement
- assert_equal("%<not_translated>s", "%{msg}" % { :msg => '%<not_translated>s', :not_translated => 'should not happen' })
- end
-
- def test_sprintf_lack_argument
- assert_raises(KeyError) { "%{num}, %{record}" % {:record => "test"} }
- assert_raises(KeyError) { "%{record}" % {:num => 1} }
- end
-
- def test_no_placeholder
- # Causes a "too many arguments for format string" warning
- # on 1.8.7 and 1.9 but we still want to make sure the behavior works
- silence_warnings do
- assert_equal("aaa", "aaa" % {:num => 1})
- assert_equal("bbb", "bbb" % [1])
- end
- end
-
- def test_sprintf_ruby19_style
- assert_equal("1", "%<num>d" % {:num => 1})
- assert_equal("0b1", "%<num>#b" % {:num => 1})
- assert_equal("foo", "%<msg>s" % {:msg => "foo"})
- assert_equal("1.000000", "%<num>f" % {:num => 1.0})
- assert_equal(" 1", "%<num>3.0f" % {:num => 1.0})
- assert_equal("100.00", "%<num>2.2f" % {:num => 100.0})
- assert_equal("0x64", "%<num>#x" % {:num => 100.0})
- assert_raise(ArgumentError) { "%<num>,d" % {:num => 100} }
- assert_raise(ArgumentError) { "%<num>/d" % {:num => 100} }
- end
-
- def test_sprintf_old_style
- assert_equal("foo 1.000000", "%s %f" % ["foo", 1.0])
- end
-
- def test_sprintf_mix_unformatted_and_formatted_named_placeholders
- assert_equal("foo 1.000000", "%{name} %<num>f" % {:name => "foo", :num => 1.0})
- end
-
- def test_string_interpolation_raises_an_argument_error_when_mixing_named_and_unnamed_placeholders
- assert_raises(ArgumentError) { "%{name} %f" % [1.0] }
- assert_raises(ArgumentError) { "%{name} %f" % [1.0, 2.0] }
- end
-end
-
class OutputSafetyTest < ActiveSupport::TestCase
def setup
@string = "hello"
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index 1cf84df386..53d497013a 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -130,6 +130,14 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,1,1,0,0,0), Time.local(2005,2,22,10,10,10).beginning_of_year
end
+ def test_weeks_ago
+ assert_equal Time.local(2005,5,29,10), Time.local(2005,6,5,10,0,0).weeks_ago(1)
+ assert_equal Time.local(2005,5,1,10), Time.local(2005,6,5,10,0,0).weeks_ago(5)
+ assert_equal Time.local(2005,4,24,10), Time.local(2005,6,5,10,0,0).weeks_ago(6)
+ assert_equal Time.local(2005,2,27,10), Time.local(2005,6,5,10,0,0).weeks_ago(14)
+ assert_equal Time.local(2004,12,25,10), Time.local(2005,1,1,10,0,0).weeks_ago(1)
+ end
+
def test_months_ago
assert_equal Time.local(2005,5,5,10), Time.local(2005,6,5,10,0,0).months_ago(1)
assert_equal Time.local(2004,11,5,10), Time.local(2005,6,5,10,0,0).months_ago(7)
@@ -187,7 +195,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -197,7 +205,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -210,7 +218,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -220,7 +228,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -252,7 +260,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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)
@@ -268,7 +276,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -278,7 +286,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -330,7 +338,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -340,7 +348,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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'
@@ -463,6 +471,16 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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_prev_week
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2005,2,21), Time.local(2005,3,1,15,15,10).prev_week
+ assert_equal Time.local(2005,2,22), Time.local(2005,3,1,15,15,10).prev_week(:tuesday)
+ assert_equal Time.local(2005,2,25), Time.local(2005,3,1,15,15,10).prev_week(:friday)
+ assert_equal Time.local(2006,10,30), Time.local(2006,11,6,0,0,0).prev_week
+ assert_equal Time.local(2006,11,15), Time.local(2006,11,23,0,0,0).prev_week(:wednesday)
+ end
+ end
+
def test_next_week
with_env_tz 'US/Eastern' do
assert_equal Time.local(2005,2,28), Time.local(2005,2,22,15,15,10).next_week
@@ -729,7 +747,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 5ce4277672..bafa335a09 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -36,6 +36,10 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal @twz.object_id, @twz.in_time_zone(ActiveSupport::TimeZone['Eastern Time (US & Canada)']).object_id
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?
@@ -102,11 +106,11 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_to_yaml
- assert_equal "--- 1999-12-31 19:00:00 -05:00\n", @twz.to_yaml
+ assert_match(/^--- 2000-01-01 00:00:00(\.0+)?\s*Z\n/, @twz.to_yaml)
end
def test_ruby_to_yaml
- assert_equal "--- \n:twz: 2000-01-01 00:00:00 Z\n", {:twz => @twz}.to_yaml
+ assert_match(/---\s*\n:twz: 2000-01-01 00:00:00(\.0+)?\s*Z\n/, {:twz => @twz}.to_yaml)
end
def test_httpdate
@@ -287,7 +291,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
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)
@@ -328,7 +332,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_kind_of Time, @twz
assert_kind_of ActiveSupport::TimeWithZone, @twz
end
-
+
def test_class_name
assert_equal 'Time', ActiveSupport::TimeWithZone.name
end
@@ -703,7 +707,7 @@ class TimeWithZoneTest < Test::Unit::TestCase
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
-
+
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
@@ -763,6 +767,13 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
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
@@ -790,7 +801,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal nil, Time.zone
end
- def test_time_zone_getter_and_setter_with_zone_default
+ def test_time_zone_getter_and_setter_with_zone_default_set
Time.zone_default = ActiveSupport::TimeZone['Alaska']
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
Time.zone = ActiveSupport::TimeZone['Hawaii']
@@ -798,6 +809,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
Time.zone = nil
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
ensure
+ Time.zone = nil
Time.zone_default = nil
end
@@ -838,7 +850,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_nil Time.zone
end
- def test_current_returns_time_now_when_zone_default_not_set
+ def test_current_returns_time_now_when_zone_not_set
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone)
@@ -846,8 +858,8 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
end
- def test_current_returns_time_zone_now_when_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_current_returns_time_zone_now_when_zone_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
@@ -855,7 +867,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal Time.utc(2000), Time.current.time
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
protected
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index f98d823f00..ef017d7436 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -477,15 +477,15 @@ class DependenciesTest < Test::Unit::TestCase
def test_references_should_work
with_loading 'dependencies' do
- c = ActiveSupport::Dependencies.ref("ServiceOne")
+ c = ActiveSupport::Dependencies.reference("ServiceOne")
service_one_first = ServiceOne
- assert_equal service_one_first, c.get
+ assert_equal service_one_first, c.get("ServiceOne")
ActiveSupport::Dependencies.clear
assert ! defined?(ServiceOne)
service_one_second = ServiceOne
- assert_not_equal service_one_first, c.get
- assert_equal service_one_second, c.get
+ assert_not_equal service_one_first, c.get("ServiceOne")
+ assert_equal service_one_second, c.get("ServiceOne")
end
end
@@ -574,16 +574,27 @@ class DependenciesTest < Test::Unit::TestCase
end
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.empty?
+ 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.empty?
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
ensure
Object.class_eval { remove_const :Hello }
end
@@ -600,7 +611,7 @@ class DependenciesTest < Test::Unit::TestCase
end
assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s)
- assert ActiveSupport::Dependencies.constant_watch_stack.empty?
+ 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) }
@@ -621,7 +632,7 @@ class DependenciesTest < Test::Unit::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
- assert ActiveSupport::Dependencies.constant_watch_stack.empty?
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
ensure
Object.class_eval { remove_const :M }
end
@@ -639,7 +650,7 @@ class DependenciesTest < Test::Unit::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
- assert ActiveSupport::Dependencies.constant_watch_stack.empty?
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
ensure
Object.class_eval { remove_const :M }
end
diff --git a/activesupport/test/file_watcher_test.rb b/activesupport/test/file_watcher_test.rb
new file mode 100644
index 0000000000..7b4d4be24f
--- /dev/null
+++ b/activesupport/test/file_watcher_test.rb
@@ -0,0 +1,233 @@
+require 'abstract_unit'
+require 'fssm'
+require "fileutils"
+require "timeout"
+
+
+class FileWatcherTest < ActiveSupport::TestCase
+ class DumbBackend < ActiveSupport::FileWatcher::Backend
+ end
+
+ def setup
+ @watcher = ActiveSupport::FileWatcher.new
+
+ # In real life, the backend would take the path and use it to observe the file
+ # system. In our case, we will manually trigger the events for unit testing,
+ # so we can pass any path.
+ @backend = DumbBackend.new("RAILS_WOOT", @watcher)
+
+ @payload = []
+ @watcher.watch %r{^app/assets/.*\.scss$} do |pay|
+ pay.each do |status, files|
+ files.sort!
+ end
+ @payload << pay
+ end
+ end
+
+ def test_use_triple_equals
+ fw = ActiveSupport::FileWatcher.new
+ called = []
+ fw.watch("some_arbitrary_file.rb") do |file|
+ called << "omg"
+ end
+ fw.trigger(%w{ some_arbitrary_file.rb })
+ assert_equal ['omg'], called
+ end
+
+ def test_one_change
+ @backend.trigger("app/assets/main.scss" => :changed)
+ assert_equal({:changed => ["app/assets/main.scss"]}, @payload.first)
+ end
+
+ def test_multiple_changes
+ @backend.trigger("app/assets/main.scss" => :changed, "app/assets/javascripts/foo.coffee" => :changed)
+ assert_equal([{:changed => ["app/assets/main.scss"]}], @payload)
+ end
+
+ def test_multiple_changes_match
+ @backend.trigger("app/assets/main.scss" => :changed, "app/assets/print.scss" => :changed, "app/assets/javascripts/foo.coffee" => :changed)
+ assert_equal([{:changed => ["app/assets/main.scss", "app/assets/print.scss"]}], @payload)
+ end
+
+ def test_multiple_state_changes
+ @backend.trigger("app/assets/main.scss" => :created, "app/assets/print.scss" => :changed)
+ assert_equal([{:changed => ["app/assets/print.scss"], :created => ["app/assets/main.scss"]}], @payload)
+ end
+
+ def test_more_blocks
+ payload = []
+ @watcher.watch %r{^config/routes\.rb$} do |pay|
+ payload << pay
+ end
+
+ @backend.trigger "config/routes.rb" => :changed
+ assert_equal [:changed => ["config/routes.rb"]], payload
+ assert_equal [], @payload
+ end
+
+ def test_overlapping_watchers
+ payload = []
+ @watcher.watch %r{^app/assets/main\.scss$} do |pay|
+ payload << pay
+ end
+
+ @backend.trigger "app/assets/print.scss" => :changed, "app/assets/main.scss" => :changed
+ assert_equal [:changed => ["app/assets/main.scss"]], payload
+ assert_equal [:changed => ["app/assets/main.scss", "app/assets/print.scss"]], @payload
+ end
+end
+
+module FSSM::Backends
+ class Polling
+ def initialize_with_low_latency(options={})
+ initialize_without_low_latency(options.merge(:latency => 0.1))
+ end
+ alias_method_chain :initialize, :low_latency
+ end
+end
+
+class FSSMFileWatcherTest < ActiveSupport::TestCase
+ class FSSMBackend < ActiveSupport::FileWatcher::Backend
+ def initialize(path, watcher)
+ super
+
+ monitor = FSSM::Monitor.new
+ monitor.path(path, '**/*') do |p|
+ p.update { |base, relative| trigger relative => :changed }
+ p.delete { |base, relative| trigger relative => :deleted }
+ p.create { |base, relative| trigger relative => :created }
+ end
+
+ @thread = Thread.new do
+ monitor.run
+ end
+ end
+
+ def stop
+ @thread.kill
+ end
+ end
+
+ def setup
+ Thread.abort_on_exception = true
+
+ @payload = []
+ @triggered = false
+
+ @watcher = ActiveSupport::FileWatcher.new
+
+ @path = path = File.expand_path("../tmp", __FILE__)
+ FileUtils.rm_rf path
+
+ create "app/assets/main.scss", true
+ create "app/assets/javascripts/foo.coffee", true
+ create "app/assets/print.scss", true
+ create "app/assets/videos.scss", true
+
+ @backend = FSSMBackend.new(path, @watcher)
+
+ @watcher.watch %r{^app/assets/.*\.scss$} do |pay|
+ pay.each do |status, files|
+ files.sort!
+ end
+ @payload << pay
+ trigger
+ end
+ end
+
+ def teardown
+ @backend.stop
+ Thread.abort_on_exception = false
+ end
+
+ def create(path, past = false)
+ wait(past) do
+ path = File.join(@path, path)
+ FileUtils.mkdir_p(File.dirname(path))
+
+ FileUtils.touch(path)
+ File.utime(Time.now - 100, Time.now - 100, path) if past
+ end
+ end
+
+ def change(path)
+ wait do
+ FileUtils.touch(File.join(@path, path))
+ end
+ end
+
+ def delete(path)
+ wait do
+ FileUtils.rm(File.join(@path, path))
+ end
+ end
+
+ def wait(past = false)
+ yield
+ return if past
+
+ begin
+ Timeout.timeout(1) do
+ sleep 0.05 until @triggered
+ end
+ rescue Timeout::Error
+ end
+
+ @triggered = false
+ end
+
+ def trigger
+ @triggered = true
+ end
+
+ def test_one_change
+ change "app/assets/main.scss"
+ assert_equal({:changed => ["app/assets/main.scss"]}, @payload.first)
+ end
+
+ def test_multiple_changes
+ change "app/assets/main.scss"
+ change "app/assets/javascripts/foo.coffee"
+ assert_equal([{:changed => ["app/assets/main.scss"]}], @payload)
+ end
+
+ def test_multiple_changes_match
+ change "app/assets/main.scss"
+ change "app/assets/print.scss"
+ change "app/assets/javascripts/foo.coffee"
+ assert_equal([{:changed => ["app/assets/main.scss"]}, {:changed => ["app/assets/print.scss"]}], @payload)
+ end
+
+ def test_multiple_state_changes
+ create "app/assets/new.scss"
+ change "app/assets/print.scss"
+ delete "app/assets/videos.scss"
+ assert_equal([{:created => ["app/assets/new.scss"]}, {:changed => ["app/assets/print.scss"]}, {:deleted => ["app/assets/videos.scss"]}], @payload)
+ end
+
+ def test_more_blocks
+ payload = []
+ @watcher.watch %r{^config/routes\.rb$} do |pay|
+ payload << pay
+ trigger
+ end
+
+ create "config/routes.rb"
+ assert_equal [{:created => ["config/routes.rb"]}], payload
+ assert_equal [], @payload
+ end
+
+ def test_overlapping_watchers
+ payload = []
+ @watcher.watch %r{^app/assets/main\.scss$} do |pay|
+ payload << pay
+ trigger
+ end
+
+ change "app/assets/main.scss"
+ change "app/assets/print.scss"
+ assert_equal [{:changed => ["app/assets/main.scss"]}], payload
+ assert_equal [{:changed => ["app/assets/main.scss"]}, {:changed => ["app/assets/print.scss"]}], @payload
+ end
+end
diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb
index 2a24c0bd0d..f564e63f29 100644
--- a/activesupport/test/gzip_test.rb
+++ b/activesupport/test/gzip_test.rb
@@ -1,7 +1,18 @@
require 'abstract_unit'
+require 'active_support/core_ext/object/blank'
class GzipTest < Test::Unit::TestCase
def test_compress_should_decompress_to_the_same_value
assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World"))
end
-end \ No newline at end of file
+
+ def test_compress_should_return_a_binary_string
+ compressed = ActiveSupport::Gzip.compress('')
+
+ if "".encoding_aware?
+ assert_equal Encoding.find('binary'), compressed.encoding
+ end
+
+ assert !compressed.blank?, "a compressed blank string should not be blank"
+ end
+end
diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb
index dfcd4f822d..34825c9b8f 100644
--- a/activesupport/test/i18n_test.rb
+++ b/activesupport/test/i18n_test.rb
@@ -7,68 +7,68 @@ class I18nTest < Test::Unit::TestCase
@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
+
+ 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 [: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
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index 2990177bed..1670d9ee7d 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -22,20 +22,55 @@ class InflectorTest < Test::Unit::TestCase
assert_equal "", ActiveSupport::Inflector.pluralize("")
end
+ ActiveSupport::Inflector.inflections.uncountable.each do |word|
+ define_method "test_uncountability_of_#{word}" do
+ assert_equal word, ActiveSupport::Inflector.singularize(word)
+ assert_equal word, ActiveSupport::Inflector.pluralize(word)
+ assert_equal ActiveSupport::Inflector.pluralize(word), ActiveSupport::Inflector.singularize(word)
+ end
+ end
+
+ def test_uncountable_word_is_not_greedy
+ uncountable_word = "ors"
+ countable_word = "sponsor"
+
+ cached_uncountables = ActiveSupport::Inflector.inflections.uncountables
+
+ ActiveSupport::Inflector.inflections.uncountable << uncountable_word
+
+ assert_equal uncountable_word, ActiveSupport::Inflector.singularize(uncountable_word)
+ assert_equal uncountable_word, ActiveSupport::Inflector.pluralize(uncountable_word)
+ assert_equal ActiveSupport::Inflector.pluralize(uncountable_word), ActiveSupport::Inflector.singularize(uncountable_word)
+
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(countable_word)
+ assert_equal "sponsors", ActiveSupport::Inflector.pluralize(countable_word)
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.pluralize(countable_word))
+
+ ensure
+ ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_uncountables
+ end
+
SingularToPlural.each do |singular, plural|
- define_method "test_pluralize_#{singular}" do
+ define_method "test_pluralize_singular_#{singular}" do
assert_equal(plural, ActiveSupport::Inflector.pluralize(singular))
assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(singular.capitalize))
end
end
SingularToPlural.each do |singular, plural|
- define_method "test_singularize_#{plural}" do
+ define_method "test_singularize_plural_#{plural}" do
assert_equal(singular, ActiveSupport::Inflector.singularize(plural))
assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(plural.capitalize))
end
end
+ SingularToPlural.each do |singular, plural|
+ define_method "test_pluralize_plural_#{plural}" do
+ assert_equal(plural, ActiveSupport::Inflector.pluralize(plural))
+ assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(plural.capitalize))
+ end
+ end
+
def test_overwrite_previous_inflectors
assert_equal("series", ActiveSupport::Inflector.singularize("series"))
ActiveSupport::Inflector.inflections.singular "series", "serie"
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
index 59515dad32..2b144e5931 100644
--- a/activesupport/test/inflector_test_cases.rb
+++ b/activesupport/test/inflector_test_cases.rb
@@ -44,6 +44,7 @@ module InflectorTestCases
"datum" => "data",
"medium" => "media",
+ "stadium" => "stadia",
"analysis" => "analyses",
"node_child" => "node_children",
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
index d2e3efaa6b..88cf97de7e 100644
--- a/activesupport/test/json/decoding_test.rb
+++ b/activesupport/test/json/decoding_test.rb
@@ -17,8 +17,16 @@ class TestJSONDecoding < ActiveSupport::TestCase
%({"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"},
@@ -41,7 +49,11 @@ class TestJSONDecoding < ActiveSupport::TestCase
[{'d' => Date.new(1970, 1, 1), 's' => ' escape'},{'d' => Date.new(1970, 1, 1), 's' => ' escape'}],
%q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) =>
[{'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'},
- {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}]
+ {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}],
+ # tests escaping of "\n" char with Yaml backend
+ %q({"a":"\n"}) => {"a"=>"\n"},
+ %q({"a":"\u000a"}) => {"a"=>"\n"},
+ %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"}
}
# load the default JSON backend
@@ -57,20 +69,16 @@ class TestJSONDecoding < ActiveSupport::TestCase
ActiveSupport.parse_json_times = true
silence_warnings do
ActiveSupport::JSON.with_backend backend do
- assert_nothing_raised do
- assert_equal expected, ActiveSupport::JSON.decode(json)
- end
+ assert_equal expected, ActiveSupport::JSON.decode(json)
end
end
end
end
- end
- if backends.include?("JSONGem")
- test "json decodes time json with time parsing disabled" do
+ 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 "JSONGem" do
+ ActiveSupport::JSON.with_backend backend do
assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"}))
end
end
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 1527d02d16..d5fcbf15b7 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -1,5 +1,6 @@
# encoding: utf-8
require 'abstract_unit'
+require 'active_support/core_ext/string/inflections'
require 'active_support/json'
class TestJSONEncoding < Test::Unit::TestCase
@@ -108,12 +109,24 @@ class TestJSONEncoding < Test::Unit::TestCase
end
end
- def test_exception_raised_when_encoding_circular_reference
+ 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))
@@ -152,6 +165,87 @@ class TestJSONEncoding < Test::Unit::TestCase
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_struct_encoding
+ Struct.new('UserNameAndEmail', :name, :email)
+ Struct.new('UserNameAndDate', :name, :date)
+ Struct.new('Custom', :name, :sub)
+ user_email = Struct::UserNameAndEmail.new 'David', 'sample@example.com'
+ user_birthday = Struct::UserNameAndDate.new 'David', Date.new(2010, 01, 01)
+ custom = Struct::Custom.new 'David', user_birthday
+
+
+ json_strings = ""
+ json_string_and_date = ""
+ json_custom = ""
+
+ assert_nothing_raised do
+ json_strings = user_email.to_json
+ json_string_and_date = user_birthday.to_json
+ json_custom = custom.to_json
+ end
+
+ assert_equal({"name" => "David",
+ "sub" => {
+ "name" => "David",
+ "date" => "2010/01/01" }}, JSON.parse(json_custom))
+
+ assert_equal({"name" => "David", "email" => "sample@example.com"},
+ JSON.parse(json_strings))
+
+ assert_equal({"name" => "David", "date" => "2010/01/01"},
+ JSON.parse(json_string_and_date))
+ end
+
protected
def object_keys(json_object)
diff --git a/activesupport/test/memoizable_test.rb b/activesupport/test/memoizable_test.rb
index b11fa8d346..bceac1315b 100644
--- a/activesupport/test/memoizable_test.rb
+++ b/activesupport/test/memoizable_test.rb
@@ -36,6 +36,13 @@ class MemoizableTest < ActiveSupport::TestCase
memoize :name, :age
+ protected
+
+ def memoize_protected_test
+ 'protected'
+ end
+ memoize :memoize_protected_test
+
private
def is_developer?
@@ -237,6 +244,13 @@ class MemoizableTest < ActiveSupport::TestCase
assert_raise(RuntimeError) { company.memoize :name }
end
+ def test_protected_method_memoization
+ person = Person.new
+
+ assert_raise(NoMethodError) { person.memoize_protected_test }
+ assert_equal "protected", person.send(:memoize_protected_test)
+ end
+
def test_private_method_memoization
person = Person.new
diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb
index 684b931176..419ac14283 100644
--- a/activesupport/test/message_encryptor_test.rb
+++ b/activesupport/test/message_encryptor_test.rb
@@ -14,18 +14,18 @@ class MessageEncryptorTest < Test::Unit::TestCase
@encryptor = ActiveSupport::MessageEncryptor.new(ActiveSupport::SecureRandom.hex(64))
@data = { :some => "data", :now => Time.local(2010) }
end
-
+
def test_simple_round_tripping
message = @encryptor.encrypt(@data)
assert_equal @data, @encryptor.decrypt(message)
end
-
+
def test_encrypting_twice_yields_differing_cipher_text
first_messqage = @encryptor.encrypt(@data)
second_message = @encryptor.encrypt(@data)
assert_not_equal first_messqage, second_message
end
-
+
def test_messing_with_either_value_causes_failure
text, iv = @encryptor.encrypt(@data).split("--")
assert_not_decrypted([iv, text] * "--")
@@ -33,20 +33,20 @@ class MessageEncryptorTest < Test::Unit::TestCase
assert_not_decrypted([munge(text), iv] * "--")
assert_not_decrypted([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
-
-
+
+
private
def assert_not_decrypted(value)
assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
@encryptor.decrypt(value)
end
end
-
+
def munge(base64_string)
bits = ActiveSupport::Base64.decode64(base64_string)
bits.reverse!
diff --git a/activesupport/test/multibyte_conformance.rb b/activesupport/test/multibyte_conformance.rb
index 6ec9a839af..b3b477bb75 100644
--- a/activesupport/test/multibyte_conformance.rb
+++ b/activesupport/test/multibyte_conformance.rb
@@ -27,21 +27,21 @@ end
class MultibyteConformanceTest < Test::Unit::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
#
@@ -56,7 +56,7 @@ class MultibyteConformanceTest < Test::Unit::TestCase
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
@@ -71,10 +71,10 @@ class MultibyteConformanceTest < Test::Unit::TestCase
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
+ col1, col2, col3, col4, col5, comment = *cols
#
# NFKC
# c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5)
@@ -85,10 +85,10 @@ class MultibyteConformanceTest < Test::Unit::TestCase
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
+ col1, col2, col3, col4, col5, comment = *cols
#
# NFKD
# c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5)
@@ -99,7 +99,7 @@ class MultibyteConformanceTest < Test::Unit::TestCase
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
@@ -108,21 +108,21 @@ class MultibyteConformanceTest < Test::Unit::TestCase
until f.eof? || (max_test_lines > 38 and lines > max_test_lines)
lines += 1
line = f.gets.chomp!
- next if (line.empty? || line =~ /^\#/)
-
+ 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
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
index 9faa11efbc..7b48b3f85b 100644
--- a/activesupport/test/notifications_test.rb
+++ b/activesupport/test/notifications_test.rb
@@ -3,14 +3,19 @@ require 'abstract_unit'
module Notifications
class TestCase < ActiveSupport::TestCase
def setup
- ActiveSupport::Notifications.notifier = nil
- @notifier = ActiveSupport::Notifications.notifier
+ @old_notifier = ActiveSupport::Notifications.notifier
+ @notifier = ActiveSupport::Notifications::Fanout.new
+ ActiveSupport::Notifications.notifier = @notifier
@events = []
@named_events = []
@subscription = @notifier.subscribe { |*args| @events << event(*args) }
@named_subscription = @notifier.subscribe("named.subscription") { |*args| @named_events << event(*args) }
end
+ def teardown
+ ActiveSupport::Notifications.notifier = @old_notifier
+ end
+
private
def event(*args)
diff --git a/activesupport/test/option_merger_test.rb b/activesupport/test/option_merger_test.rb
index 33e3e69666..5b2e16a212 100644
--- a/activesupport/test/option_merger_test.rb
+++ b/activesupport/test/option_merger_test.rb
@@ -65,7 +65,7 @@ class OptionMergerTest < Test::Unit::TestCase
end
end
end
-
+
def test_nested_method_with_options_using_lamdba
local_lamdba = lambda { { :lambda => true } }
with_options(@options) do |o|
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index f47e896487..50168fa78f 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -78,20 +78,26 @@ class OrderedHashTest < Test::Unit::TestCase
def test_each_key
keys = []
- @ordered_hash.each_key { |k| keys << k }
+ assert_equal @ordered_hash, @ordered_hash.each_key { |k| keys << k }
assert_equal @keys, keys
+ expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator
+ assert_kind_of expected_class, @ordered_hash.each_key
end
def test_each_value
values = []
- @ordered_hash.each_value { |v| values << v }
+ assert_equal @ordered_hash, @ordered_hash.each_value { |v| values << v }
assert_equal @values, values
+ expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator
+ assert_kind_of expected_class, @ordered_hash.each_value
end
def test_each
values = []
- @ordered_hash.each {|key, value| values << value}
+ assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value}
assert_equal @values, values
+ expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator
+ assert_kind_of expected_class, @ordered_hash.each
end
def test_each_with_index
@@ -109,6 +115,14 @@ class OrderedHashTest < Test::Unit::TestCase
assert_equal @keys, keys
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')
@@ -217,8 +231,8 @@ class OrderedHashTest < Test::Unit::TestCase
ActiveSupport::OrderedHash[1,2,3,4,5]
flunk "Hash::[] should have raised an exception on initialization " +
"with an odd number of parameters"
- rescue
- assert_equal "odd number of arguments for Hash", $!.message
+ rescue ArgumentError => e
+ assert_equal "odd number of arguments for Hash", e.message
end
end
@@ -231,14 +245,14 @@ class OrderedHashTest < Test::Unit::TestCase
def test_each_after_yaml_serialization
values = []
- @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
@deserialized_ordered_hash.each {|key, value| values << value}
assert_equal @values, values
end
def test_order_after_yaml_serialization
- @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
assert_equal @keys, @deserialized_ordered_hash.keys
assert_equal @values, @deserialized_ordered_hash.values
@@ -247,12 +261,34 @@ class OrderedHashTest < Test::Unit::TestCase
def test_order_after_yaml_serialization_with_nested_arrays
@ordered_hash[:array] = %w(a b c)
- @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
assert_equal @ordered_hash.keys, @deserialized_ordered_hash.keys
assert_equal @ordered_hash.values, @deserialized_ordered_hash.values
end
+ begin
+ require 'psych'
+
+ def test_psych_serialize
+ @deserialized_ordered_hash = Psych.load(Psych.dump(@ordered_hash))
+
+ values = @deserialized_ordered_hash.map { |_, value| value }
+ assert_equal @values, values
+ end
+
+ def test_psych_serialize_tag
+ yaml = Psych.dump(@ordered_hash)
+ assert_match '!omap', yaml
+ end
+ rescue LoadError
+ end
+
+ def test_has_yaml_tag
+ @ordered_hash[:array] = %w(a b c)
+ assert_match '!omap', YAML.dump(@ordered_hash)
+ end
+
def test_update_sets_keys
@updated_ordered_hash = ActiveSupport::OrderedHash.new
@updated_ordered_hash.update(:name => "Bob")
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
index 1c74ce8b2a..bf4f5265ef 100644
--- a/activesupport/test/rescuable_test.rb
+++ b/activesupport/test/rescuable_test.rb
@@ -24,7 +24,7 @@ class Stargate
rescue_from NuclearExplosion do
@result = 'alldead'
end
-
+
rescue_from MadRonon do |e|
@result = e.message
end
@@ -80,16 +80,16 @@ class RescueableTest < Test::Unit::TestCase
@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
+ end
def test_rescues_defined_later_are_added_at_end_of_the_rescue_handlers_array
expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon"]
diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb
index bf61f9e58c..a4e2acbb32 100644
--- a/activesupport/test/safe_buffer_test.rb
+++ b/activesupport/test/safe_buffer_test.rb
@@ -1,4 +1,10 @@
require 'abstract_unit'
+begin
+ require 'psych'
+rescue LoadError
+end
+
+require 'yaml'
class SafeBufferTest < ActiveSupport::TestCase
def setup
@@ -38,4 +44,20 @@ class SafeBufferTest < ActiveSupport::TestCase
new_buffer = @buffer.to_s
assert_equal ActiveSupport::SafeBuffer, new_buffer.class
end
+
+ def test_to_yaml
+ str = 'hello!'
+ buf = ActiveSupport::SafeBuffer.new str
+ yaml = buf.to_yaml
+
+ assert_match(/^--- #{str}/, yaml)
+ assert_equal 'hello!', YAML.load(yaml)
+ end
+
+ def test_nested
+ str = 'hello!'
+ data = { 'str' => ActiveSupport::SafeBuffer.new(str) }
+ yaml = YAML.dump data
+ assert_equal({'str' => str}, YAML.load(yaml))
+ end
end
diff --git a/activesupport/test/test_case_test.rb b/activesupport/test/test_case_test.rb
new file mode 100644
index 0000000000..756d21b3e4
--- /dev/null
+++ b/activesupport/test/test_case_test.rb
@@ -0,0 +1,61 @@
+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
+ end
+
+ if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
+ def test_callback_with_exception
+ tc = Class.new(TestCase) do
+ 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_teardown_callback_with_exception
+ tc = Class.new(TestCase) do
+ 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
+ end
+ end
+end
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
index 633d3b212b..ee5a20c789 100644
--- a/activesupport/test/test_test.rb
+++ b/activesupport/test/test_test.rb
@@ -89,19 +89,19 @@ 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 { |v| assert_blank v }
end
-
+
def test_assert_blank_false
NOT_BLANK.each { |v|
- begin
+ begin
assert_blank v
fail 'should not get to here'
rescue Exception => e
- assert_match(/is not blank/, e.message)
- end
+ assert_match(/is not blank/, e.message)
+ end
}
end
end
@@ -109,30 +109,23 @@ 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_blank_true
NOT_BLANK.each { |v| assert_present v }
end
-
+
def test_assert_blank_false
BLANK.each { |v|
- begin
+ begin
assert_present v
fail 'should not get to here'
rescue Exception => e
- assert_match(/is blank/, e.message)
- end
+ assert_match(/is blank/, e.message)
+ end
}
end
end
-# These should always pass
-if ActiveSupport::Testing.const_defined?(:Default)
- class NotTestingThingsTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Default
- end
-end
-
class AlsoDoingNothingTest < ActiveSupport::TestCase
end
diff --git a/activesupport/test/test_xml_mini.rb b/activesupport/test/test_xml_mini.rb
index 585eb15c6e..6dbcd1f40b 100644
--- a/activesupport/test/test_xml_mini.rb
+++ b/activesupport/test/test_xml_mini.rb
@@ -1,49 +1,100 @@
require 'abstract_unit'
require 'active_support/xml_mini'
+require 'active_support/builder'
-class XmlMiniTest < Test::Unit::TestCase
- def test_rename_key_dasherizes_by_default
- assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key")
- end
+module XmlMiniTest
+ class RenameKeyTest < Test::Unit::TestCase
+ def test_rename_key_dasherizes_by_default
+ assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key")
+ end
- def test_rename_key_does_nothing_with_dasherize_true
- assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true)
- end
+ def test_rename_key_does_nothing_with_dasherize_true
+ assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true)
+ end
- def test_rename_key_does_nothing_with_dasherize_false
- assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false)
- end
+ def test_rename_key_does_nothing_with_dasherize_false
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false)
+ end
- def test_rename_key_camelizes_with_camelize_true
- assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true)
- end
+ def test_rename_key_camelizes_with_camelize_false
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => false)
+ end
- def test_rename_key_camelizes_with_camelize_true
- assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true)
- end
+ def test_rename_key_camelizes_with_camelize_nil
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => nil)
+ end
- def test_rename_key_does_not_dasherize_leading_underscores
- assert_equal "_id", ActiveSupport::XmlMini.rename_key("_id")
- 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_with_leading_underscore_dasherizes_interior_underscores
- assert_equal "_my-key", ActiveSupport::XmlMini.rename_key("_my_key")
- 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_does_not_dasherize_trailing_underscores
- assert_equal "id_", ActiveSupport::XmlMini.rename_key("id_")
- 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_with_trailing_underscore_dasherizes_interior_underscores
- assert_equal "my-key_", ActiveSupport::XmlMini.rename_key("my_key_")
- end
+ def test_rename_key_does_not_dasherize_leading_underscores
+ assert_equal "_id", ActiveSupport::XmlMini.rename_key("_id")
+ end
- def test_rename_key_does_not_dasherize_multiple_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_does_not_dasherize_multiple_leading_underscores
- assert_equal "id__", ActiveSupport::XmlMini.rename_key("id__")
+ def test_rename_key_with_trailing_underscore_dasherizes_interior_underscores
+ assert_equal "my-key_", ActiveSupport::XmlMini.rename_key("my_key_")
+ end
+
+ def test_rename_key_does_not_dasherize_multiple_leading_underscores
+ assert_equal "__id", ActiveSupport::XmlMini.rename_key("__id")
+ end
+
+ def test_rename_key_does_not_dasherize_multiple_leading_underscores
+ assert_equal "id__", ActiveSupport::XmlMini.rename_key("id__")
+ end
end
+ class ToTagTest < ActiveSupport::TestCase
+ def assert_xml(xml)
+ assert_equal xml, @options[:builder].target!
+ end
+
+ setup do
+ @xml = ActiveSupport::XmlMini
+ @options = {:skip_instruct => true, :builder => Builder::XmlMarkup.new}
+ end
+
+ test "#to_tag accepts a callable object and passes options with the builder" do
+ @xml.to_tag(:some_tag, lambda {|o| o[:builder].br }, @options)
+ assert_xml "<br/>"
+ end
+
+ test "#to_tag accepts a callable object and passes options and tag name" do
+ @xml.to_tag(:tag, lambda {|o, t| o[:builder].b(t) }, @options)
+ assert_xml "<b>tag</b>"
+ end
+
+ test "#to_tag accepts an object responding to #to_xml and passes the options, where :root is key" do
+ obj = Object.new
+ obj.instance_eval do
+ def to_xml(options) options[:builder].yo(options[:root].to_s) end
+ end
+
+ @xml.to_tag(:tag, obj, @options)
+ assert_xml "<yo>tag</yo>"
+ end
+
+ test "#to_tag accepts arbitrary objects responding to #to_str" do
+ @xml.to_tag(:b, "Howdy", @options)
+ assert_xml "<b>Howdy</b>"
+ end
+ # TODO: test the remaining functions hidden in #to_tag.
+ end
end
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index af6eee69e5..49cefc6e82 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -216,7 +216,7 @@ class TimeZoneTest < Test::Unit::TestCase
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)
diff --git a/activesupport/test/whiny_nil_test.rb b/activesupport/test/whiny_nil_test.rb
index 4b9f06dead..ec3ca99ee6 100644
--- a/activesupport/test/whiny_nil_test.rb
+++ b/activesupport/test/whiny_nil_test.rb
@@ -33,9 +33,11 @@ class WhinyNilTest < Test::Unit::TestCase
end
def test_id
+ nil.stubs(:object_id).returns(999)
nil.id
rescue RuntimeError => nme
assert_no_match(/nil:NilClass/, nme.message)
+ assert_match(/999/, nme.message)
end
def test_no_to_ary_coercion
diff --git a/ci/ci_build.rb b/ci/ci_build.rb
index f9933cb922..c3af1f0177 100755
--- a/ci/ci_build.rb
+++ b/ci/ci_build.rb
@@ -19,88 +19,137 @@ puts "[CruiseControl] Rails build"
build_results = {}
# Install required version of bundler.
-bundler_install_cmd = "sudo gem install bundler --pre --no-ri --no-rdoc"
+bundler_install_cmd = "sudo gem install bundler --no-ri --no-rdoc"
puts "Running command: #{bundler_install_cmd}"
build_results[:install_bundler] = system bundler_install_cmd
cd root_dir do
puts
- puts "[CruiseControl] Bundling RubyGems"
+ puts "[CruiseControl] Bundling gems"
puts
- build_results[:bundle] = system 'rm -rf ~/.bundle; env CI=1 bundle update'
+ build_results[:bundle] = system 'bundle update'
end
cd "#{root_dir}/activesupport" do
puts
- puts "[CruiseControl] Building ActiveSupport"
+ puts "[CruiseControl] Building Active Support"
puts
build_results[:activesupport] = rake 'test'
- # build_results[:activesupport_isolated] = rake 'test:isolated'
+ build_results[:activesupport_isolated] = rake 'test:isolated'
end
+system "sudo rm -R #{root_dir}/railties/tmp"
cd "#{root_dir}/railties" do
puts
- puts "[CruiseControl] Building RailTies"
+ puts "[CruiseControl] Building Railties"
puts
build_results[:railties] = rake 'test'
end
cd "#{root_dir}/actionpack" do
puts
- puts "[CruiseControl] Building ActionPack"
+ puts "[CruiseControl] Building Action Pack"
puts
build_results[:actionpack] = rake 'test'
- # build_results[:actionpack_isolated] = rake 'test:isolated'
+ build_results[:actionpack_isolated] = rake 'test:isolated'
end
cd "#{root_dir}/actionmailer" do
puts
- puts "[CruiseControl] Building ActionMailer"
+ puts "[CruiseControl] Building Action Mailer"
puts
build_results[:actionmailer] = rake 'test'
- # build_results[:actionmailer_isolated] = rake 'test:isolated'
+ build_results[:actionmailer_isolated] = rake 'test:isolated'
end
cd "#{root_dir}/activemodel" do
puts
- puts "[CruiseControl] Building ActiveModel"
+ puts "[CruiseControl] Building Active Model"
puts
build_results[:activemodel] = rake 'test'
- # build_results[:activemodel_isolated] = rake 'test:isolated'
+ build_results[:activemodel_isolated] = rake 'test:isolated'
end
rm_f "#{root_dir}/activeresource/debug.log"
cd "#{root_dir}/activeresource" do
puts
- puts "[CruiseControl] Building ActiveResource"
+ puts "[CruiseControl] Building Active Resource"
puts
build_results[:activeresource] = rake 'test'
- # build_results[:activeresource_isolated] = rake 'test:isolated'
+ build_results[:activeresource_isolated] = rake 'test:isolated'
end
rm_f "#{root_dir}/activerecord/debug.log"
cd "#{root_dir}/activerecord" do
puts
- puts "[CruiseControl] Building ActiveRecord with MySQL"
+ puts "[CruiseControl] Building Active Record with MySQL IM enabled"
puts
+ ENV['IM'] = 'true'
build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'mysql:test'
- # build_results[:activerecord_mysql_isolated] = rake 'mysql:rebuild_databases', 'mysql:isolated_test'
+ build_results[:activerecord_mysql_isolated] = rake 'mysql:rebuild_databases', 'mysql:isolated_test'
end
cd "#{root_dir}/activerecord" do
puts
- puts "[CruiseControl] Building ActiveRecord with PostgreSQL"
+ puts "[CruiseControl] Building Active Record with MySQL IM disabled"
puts
+ ENV['IM'] = 'false'
+ build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'mysql:test'
+ build_results[:activerecord_mysql_isolated] = rake 'mysql:rebuild_databases', 'mysql:isolated_test'
+end
+
+cd "#{root_dir}/activerecord" do
+ puts
+ puts "[CruiseControl] Building Active Record with MySQL2 IM enabled"
+ puts
+ ENV['IM'] = 'true'
+ build_results[:activerecord_mysql2] = rake 'mysql:rebuild_databases', 'mysql2:test'
+ build_results[:activerecord_mysql2_isolated] = rake 'mysql:rebuild_databases', 'mysql2:isolated_test'
+end
+
+cd "#{root_dir}/activerecord" do
+ puts
+ puts "[CruiseControl] Building Active Record with MySQL2 IM disabled"
+ puts
+ ENV['IM'] = 'false'
+ build_results[:activerecord_mysql2] = rake 'mysql:rebuild_databases', 'mysql2:test'
+ build_results[:activerecord_mysql2_isolated] = rake 'mysql:rebuild_databases', 'mysql2:isolated_test'
+end
+
+cd "#{root_dir}/activerecord" do
+ puts
+ puts "[CruiseControl] Building Active Record with PostgreSQL IM enabled"
+ puts
+ ENV['IM'] = 'true'
+ build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'postgresql:test'
+ build_results[:activerecord_postgresql8_isolated] = rake 'postgresql:rebuild_databases', 'postgresql:isolated_test'
+end
+
+cd "#{root_dir}/activerecord" do
+ puts
+ puts "[CruiseControl] Building Active Record with PostgreSQL IM disabled"
+ puts
+ ENV['IM'] = 'false'
build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'postgresql:test'
- # build_results[:activerecord_postgresql8_isolated] = rake 'postgresql:rebuild_databases', 'postgresql:isolated_test'
+ build_results[:activerecord_postgresql8_isolated] = rake 'postgresql:rebuild_databases', 'postgresql:isolated_test'
+end
+
+cd "#{root_dir}/activerecord" do
+ puts
+ puts "[CruiseControl] Building Active Record with SQLite 3 IM enabled"
+ puts
+ ENV['IM'] = 'true'
+ build_results[:activerecord_sqlite3] = rake 'sqlite3:test'
+ build_results[:activerecord_sqlite3_isolated] = rake 'sqlite3:isolated_test'
end
cd "#{root_dir}/activerecord" do
puts
- puts "[CruiseControl] Building ActiveRecord with SQLite 3"
+ puts "[CruiseControl] Building Active Record with SQLite 3 IM disabled"
puts
+ ENV['IM'] = 'false'
build_results[:activerecord_sqlite3] = rake 'sqlite3:test'
- # build_results[:activerecord_sqlite3_isolated] = rake 'sqlite3:isolated_test'
+ build_results[:activerecord_sqlite3_isolated] = rake 'sqlite3:isolated_test'
end
diff --git a/ci/ci_setup_notes.txt b/ci/ci_setup_notes.txt
index b61e893b8e..890f9e8ef6 100644
--- a/ci/ci_setup_notes.txt
+++ b/ci/ci_setup_notes.txt
@@ -26,8 +26,8 @@ $ sudo shutdown -r now
* Update aptitude:
$ sudo aptitude update
-* Use cinabox to perform rest of ruby/ccrb setup:
-* http://github.com/thewoolleyman/cinabox/tree/master/README.txt
+* Use cinabox to perform rest of ruby/ccrb setup:
+* https://github.com/thewoolleyman/cinabox/tree/master/README.txt
# This is not yet properly supported by RubyGems...
# * Configure RubyGems to not require root access for gem installation
@@ -41,7 +41,7 @@ $ sudo aptitude update
# # add these lines:
# ---
# gemhome: /home/ci/.gem/ruby/1.8
-# gempath:
+# gempath:
# - /home/ci/.gem/ruby/1.8
* If you did not configure no-root-gem installation via ~/.gemrc as shown above, then allow no-password sudo for gem installation:
@@ -89,7 +89,7 @@ Configuration.dashboard_url = 'http://ci.yourdomain.com/'
Configuration.serialize_builds = true
Configuration.serialized_build_timeout = 1.hours
BuildReaper.number_of_builds_to_keep = 100
-
+
* Copy and configure cruise project config file
$ cp ~/.cruise/projects/rails/work/ci/cruise_config.rb ~/.cruise/projects/rails
$ vi ~/.cruise/projects/rails/cruise_config.rb:
@@ -137,4 +137,4 @@ $ rake postgresql:build_databases
* Reboot and make sure everything is working
$ sudo shutdown -r now
-$ http://ci.yourdomain.com \ No newline at end of file
+$ http://ci.yourdomain.com
diff --git a/ci/site_config.rb b/ci/site_config.rb
index c08dac8e84..09d5b550e8 100644
--- a/ci/site_config.rb
+++ b/ci/site_config.rb
@@ -6,10 +6,10 @@
# EMAIL NOTIFICATION
# ------------------
-# CruiseControl.rb can notify you about build status via email. It uses the Action Mailer component of Ruby on Rails
-# framework. Obviously, Action Mailer needs to know how to send out email messages.
+# CruiseControl.rb can notify you about build status via email. It uses the Action Mailer component of Ruby on Rails
+# framework. Obviously, Action Mailer needs to know how to send out email messages.
# If you have an SMTP server on your network, and it needs no authentication, write this in your site_config.rb:
-#
+#
ActionMailer::Base.smtp_settings = {
:address => "localhost",
:domain => "ci.rubyonrails.org",
@@ -26,8 +26,8 @@ ActionMailer::Base.smtp_settings = {
# :user_name => "yourgmailaccount",
# :password => "yourgmailpassword"
# }
-#
-# The same approach works for other SMTP servers thet require authentication. Note that GMail's SMTP server runs on a
+#
+# The same approach works for other SMTP servers thet require authentication. Note that GMail's SMTP server runs on a
# non-standard port 587 (standard port for SMTP is 25).
#
# For further details about configuration of outgoing email, see Ruby On Rails documentation for ActionMailer::Base.
@@ -63,7 +63,7 @@ Configuration.serialize_builds = true
# Amount of time a project will wait to build before failing when build serialization is on
Configuration.serialized_build_timeout = 3.hours
-# To delete build when there are more than a certain number present, uncomment this line - it will make the dashboard
+# To delete build when there are more than a certain number present, uncomment this line - it will make the dashboard
# perform better
BuildReaper.number_of_builds_to_keep = 100
diff --git a/load_paths.rb b/load_paths.rb
index 873315f978..8f37364629 100644
--- a/load_paths.rb
+++ b/load_paths.rb
@@ -4,7 +4,7 @@ rescue LoadError
begin
# bust gem prelude
if defined? Gem
- Gem.cache
+ Gem.source_index
gem 'bundler'
else
require 'rubygems'
diff --git a/rails.gemspec b/rails.gemspec
index 8c90584470..98b5f46554 100644
--- a/rails.gemspec
+++ b/rails.gemspec
@@ -25,5 +25,5 @@ Gem::Specification.new do |s|
s.add_dependency('activeresource', version)
s.add_dependency('actionmailer', version)
s.add_dependency('railties', version)
- s.add_dependency('bundler', '>= 1.0.0.rc.2')
+ s.add_dependency('bundler', '~> 1.0')
end
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index fc1ec340c7..75f1df44e7 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,7 +1,38 @@
-*Rails 3.0.0 [release candidate] (July 26th, 2010)*
+*Rails 3.1.0 (unreleased)*
-* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit
- and --skip-active-record respectively. [fxn]
+* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing [Piotr Sarnacki]
+
+* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. [siong1987]
+
+* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack [José Valim]
+
+* Added Rack::Cache to the default middleware stack [Yehuda Katz and Carl Lerche]
+
+* Engine is now rack application [Piotr Sarnacki]
+
+* Added middleware stack to Engine [Piotr Sarnacki]
+
+* Engine can now load plugins [Piotr Sarnacki]
+
+* Engine can load its own environment file [Piotr Sarnacki]
+
+* Added helpers to call engines' route helpers from application and vice versa [Piotr Sarnacki]
+
+* Task for copying plugins' and engines' migrations to application's db/migrate directory [Piotr Sarnacki]
+
+* Changed ActionDispatch::Static to allow handling multiple directories [Piotr Sarnacki]
+
+* Added isolate_namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki]
+
+* Include all helpers from plugins and shared engines in application [Piotr Sarnacki]
+
+*Rails 3.0.1 (October 15, 2010)*
+
+* No Changes, just a version bump.
+
+*Rails 3.0.0 (August 29, 2010)*
+
+* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit and --skip-active-record respectively. [fxn]
* Added console to Rails::Railtie as a hook called just after console starts. [José Valim]
@@ -15,19 +46,10 @@
* Made the rails command work even when you're in a subdirectory [Chad Fowler]
-
-*Rails 3.0.0 [beta 4] (June 8th, 2010)*
-
* Removed Rails Metal [Yehuda Katz, José Valim].
-
-*Rails 3.0.0 [beta 3] (April 13th, 2010)*
-
* Renamed config.cookie_secret to config.secret_token and pass it as env key. [José Valim]
-
-*Rails 3.0.0 [beta 2] (April 1st, 2010)*
-
* Session store configuration has changed [Yehuda Katz, Carl Lerche]
config.session_store :cookie_store, {:key => "..."}
@@ -39,14 +61,12 @@
* Added config.generators.templates to provide alternative paths for the generators
to look for templates [José Valim]
-*Rails 3.0.0 [beta 1] (February 4, 2010)*
-
* Added "rake about" as a replacement for script/about [DHH]
* Removed all the default commands in script/* and replaced them with script/rails and a rails command that'll act the same when run from within the app [DHH]. Example:
./script/generate scaffold post title:string can now be called as rails g scaffold post title:string
-
+
Run rails --help inside an app for more help.
* Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it [DHH]
@@ -68,7 +88,7 @@
cookies.permanent.signed[:remember_me] = current_user.id
# => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
+
...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications).
* Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed [DHH]
@@ -101,42 +121,42 @@
* Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally]
This has been extracted from rg - http://github.com/jeremymcanally/rg
-
+
Example:
-
+
# template.rb
-
+
# Install plugins from git or svn
plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git"
plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/"
-
+
# Add gems to environment.rb
gem "jeremymcanally-context"
gem "bluecloth"
-
+
# Vendor file. Data in a string or...
vendor("borrowed.rb", <<CODE
def helpful_method
do_something_helpful_here
end
CODE
-
+
# ...file data from block return value.
# #initializer creates a new initializer file
initializer("crypto.rb") do
salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}"
-
+
"SPECIAL_SALT = '#{salt}'"
end
-
+
Usage:
-
+
To use a template, provide a file path or URL:
-
+
1. Using a local file :
rails <application name> -m /path/to/my/template.rb
-
+
2. Or directly from a URL :
rails <application name> --template=http://gist.github.com/31208.txt
@@ -235,7 +255,7 @@
rake gems:unpack # unpacks all gems
rake gems:unpack GEM=mygem # unpacks only the gem 'mygem'
-
+
rake gems:build # builds all unpacked gems
rake gems:build GEM=mygem # builds only the gem 'mygem'
@@ -246,16 +266,16 @@
* Allow files in plugins to be reloaded like the rest of the application. [Rick Olson]
Enables or disables plugin reloading.
-
+
config.reload_plugins = true
-
+
You can get around this setting per plugin.
If #reload_plugins? == false (DEFAULT), add this to your plugin's init.rb to make it reloadable:
-
+
Dependencies.load_once_paths.delete lib_path
-
+
If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
-
+
Dependencies.load_once_paths << lib_path
* Small tweak to allow plugins to specify gem dependencies. [Rick Olson]
@@ -280,13 +300,13 @@
config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
config.gem "aws-s3", :lib => "aws/s3"
end
-
+
# List required gems.
rake gems
-
+
# Install all required gems:
rake gems:install
-
+
# Unpack specified gem to vendor/gems/gem_name-x.x.x
rake gems:unpack GEM=bj
@@ -473,9 +493,9 @@ databases on localhost. #9753 [Trevor Wennblom]
For example:
ruby script/generation migration AddSomeStuffToCustomers first_name:string last_name:string
-
+
or
-
+
ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string
* Add ActiveResource to Rails::Info. Closes #8741 [Chris Kampmeier]
@@ -535,13 +555,13 @@ databases on localhost. #9753 [Trevor Wennblom]
* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [David Heinemeier Hansson]
To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger'
- (instead of 'breakpoint') where you want to jump into the debugger.
-
+ (instead of 'breakpoint') where you want to jump into the debugger.
+
BACKWARDS INCOMPATIBILITY NOTE: You must remove the default line 12 from config/environments/development.rb:
-
+
config.breakpoint_server = true
-
- This configuration option is no longer available. Rails will fail to start in development mode as long as
+
+ This configuration option is no longer available. Rails will fail to start in development mode as long as
that's still present.
* Resource scaffolding returns the created entity.to_xml. [Jeremy Kemper]
@@ -553,7 +573,7 @@ databases on localhost. #9753 [Trevor Wennblom]
* Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb:
config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib )
-
+
...or just gem 'actionwebservice'
* Give generate scaffold a more descriptive database message. Closes #7316 [Jeremy McAnally]
@@ -566,7 +586,7 @@ databases on localhost. #9753 [Trevor Wennblom]
* Windows: include MinGW in RUBY_PLATFORM check. #2982 [okkez000@gmail.com, Kaspar Schiess]
-* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. [Marcel Molina Jr.]
+* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. [Marcel Molina Jr.]
* Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. [Marcel Molina Jr.]
@@ -602,7 +622,7 @@ databases on localhost. #9753 [Trevor Wennblom]
* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
If you really want your plugins to reload, add this to the very top of init.rb:
-
+
Dependencies.load_once_paths.delete(lib_path)
* Allow config.to_prepare to work, make the dispatcher safe to 're require'. [Michael Koziarski, Nicholas Seckar]
@@ -724,9 +744,9 @@ databases on localhost. #9753 [Trevor Wennblom]
* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
documented in initializer.rb, the workaround is:
-
+
config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/']
-
+
References #6031. [Nicholas Seckar]
* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
@@ -811,10 +831,10 @@ References #6031. [Nicholas Seckar]
0002 def show
0003-> breakpoint
0004 end
- 0005
+ 0005
0006 def index
0007 end
- 0008
+ 0008
=> "/path/to/rails/root/app/controllers/top_controller.rb"
irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
@@ -905,7 +925,7 @@ References #6031. [Nicholas Seckar]
* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
If you really want your plugins to reload, add this to the very top of init.rb:
-
+
Dependencies.load_once_paths.delete(lib_path)
* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 [fearoffish]
@@ -1011,9 +1031,9 @@ References #6031. [Nicholas Seckar]
* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
documented in initializer.rb, the workaround is:
-
+
config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/']
-
+
References #6031. [Nicholas Seckar]
* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
@@ -1094,10 +1114,10 @@ References #6031. [Nicholas Seckar]
0002 def show
0003-> breakpoint
0004 end
- 0005
+ 0005
0006 def index
0007 end
- 0008
+ 0008
=> "/path/to/rails/root/app/controllers/top_controller.rb"
irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
@@ -1332,7 +1352,7 @@ References #6031. [Nicholas Seckar]
* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) [David Heinemeier Hansson]
-* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [David Heinemeier Hansson]
+* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [David Heinemeier Hansson]
* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration [David Heinemeier Hansson]
@@ -1711,7 +1731,7 @@ References #6031. [Nicholas Seckar]
# runs the one statement 10 times
script/benchmarker 10 'Person.expensive_method(10)'
-
+
# pits the two statements against each other with 50 runs each
script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)'
@@ -1751,18 +1771,18 @@ References #6031. [Nicholas Seckar]
* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Lütke]
* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
-
+
./script/runner 'ReminderService.deliver'
./script/runner 'Mailer.receive(STDIN.read)'
-
+
This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code.
* Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 [dave@cherryville.org]
* Fixed the Rakefile's interaction with postgresql to:
- 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
- passwords when connecting to a remote db and local socket connections.
+ 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
+ passwords when connecting to a remote db and local socket connections.
2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik]
3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson]
4. Use the port if available #875 [madrobby]
@@ -1825,10 +1845,10 @@ References #6031. [Nicholas Seckar]
Controller: components/list/items_controller.rb
(holds a List::ItemsController class with uses_component_template_root called)
-
+
Model : components/list/item.rb
(namespace is still shared, so an Item model in app/models will take precedence)
-
+
Views : components/list/items/show.rhtml
@@ -1921,11 +1941,11 @@ References #6031. [Nicholas Seckar]
* Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that
the environment options needs to change from:
-
+
Before in development.rb:
ActionController::Base.reload_dependencies = true  
ActiveRecord::Base.reload_associations     = true
-
+
Now in development.rb:
Dependencies.mechanism = :load
@@ -1979,41 +1999,41 @@ References #6031. [Nicholas Seckar]
* Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in
the code, investigate and change the model, AND then resume execution! Example:
-
+
class WeblogController < ActionController::Base
def index
@posts = Post.find_all
breakpoint "Breaking out from the list"
end
end
-
- So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
+
+ So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
Here you can do things like:
-
+
Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
>> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
+ => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
#<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
>> @posts.first.title = "hello from a breakpoint"
=> "hello from a breakpoint"
...and even better is that you can examine how your runtime objects actually work:
- >> f = @posts.first
+ >> f = @posts.first
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
-
+
Finally, when you're ready to resume execution, you press CTRL-D
* Changed environments to be configurable through an environment variable. By default, the environment is "development", but you
can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server):
-
+
SetEnv RAILS_ENV production
-
+
...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this:
-
+
ruby public/dispatcher.servlet -e production
* Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that.
@@ -2028,11 +2048,11 @@ References #6031. [Nicholas Seckar]
app/controllers/account_controller.rb # URL: /account/
app/controllers/admin/account_controller.rb # URL: /admin/account/
-
+
NOTE: You need to update your public/.htaccess with the new rules to pick it up
-* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
- those environments for development. This is turned on by default, but can be turned off with
+* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
+ those environments for development. This is turned on by default, but can be turned off with
ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments.
* Added support for sub-directories in app/models. So now you can have something like Basecamp with:
@@ -2041,7 +2061,7 @@ References #6031. [Nicholas Seckar]
app/models/project
app/models/participants
app/models/settings
-
+
It's poor man's namespacing, but only for file-system organization. You still require files just like before.
Nothing changes inside the files themselves.
@@ -2061,7 +2081,7 @@ References #6031. [Nicholas Seckar]
@david.projects << @new_project
breakpoint "Let's have a closer look at @david"
end
-
+
You need to install dev-utils yourself for this to work ("gem install dev-util").
* Added shared generator behavior so future upgrades should be possible without manually copying over files [Jeremy Kemper]
@@ -2120,7 +2140,7 @@ References #6031. [Nicholas Seckar]
*0.7.0*
-* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
+* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures.
[Kevin Radloff]
@@ -2134,8 +2154,8 @@ References #6031. [Nicholas Seckar]
* create_fixtures in both the functional and unit test helper now turns off the log during fixture generation
and can generate more than one fixture at a time. Which makes it possible for assignments like:
-
- @people, @projects, @project_access, @companies, @accounts =
+
+ @people, @projects, @project_access, @companies, @accounts =
create_fixtures "people", "projects", "project_access", "companies", "accounts"
* Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file)
@@ -2147,7 +2167,7 @@ References #6031. [Nicholas Seckar]
* No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile)
-* The new_model generator will now use the same rules for plural wordings as Active Record
+* The new_model generator will now use the same rules for plural wordings as Active Record
(so Category will give categories, not categorys) [Kevin Radloff]
* dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded [danp]
@@ -2173,13 +2193,13 @@ References #6031. [Nicholas Seckar]
* Added environments that can be included from any script to get the full Active Record and Action Controller
context running. This can be used by maintenance scripts or to interact with the model through IRB. Example:
-
+
require 'config/environments/production'
-
+
for account in Account.find_all
account.recalculate_interests
end
-
+
A short migration script for an account model that had it's interest calculation strategy changed.
* Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick)
@@ -2202,7 +2222,7 @@ References #6031. [Nicholas Seckar]
* Added lib in root as a place to store app specific libraries
-* Added lib and vendor to load_path, so anything store within can be loaded directly.
+* Added lib and vendor to load_path, so anything store within can be loaded directly.
Hence lib/redcloth.rb can be loaded with require "redcloth"
* Upgraded to Action Pack 0.7.8 (lots of fixes)
@@ -2216,7 +2236,7 @@ References #6031. [Nicholas Seckar]
* Updated the generated template stubs to valid XHTML files
-* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
+* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
gives the same as "new_controller Todolists" and "new_controller todolists".
diff --git a/railties/MIT-LICENSE b/railties/MIT-LICENSE
index 86bcb23b7c..c73d1af096 100644
--- a/railties/MIT-LICENSE
+++ b/railties/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/railties/README.rdoc b/railties/README.rdoc
index a1718a7d96..0457227473 100644
--- a/railties/README.rdoc
+++ b/railties/README.rdoc
@@ -4,7 +4,7 @@ Railties is responsible to glue all frameworks together. Overall, it:
* handles all the bootstrapping process for a Rails application;
-* manager rails command line interface;
+* manages rails command line interface;
* provides Rails generators core;
@@ -15,7 +15,7 @@ The latest version of Railties can be installed with Rubygems:
* gem install railties
-Documentation can be found at
+Documentation can be found at
* http://api.rubyonrails.org
@@ -23,3 +23,4 @@ Documentation can be found at
== License
Railties is released under the MIT license.
+
diff --git a/railties/Rakefile b/railties/Rakefile
index 8e78d2ff4a..26fa0bf6a5 100644..100755
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -1,8 +1,5 @@
-gem 'rdoc', '>= 2.5.9'
-require 'rdoc'
-require 'rake'
+#!/usr/bin/env rake
require 'rake/testtask'
-require 'rdoc/task'
require 'rake/gempackagetask'
require 'date'
@@ -21,7 +18,7 @@ namespace :test do
Dir["test/#{dir}/*_test.rb"].each do |file|
next true if file.include?("fixtures")
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
- system(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file)
+ sh(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file)
end
end
end
@@ -48,8 +45,9 @@ task :generate_guides do
ruby "guides/rails_guides.rb"
end
-task :update_prototype_ujs do
- system "curl http://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/rails.js"
+task :update_ujs do
+ system "curl https://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js"
+ system "curl https://github.com/rails/jquery-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js"
end
# Validate guides -------------------------------------------------------------------------
@@ -58,19 +56,6 @@ task :validate_guides do
ruby "guides/w3c_validator.rb"
end
-# Generate documentation ------------------------------------------------------------------
-
-RDoc::Task.new { |rdoc|
- rdoc.rdoc_dir = 'doc'
- rdoc.title = "Railties -- Gluing the Engine to the Rails"
- rdoc.options << '-f' << 'horo'
- rdoc.options << '--main' << 'README.rdoc'
- rdoc.options << '--charset' << 'utf-8'
- rdoc.rdoc_files.include('README.rdoc', 'CHANGELOG')
- rdoc.rdoc_files.include('lib/**/*.rb')
- rdoc.rdoc_files.exclude('lib/rails/generators/**/templates/*')
-}
-
# Generate GEM ----------------------------------------------------------------------------
spec = eval(File.read('railties.gemspec'))
diff --git a/railties/guides/assets/javascripts/code_highlighter.js b/railties/guides/assets/javascripts/code_highlighter.js
deleted file mode 100644
index ce983dad52..0000000000
--- a/railties/guides/assets/javascripts/code_highlighter.js
+++ /dev/null
@@ -1,188 +0,0 @@
-/* Unobtrustive Code Highlighter By Dan Webb 11/2005
- Version: 0.4
-
- Usage:
- Add a script tag for this script and any stylesets you need to use
- to the page in question, add correct class names to CODE elements,
- define CSS styles for elements. That's it!
-
- Known to work on:
- IE 5.5+ PC
- Firefox/Mozilla PC/Mac
- Opera 7.23 + PC
- Safari 2
-
- Known to degrade gracefully on:
- IE5.0 PC
-
- Note: IE5.0 fails due to the use of lookahead in some stylesets. To avoid script errors
- in older browsers use expressions that use lookahead in string format when defining stylesets.
-
- This script is inspired by star-light by entirely cunning Dean Edwards
- http://dean.edwards.name/star-light/.
-*/
-
-// replace callback support for safari.
-if ("a".replace(/a/, function() {return "b"}) != "b") (function(){
- var default_replace = String.prototype.replace;
- String.prototype.replace = function(search,replace){
- // replace is not function
- if(typeof replace != "function"){
- return default_replace.apply(this,arguments)
- }
- var str = "" + this;
- var callback = replace;
- // search string is not RegExp
- if(!(search instanceof RegExp)){
- var idx = str.indexOf(search);
- return (
- idx == -1 ? str :
- default_replace.apply(str,[search,callback(search, idx, str)])
- )
- }
- var reg = search;
- var result = [];
- var lastidx = reg.lastIndex;
- var re;
- while((re = reg.exec(str)) != null){
- var idx = re.index;
- var args = re.concat(idx, str);
- result.push(
- str.slice(lastidx,idx),
- callback.apply(null,args).toString()
- );
- if(!reg.global){
- lastidx += RegExp.lastMatch.length;
- break
- }else{
- lastidx = reg.lastIndex;
- }
- }
- result.push(str.slice(lastidx));
- return result.join("")
- }
-})();
-
-var CodeHighlighter = { styleSets : new Array };
-
-CodeHighlighter.addStyle = function(name, rules) {
- // using push test to disallow older browsers from adding styleSets
- if ([].push) this.styleSets.push({
- name : name,
- rules : rules,
- ignoreCase : arguments[2] || false
- })
-
- function setEvent() {
- // set highlighter to run on load (use LowPro if present)
- if (typeof Event != 'undefined' && typeof Event.onReady == 'function')
- return Event.onReady(CodeHighlighter.init.bind(CodeHighlighter));
-
- var old = window.onload;
-
- if (typeof window.onload != 'function') {
- window.onload = function() { CodeHighlighter.init() };
- } else {
- window.onload = function() {
- old();
- CodeHighlighter.init();
- }
- }
- }
-
- // only set the event when the first style is added
- if (this.styleSets.length==1) setEvent();
-}
-
-CodeHighlighter.init = function() {
- if (!document.getElementsByTagName) return;
- if ("a".replace(/a/, function() {return "b"}) != "b") return; // throw out Safari versions that don't support replace function
- // throw out older browsers
-
- var codeEls = document.getElementsByTagName("CODE");
- // collect array of all pre elements
- codeEls.filter = function(f) {
- var a = new Array;
- for (var i = 0; i < this.length; i++) if (f(this[i])) a[a.length] = this[i];
- return a;
- }
-
- var rules = new Array;
- rules.toString = function() {
- // joins regexes into one big parallel regex
- var exps = new Array;
- for (var i = 0; i < this.length; i++) exps.push(this[i].exp);
- return exps.join("|");
- }
-
- function addRule(className, rule) {
- // add a replace rule
- var exp = (typeof rule.exp != "string")?String(rule.exp).substr(1, String(rule.exp).length-2):rule.exp;
- // converts regex rules to strings and chops of the slashes
- rules.push({
- className : className,
- exp : "(" + exp + ")",
- length : (exp.match(/(^|[^\\])\([^?]/g) || "").length + 1, // number of subexps in rule
- replacement : rule.replacement || null
- });
- }
-
- function parse(text, ignoreCase) {
- // main text parsing and replacement
- return text.replace(new RegExp(rules, (ignoreCase)?"gi":"g"), function() {
- var i = 0, j = 1, rule;
- while (rule = rules[i++]) {
- if (arguments[j]) {
- // if no custom replacement defined do the simple replacement
- if (!rule.replacement) return "<span class=\"" + rule.className + "\">" + arguments[0] + "</span>";
- else {
- // replace $0 with the className then do normal replaces
- var str = rule.replacement.replace("$0", rule.className);
- for (var k = 1; k <= rule.length - 1; k++) str = str.replace("$" + k, arguments[j + k]);
- return str;
- }
- } else j+= rule.length;
- }
- });
- }
-
- function highlightCode(styleSet) {
- // clear rules array
- var parsed, clsRx = new RegExp("(\\s|^)" + styleSet.name + "(\\s|$)");
- rules.length = 0;
-
- // get stylable elements by filtering out all code elements without the correct className
- var stylableEls = codeEls.filter(function(item) { return clsRx.test(item.className) });
-
- // add style rules to parser
- for (var className in styleSet.rules) addRule(className, styleSet.rules[className]);
-
-
- // replace for all elements
- for (var i = 0; i < stylableEls.length; i++) {
- // EVIL hack to fix IE whitespace badness if it's inside a <pre>
- if (/MSIE/.test(navigator.appVersion) && stylableEls[i].parentNode.nodeName == 'PRE') {
- stylableEls[i] = stylableEls[i].parentNode;
-
- parsed = stylableEls[i].innerHTML.replace(/(<code[^>]*>)([^<]*)<\/code>/i, function() {
- return arguments[1] + parse(arguments[2], styleSet.ignoreCase) + "</code>"
- });
- parsed = parsed.replace(/\n( *)/g, function() {
- var spaces = "";
- for (var i = 0; i < arguments[1].length; i++) spaces+= "&nbsp;";
- return "\n" + spaces;
- });
- parsed = parsed.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
- parsed = parsed.replace(/\n(<\/\w+>)?/g, "<br />$1").replace(/<br \/>[\n\r\s]*<br \/>/g, "<p><br></p>");
-
- } else parsed = parse(stylableEls[i].innerHTML, styleSet.ignoreCase);
-
- stylableEls[i].innerHTML = parsed;
- }
- }
-
- // run highlighter on all stylesets
- for (var i=0; i < this.styleSets.length; i++) {
- highlightCode(this.styleSets[i]);
- }
-}
diff --git a/railties/guides/assets/javascripts/highlighters.js b/railties/guides/assets/javascripts/highlighters.js
deleted file mode 100644
index 4f5f0779d7..0000000000
--- a/railties/guides/assets/javascripts/highlighters.js
+++ /dev/null
@@ -1,90 +0,0 @@
-CodeHighlighter.addStyle("css", {
- comment : {
- exp : /\/\*[^*]*\*+([^\/][^*]*\*+)*\//
- },
- keywords : {
- exp : /@\w[\w\s]*/
- },
- selectors : {
- exp : "([\\w-:\\[.#][^{};>]*)(?={)"
- },
- properties : {
- exp : "([\\w-]+)(?=\\s*:)"
- },
- units : {
- exp : /([0-9])(em|en|px|%|pt)\b/,
- replacement : "$1<span class=\"$0\">$2</span>"
- },
- urls : {
- exp : /url\([^\)]*\)/
- }
- });
-
-CodeHighlighter.addStyle("ruby",{
- comment : {
- exp : /#[^\n]+/
- },
- brackets : {
- exp : /\(|\)/
- },
- string : {
- exp : /'[^']*'|"[^"]*"/
- },
- keywords : {
- exp : /\b(do|end|self|class|def|if|module|yield|then|else|for|until|unless|while|elsif|case|when|break|retry|redo|rescue|require|raise)\b/
- },
- /* Added by Shelly Fisher (shelly@agileevolved.com) */
- symbol : {
- exp : /([^:])(:[A-Za-z0-9_!?]+)/
- },
- ivar : {
- exp : /\@[A-Za-z0-9_!?]+/
- }
-});
-
-CodeHighlighter.addStyle("html", {
- comment : {
- exp: /&lt;!\s*(--([^-]|[\r\n]|-[^-])*--\s*)&gt;/
- },
- tag : {
- exp: /(&lt;\/?)([a-zA-Z1-9]+\s?)/,
- replacement: "$1<span class=\"$0\">$2</span>"
- },
- string : {
- exp : /'[^']*'|"[^"]*"/
- },
- attribute : {
- exp: /\b([a-zA-Z-:]+)(=)/,
- replacement: "<span class=\"$0\">$1</span>$2"
- },
- doctype : {
- exp: /&lt;!DOCTYPE([^&]|&[^g]|&g[^t])*&gt;/
- }
-});
-
-CodeHighlighter.addStyle("javascript",{
- comment : {
- exp : /(\/\/[^\n]*(\n|$))|(\/\*[^*]*\*+([^\/][^*]*\*+)*\/)/
- },
- brackets : {
- exp : /\(|\)/
- },
- string : {
- exp : /'[^']*'|"[^"]*"/
- },
- keywords : {
- exp : /\b(arguments|break|case|continue|default|delete|do|else|false|for|function|if|in|instanceof|new|null|return|switch|this|true|typeof|var|void|while|with)\b/
- },
- global : {
- exp : /\b(toString|valueOf|window|element|prototype|constructor|document|escape|unescape|parseInt|parseFloat|setTimeout|clearTimeout|setInterval|clearInterval|NaN|isNaN|Infinity)\b/
- }
-});
-
-CodeHighlighter.addStyle("yaml", {
- keyword : {
- exp : /\/\*[^*]*\*+([^\/][^*]*\*+)*\//
- },
- value : {
- exp : /@\w[\w\s]*/
- },
-});
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js
new file mode 100644
index 0000000000..8aa3ed2732
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js
new file mode 100644
index 0000000000..d40bbd7dd2
--- /dev/null
+++ b/railties/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|end) )?if|else|(end )?(script|tell|try)|(on )?error|(put )?into|(of )?(it|me)|its|my|with (timeout( of)?|transaction)|end (timeout|transaction))\b/g,
+ 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) )?window|with (data|icon( (caution|note|stop))?|parameter(s)?|prompt|properties|seed|title)|case|diacriticals|hyphens|numeric strings|punctuation|white space|folder creation|application(s( folder)?| (processes|scripts position|support))?|((desktop )?(pictures )?|(documents|downloads|favorites|home|keychain|library|movies|music|public|scripts|sites|system|users|utilities|workflows) )folder|desktop|Folder Action scripts|font(s| panel)?|help|internet plugins|modem scripts|(system )?preferences|printer descriptions|scripting (additions|components)|shared (documents|libraries)|startup (disk|items)|temporary items|trash|on server|in AppleTalk zone|((as|long|short) )?user name|user (ID|locale)|(with )?password|in (bundle( with identifier)?|directory)|(close|open for) access|read|write( permission)?|(g|s)et eof|using( delimiters)?|starting at|default (answer|button|color|country code|entr(y|ies)|identifiers|items|name|location|script editor)|hidden( answer)?|open(ed| (location|untitled))?|error (handling|reporting)|(do( shell)?|load|run|store) script|administrator privileges|altering line endings|get volume settings|(alert|boot|input|mount|output|set) volume|output muted|(fax|random )?number|round(ing)?|up|down|toward zero|to nearest|as taught in school|system (attribute|info)|((AppleScript( Studio)?|system) )?version|(home )?directory|(IPv4|primary Ethernet) address|CPU (type|speed)|physical memory|time (stamp|to GMT)|replacing|ASCII (character|number)|localized string|from table|offset|summarize|beep|delay|say|(empty|multiple) selections allowed|(of|preferred) type|invisibles|showing( package contents)?|editable URL|(File|FTP|News|Media|Web) [Ss]ervers|Telnet hosts|Directory services|Remote applications|waiting until completion|saving( (in|to))?|path (for|to( (((current|frontmost) )?application|resource))?)|POSIX (file|path)|(background|RGB) color|(OK|cancel) button name|cancel button|button(s)?|cubic ((centi)?met(re|er)s|yards|feet|inches)|square ((kilo)?met(re|er)s|miles|yards|feet)|(centi|kilo)?met(re|er)s|miles|yards|feet|inches|lit(re|er)s|gallons|quarts|(kilo)?grams|ounces|pounds|degrees (Celsius|Fahrenheit|Kelvin)|print( (dialog|settings))?|clos(e(able)?|ing)|(de)?miniaturized|miniaturizable|zoom(ed|able)|attribute run|action (method|property|title)|phone|email|((start|end)ing|home) page|((birth|creation|current|custom|modification) )?date|((((phonetic )?(first|last|middle))|computer|host|maiden|related) |nick)?name|aim|icq|jabber|msn|yahoo|address(es)?|save addressbook|should enable action|city|country( code)?|formatte(r|d address)|(palette )?label|state|street|zip|AIM [Hh]andle(s)?|my card|select(ion| all)?|unsaved|(alpha )?value|entr(y|ies)|group|(ICQ|Jabber|MSN) handle|person|people|company|department|icon image|job title|note|organization|suffix|vcard|url|copies|collating|pages (across|down)|request print time|target( printer)?|((GUI Scripting|Script menu) )?enabled|show Computer scripts|(de)?activated|awake from nib|became (key|main)|call method|of (class|object)|center|clicked toolbar item|closed|for document|exposed|(can )?hide|idle|keyboard (down|up)|event( (number|type))?|launch(ed)?|load (image|movie|nib|sound)|owner|log|mouse (down|dragged|entered|exited|moved|up)|move|column|localization|resource|script|register|drag (info|types)|resigned (active|key|main)|resiz(e(d)?|able)|right mouse (down|dragged|up)|scroll wheel|(at )?index|should (close|open( untitled)?|quit( after last window closed)?|zoom)|((proposed|screen) )?bounds|show(n)?|behind|in front of|size (mode|to fit)|update(d| toolbar item)?|was (hidden|miniaturized)|will (become active|close|finish launching|hide|miniaturize|move|open|quit|(resign )?active|((maximum|minimum|proposed) )?size|show|zoom)|bundle|data source|movie|pasteboard|sound|tool(bar| tip)|(color|open|save) panel|coordinate system|frontmost|main( (bundle|menu|window))?|((services|(excluded from )?windows) )?menu|((executable|frameworks|resource|scripts|shared (frameworks|support)) )?path|(selected item )?identifier|data|content(s| view)?|character(s)?|click count|(command|control|option|shift) key down|context|delta (x|y|z)|key( code)?|location|pressure|unmodified characters|types|(first )?responder|playing|(allowed|selectable) identifiers|allows customization|(auto saves )?configuration|visible|image( name)?|menu form representation|tag|user(-| )defaults|associated file name|(auto|needs) display|current field editor|floating|has (resize indicator|shadow)|hides when deactivated|level|minimized (image|title)|opaque|position|release when closed|sheet|title(d)?)\b/g,
+ 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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js
new file mode 100644
index 0000000000..8c296969ff
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js
new file mode 100644
index 0000000000..079214efe1
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js
new file mode 100644
index 0000000000..627dbb9b76
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js
new file mode 100644
index 0000000000..9f70d3aed6
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js
new file mode 100644
index 0000000000..4297a9a648
--- /dev/null
+++ b/railties/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: /(&lt;|<)\s*style.*?(&gt;|>)/gi,
+ right: /(&lt;|<)\/\s*style\s*(&gt;|>)/gi
+ });
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['css'];
+
+ SyntaxHighlighter.brushes.CSS = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js
new file mode 100644
index 0000000000..e1060d4468
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js
new file mode 100644
index 0000000000..e9b14fc580
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js
new file mode 100644
index 0000000000..6ba7d9da87
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js
new file mode 100644
index 0000000000..6ec5c18521
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js
new file mode 100644
index 0000000000..ff98daba16
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js
new file mode 100644
index 0000000000..d692fd6382
--- /dev/null
+++ b/railties/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 : /(&lt;|<)%[@!=]?/g,
+ right : /%(&gt;|>)/g
+ });
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['java'];
+
+ SyntaxHighlighter.brushes.Java = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js
new file mode 100644
index 0000000000..1a150a6ad3
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js
new file mode 100644
index 0000000000..d94a2e0ec5
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js
new file mode 100644
index 0000000000..95e6e4325b
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js
new file mode 100644
index 0000000000..9f7d9e90c3
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js
new file mode 100644
index 0000000000..0be1752968
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js
new file mode 100644
index 0000000000..ce77462975
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js
new file mode 100644
index 0000000000..ff82130a7a
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js
new file mode 100644
index 0000000000..aa04da0996
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js
new file mode 100644
index 0000000000..4b0b6f04d2
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js
new file mode 100644
index 0000000000..5c2cd8806f
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js
new file mode 100644
index 0000000000..be845dc0b3
--- /dev/null
+++ b/railties/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/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js
new file mode 100644
index 0000000000..69d9fd0b1f
--- /dev/null
+++ b/railties/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('(&lt;|<)[\\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('(\\&lt;|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\&gt;|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]>
+ { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... -->
+ { regex: new XRegExp('(&lt;|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(&gt;|>)', '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/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js b/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js
new file mode 100644
index 0000000000..b47b645472
--- /dev/null
+++ b/railties/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}6 t(f){H(f.1J?"g":"")+(f.4s?"i":"")+(f.4p?"m":"")+(f.4v?"x":"")+(f.3n?"y":"")}6 B(f,e,a,b){K c=u.L,d,h,g;v=R;5K{O(;c--;){g=u[c];I(a&g.3r&&(!g.2p||g.2p.W(b))){g.2q.12=e;I((h=g.2q.X(f))&&h.P===e){d={3k:g.2b.W(b,h,a),1C:h};1N}}}}5v(i){1S i}5q{v=11}H d}6 p(f,e,a){I(3b.Z.1i)H f.1i(e,a);O(a=a||0;a<f.L;a++)I(f[a]===e)H a;H-1}M=6(f,e){K a=[],b=M.1B,c=0,d,h;I(M.1R(f)){I(e!==1d)1S 3m("2a\'t 5r 5I 5F 5B 5C 15 5E 5p");H r(f)}I(v)1S 2U("2a\'t W 3l M 59 5m 5g 5x 5i");e=e||"";O(d={2N:11,19:[],2K:6(g){H e.1i(g)>-1},3d:6(g){e+=g}};c<f.L;)I(h=B(f,c,b,d)){a.U(h.3k);c+=h.1C[0].L||1}Y I(h=n.X.W(z[b],f.1a(c))){a.U(h[0]);c+=h[0].L}Y{h=f.3a(c);I(h==="[")b=M.2I;Y I(h==="]")b=M.1B;a.U(h);c++}a=15(a.1K(""),n.Q.W(e,w,""));a.1w={1m:f,19:d.2N?d.19:N};H a};M.3v="1.5.0";M.2I=1;M.1B=2;K C=/\\$(?:(\\d\\d?|[$&`\'])|{([$\\w]+)})/g,w=/[^5h]+|([\\s\\S])(?=[\\s\\S]*\\1)/g,A=/^(?:[?*+]|{\\d+(?:,\\d*)?})\\??/,v=11,u=[],n={X:15.Z.X,1A:15.Z.1A,1C:1r.Z.1C,Q:1r.Z.Q,1e:1r.Z.1e},x=n.X.W(/()??/,"")[1]===1d,D=6(){K f=/^/g;n.1A.W(f,"");H!f.12}(),y=6(){K f=/x/g;n.Q.W("x",f,"");H!f.12}(),E=15.Z.3n!==1d,z={};z[M.2I]=/^(?:\\\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S]))/;z[M.1B]=/^(?:\\\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\\d*|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S])|\\(\\?[:=!]|[?*+]\\?|{\\d+(?:,\\d*)?}\\??)/;M.1h=6(f,e,a,b){u.U({2q:r(f,"g"+(E?"y":"")),2b:e,3r:a||M.1B,2p:b||N})};M.2n=6(f,e){K a=f+"/"+(e||"");H M.2n[a]||(M.2n[a]=M(f,e))};M.3c=6(f){H r(f,"g")};M.5l=6(f){H f.Q(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&")};M.5e=6(f,e,a,b){e=r(e,"g"+(b&&E?"y":""));e.12=a=a||0;f=e.X(f);H b?f&&f.P===a?f:N:f};M.3q=6(){M.1h=6(){1S 2U("2a\'t 55 1h 54 3q")}};M.1R=6(f){H 53.Z.1q.W(f)==="[2m 15]"};M.3p=6(f,e,a,b){O(K c=r(e,"g"),d=-1,h;h=c.X(f);){a.W(b,h,++d,f,c);c.12===h.P&&c.12++}I(e.1J)e.12=0};M.57=6(f,e){H 6 a(b,c){K d=e[c].1I?e[c]:{1I:e[c]},h=r(d.1I,"g"),g=[],i;O(i=0;i<b.L;i++)M.3p(b[i],h,6(k){g.U(d.3j?k[d.3j]||"":k[0])});H c===e.L-1||!g.L?g:a(g,c+1)}([f],0)};15.Z.1p=6(f,e){H J.X(e[0])};15.Z.W=6(f,e){H J.X(e)};15.Z.X=6(f){K e=n.X.1p(J,14),a;I(e){I(!x&&e.L>1&&p(e,"")>-1){a=15(J.1m,n.Q.W(t(J),"g",""));n.Q.W(f.1a(e.P),a,6(){O(K c=1;c<14.L-2;c++)I(14[c]===1d)e[c]=1d})}I(J.1w&&J.1w.19)O(K b=1;b<e.L;b++)I(a=J.1w.19[b-1])e[a]=e[b];!D&&J.1J&&!e[0].L&&J.12>e.P&&J.12--}H e};I(!D)15.Z.1A=6(f){(f=n.X.W(J,f))&&J.1J&&!f[0].L&&J.12>f.P&&J.12--;H!!f};1r.Z.1C=6(f){M.1R(f)||(f=15(f));I(f.1J){K e=n.1C.1p(J,14);f.12=0;H e}H f.X(J)};1r.Z.Q=6(f,e){K a=M.1R(f),b,c;I(a&&1j e.58()==="3f"&&e.1i("${")===-1&&y)H n.Q.1p(J,14);I(a){I(f.1w)b=f.1w.19}Y f+="";I(1j e==="6")c=n.Q.W(J,f,6(){I(b){14[0]=1f 1r(14[0]);O(K d=0;d<b.L;d++)I(b[d])14[0][b[d]]=14[d+1]}I(a&&f.1J)f.12=14[14.L-2]+14[0].L;H e.1p(N,14)});Y{c=J+"";c=n.Q.W(c,f,6(){K d=14;H n.Q.W(e,C,6(h,g,i){I(g)5b(g){24"$":H"$";24"&":H d[0];24"`":H d[d.L-1].1a(0,d[d.L-2]);24"\'":H d[d.L-1].1a(d[d.L-2]+d[0].L);5a:i="";g=+g;I(!g)H h;O(;g>d.L-3;){i=1r.Z.1a.W(g,-1)+i;g=1Q.3i(g/10)}H(g?d[g]||"":"$")+i}Y{g=+i;I(g<=d.L-3)H d[g];g=b?p(b,i):-1;H g>-1?d[g+1]:h}})})}I(a&&f.1J)f.12=0;H c};1r.Z.1e=6(f,e){I(!M.1R(f))H n.1e.1p(J,14);K a=J+"",b=[],c=0,d,h;I(e===1d||+e<0)e=5D;Y{e=1Q.3i(+e);I(!e)H[]}O(f=M.3c(f);d=f.X(a);){I(f.12>c){b.U(a.1a(c,d.P));d.L>1&&d.P<a.L&&3b.Z.U.1p(b,d.1a(1));h=d[0].L;c=f.12;I(b.L>=e)1N}f.12===d.P&&f.12++}I(c===a.L){I(!n.1A.W(f,"")||h)b.U("")}Y b.U(a.1a(c));H b.L>e?b.1a(0,e):b};M.1h(/\\(\\?#[^)]*\\)/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"});M.1h(/\\((?!\\?)/,6(){J.19.U(N);H"("});M.1h(/\\(\\?<([$\\w]+)>/,6(f){J.19.U(f[1]);J.2N=R;H"("});M.1h(/\\\\k<([\\w$]+)>/,6(f){K e=p(J.19,f[1]);H e>-1?"\\\\"+(e+1)+(3R(f.2S.3a(f.P+f[0].L))?"":"(?:)"):f[0]});M.1h(/\\[\\^?]/,6(f){H f[0]==="[]"?"\\\\b\\\\B":"[\\\\s\\\\S]"});M.1h(/^\\(\\?([5A]+)\\)/,6(f){J.3d(f[1]);H""});M.1h(/(?:\\s+|#.*)+/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"},M.1B,6(){H J.2K("x")});M.1h(/\\./,6(){H"[\\\\s\\\\S]"},M.1B,6(){H J.2K("s")})})();1j 2e!="1d"&&(2e.M=M);K 1v=6(){6 r(a,b){a.1l.1i(b)!=-1||(a.1l+=" "+b)}6 t(a){H a.1i("3e")==0?a:"3e"+a}6 B(a){H e.1Y.2A[t(a)]}6 p(a,b,c){I(a==N)H N;K d=c!=R?a.3G:[a.2G],h={"#":"1c",".":"1l"}[b.1o(0,1)]||"3h",g,i;g=h!="3h"?b.1o(1):b.5u();I((a[h]||"").1i(g)!=-1)H a;O(a=0;d&&a<d.L&&i==N;a++)i=p(d[a],b,c);H i}6 C(a,b){K c={},d;O(d 2g a)c[d]=a[d];O(d 2g b)c[d]=b[d];H c}6 w(a,b,c,d){6 h(g){g=g||1P.5y;I(!g.1F){g.1F=g.52;g.3N=6(){J.5w=11}}c.W(d||1P,g)}a.3g?a.3g("4U"+b,h):a.4y(b,h,11)}6 A(a,b){K c=e.1Y.2j,d=N;I(c==N){c={};O(K h 2g e.1U){K g=e.1U[h];d=g.4x;I(d!=N){g.1V=h.4w();O(g=0;g<d.L;g++)c[d[g]]=h}}e.1Y.2j=c}d=e.1U[c[a]];d==N&&b!=11&&1P.1X(e.13.1x.1X+(e.13.1x.3E+a));H d}6 v(a,b){O(K c=a.1e("\\n"),d=0;d<c.L;d++)c[d]=b(c[d],d);H c.1K("\\n")}6 u(a,b){I(a==N||a.L==0||a=="\\n")H a;a=a.Q(/</g,"&1y;");a=a.Q(/ {2,}/g,6(c){O(K d="",h=0;h<c.L-1;h++)d+=e.13.1W;H d+" "});I(b!=N)a=v(a,6(c){I(c.L==0)H"";K d="";c=c.Q(/^(&2s;| )+/,6(h){d=h;H""});I(c.L==0)H d;H d+\'<17 1g="\'+b+\'">\'+c+"</17>"});H a}6 n(a,b){a.1e("\\n");O(K c="",d=0;d<50;d++)c+=" ";H a=v(a,6(h){I(h.1i("\\t")==-1)H h;O(K g=0;(g=h.1i("\\t"))!=-1;)h=h.1o(0,g)+c.1o(0,b-g%b)+h.1o(g+1,h.L);H h})}6 x(a){H a.Q(/^\\s+|\\s+$/g,"")}6 D(a,b){I(a.P<b.P)H-1;Y I(a.P>b.P)H 1;Y I(a.L<b.L)H-1;Y I(a.L>b.L)H 1;H 0}6 y(a,b){6 c(k){H k[0]}O(K d=N,h=[],g=b.2D?b.2D:c;(d=b.1I.X(a))!=N;){K i=g(d,b);I(1j i=="3f")i=[1f e.2L(i,d.P,b.23)];h=h.1O(i)}H h}6 E(a){K b=/(.*)((&1G;|&1y;).*)/;H a.Q(e.3A.3M,6(c){K d="",h=N;I(h=b.X(c)){c=h[1];d=h[2]}H\'<a 2h="\'+c+\'">\'+c+"</a>"+d})}6 z(){O(K a=1E.36("1k"),b=[],c=0;c<a.L;c++)a[c].3s=="20"&&b.U(a[c]);H b}6 f(a){a=a.1F;K b=p(a,".20",R);a=p(a,".3O",R);K c=1E.4i("3t");I(!(!a||!b||p(a,"3t"))){B(b.1c);r(b,"1m");O(K d=a.3G,h=[],g=0;g<d.L;g++)h.U(d[g].4z||d[g].4A);h=h.1K("\\r");c.39(1E.4D(h));a.39(c);c.2C();c.4C();w(c,"4u",6(){c.2G.4E(c);b.1l=b.1l.Q("1m","")})}}I(1j 3F!="1d"&&1j M=="1d")M=3F("M").M;K e={2v:{"1g-27":"","2i-1s":1,"2z-1s-2t":11,1M:N,1t:N,"42-45":R,"43-22":4,1u:R,16:R,"3V-17":R,2l:11,"41-40":R,2k:11,"1z-1k":11},13:{1W:"&2s;",2M:R,46:11,44:11,34:"4n",1x:{21:"4o 1m",2P:"?",1X:"1v\\n\\n",3E:"4r\'t 4t 1D O: ",4g:"4m 4B\'t 51 O 1z-1k 4F: ",37:\'<!4T 1z 4S "-//4V//3H 4W 1.0 4Z//4Y" "1Z://2y.3L.3K/4X/3I/3H/3I-4P.4J"><1z 4I="1Z://2y.3L.3K/4L/5L"><3J><4N 1Z-4M="5G-5M" 6K="2O/1z; 6J=6I-8" /><1t>6L 1v</1t></3J><3B 1L="25-6M:6Q,6P,6O,6N-6F;6y-2f:#6x;2f:#6w;25-22:6v;2O-3D:3C;"><T 1L="2O-3D:3C;3w-32:1.6z;"><T 1L="25-22:6A-6E;">1v</T><T 1L="25-22:.6C;3w-6B:6R;"><T>3v 3.0.76 (72 73 3x)</T><T><a 2h="1Z://3u.2w/1v" 1F="38" 1L="2f:#3y">1Z://3u.2w/1v</a></T><T>70 17 6U 71.</T><T>6T 6X-3x 6Y 6D.</T></T><T>6t 61 60 J 1k, 5Z <a 2h="6u://2y.62.2w/63-66/65?64=5X-5W&5P=5O" 1L="2f:#3y">5R</a> 5V <2R/>5U 5T 5S!</T></T></3B></1z>\'}},1Y:{2j:N,2A:{}},1U:{},3A:{6n:/\\/\\*[\\s\\S]*?\\*\\//2c,6m:/\\/\\/.*$/2c,6l:/#.*$/2c,6k:/"([^\\\\"\\n]|\\\\.)*"/g,6o:/\'([^\\\\\'\\n]|\\\\.)*\'/g,6p:1f M(\'"([^\\\\\\\\"]|\\\\\\\\.)*"\',"3z"),6s:1f M("\'([^\\\\\\\\\']|\\\\\\\\.)*\'","3z"),6q:/(&1y;|<)!--[\\s\\S]*?--(&1G;|>)/2c,3M:/\\w+:\\/\\/[\\w-.\\/?%&=:@;]*/g,6a:{18:/(&1y;|<)\\?=?/g,1b:/\\?(&1G;|>)/g},69:{18:/(&1y;|<)%=?/g,1b:/%(&1G;|>)/g},6d:{18:/(&1y;|<)\\s*1k.*?(&1G;|>)/2T,1b:/(&1y;|<)\\/\\s*1k\\s*(&1G;|>)/2T}},16:{1H:6(a){6 b(i,k){H e.16.2o(i,k,e.13.1x[k])}O(K c=\'<T 1g="16">\',d=e.16.2x,h=d.2X,g=0;g<h.L;g++)c+=(d[h[g]].1H||b)(a,h[g]);c+="</T>";H c},2o:6(a,b,c){H\'<2W><a 2h="#" 1g="6e 6h\'+b+" "+b+\'">\'+c+"</a></2W>"},2b:6(a){K b=a.1F,c=b.1l||"";b=B(p(b,".20",R).1c);K d=6(h){H(h=15(h+"6f(\\\\w+)").X(c))?h[1]:N}("6g");b&&d&&e.16.2x[d].2B(b);a.3N()},2x:{2X:["21","2P"],21:{1H:6(a){I(a.V("2l")!=R)H"";K b=a.V("1t");H e.16.2o(a,"21",b?b:e.13.1x.21)},2B:6(a){a=1E.6j(t(a.1c));a.1l=a.1l.Q("47","")}},2P:{2B:6(){K a="68=0";a+=", 18="+(31.30-33)/2+", 32="+(31.2Z-2Y)/2+", 30=33, 2Z=2Y";a=a.Q(/^,/,"");a=1P.6Z("","38",a);a.2C();K b=a.1E;b.6W(e.13.1x.37);b.6V();a.2C()}}}},35:6(a,b){K c;I(b)c=[b];Y{c=1E.36(e.13.34);O(K d=[],h=0;h<c.L;h++)d.U(c[h]);c=d}c=c;d=[];I(e.13.2M)c=c.1O(z());I(c.L===0)H d;O(h=0;h<c.L;h++){O(K g=c[h],i=a,k=c[h].1l,j=3W 0,l={},m=1f M("^\\\\[(?<2V>(.*?))\\\\]$"),s=1f M("(?<27>[\\\\w-]+)\\\\s*:\\\\s*(?<1T>[\\\\w-%#]+|\\\\[.*?\\\\]|\\".*?\\"|\'.*?\')\\\\s*;?","g");(j=s.X(k))!=N;){K o=j.1T.Q(/^[\'"]|[\'"]$/g,"");I(o!=N&&m.1A(o)){o=m.X(o);o=o.2V.L>0?o.2V.1e(/\\s*,\\s*/):[]}l[j.27]=o}g={1F:g,1n:C(i,l)};g.1n.1D!=N&&d.U(g)}H d},1M:6(a,b){K c=J.35(a,b),d=N,h=e.13;I(c.L!==0)O(K g=0;g<c.L;g++){b=c[g];K i=b.1F,k=b.1n,j=k.1D,l;I(j!=N){I(k["1z-1k"]=="R"||e.2v["1z-1k"]==R){d=1f e.4l(j);j="4O"}Y I(d=A(j))d=1f d;Y 6H;l=i.3X;I(h.2M){l=l;K m=x(l),s=11;I(m.1i("<![6G[")==0){m=m.4h(9);s=R}K o=m.L;I(m.1i("]]\\>")==o-3){m=m.4h(0,o-3);s=R}l=s?m:l}I((i.1t||"")!="")k.1t=i.1t;k.1D=j;d.2Q(k);b=d.2F(l);I((i.1c||"")!="")b.1c=i.1c;i.2G.74(b,i)}}},2E:6(a){w(1P,"4k",6(){e.1M(a)})}};e.2E=e.2E;e.1M=e.1M;e.2L=6(a,b,c){J.1T=a;J.P=b;J.L=a.L;J.23=c;J.1V=N};e.2L.Z.1q=6(){H J.1T};e.4l=6(a){6 b(j,l){O(K m=0;m<j.L;m++)j[m].P+=l}K c=A(a),d,h=1f e.1U.5Y,g=J,i="2F 1H 2Q".1e(" ");I(c!=N){d=1f c;O(K k=0;k<i.L;k++)(6(){K j=i[k];g[j]=6(){H h[j].1p(h,14)}})();d.28==N?1P.1X(e.13.1x.1X+(e.13.1x.4g+a)):h.2J.U({1I:d.28.17,2D:6(j){O(K l=j.17,m=[],s=d.2J,o=j.P+j.18.L,F=d.28,q,G=0;G<s.L;G++){q=y(l,s[G]);b(q,o);m=m.1O(q)}I(F.18!=N&&j.18!=N){q=y(j.18,F.18);b(q,j.P);m=m.1O(q)}I(F.1b!=N&&j.1b!=N){q=y(j.1b,F.1b);b(q,j.P+j[0].5Q(j.1b));m=m.1O(q)}O(j=0;j<m.L;j++)m[j].1V=c.1V;H m}})}};e.4j=6(){};e.4j.Z={V:6(a,b){K c=J.1n[a];c=c==N?b:c;K d={"R":R,"11":11}[c];H d==N?c:d},3Y:6(a){H 1E.4i(a)},4c:6(a,b){K c=[];I(a!=N)O(K d=0;d<a.L;d++)I(1j a[d]=="2m")c=c.1O(y(b,a[d]));H J.4e(c.6b(D))},4e:6(a){O(K b=0;b<a.L;b++)I(a[b]!==N)O(K c=a[b],d=c.P+c.L,h=b+1;h<a.L&&a[b]!==N;h++){K g=a[h];I(g!==N)I(g.P>d)1N;Y I(g.P==c.P&&g.L>c.L)a[b]=N;Y I(g.P>=c.P&&g.P<d)a[h]=N}H a},4d:6(a){K b=[],c=2u(J.V("2i-1s"));v(a,6(d,h){b.U(h+c)});H b},3U:6(a){K b=J.V("1M",[]);I(1j b!="2m"&&b.U==N)b=[b];a:{a=a.1q();K c=3W 0;O(c=c=1Q.6c(c||0,0);c<b.L;c++)I(b[c]==a){b=c;1N a}b=-1}H b!=-1},2r:6(a,b,c){a=["1s","6i"+b,"P"+a,"6r"+(b%2==0?1:2).1q()];J.3U(b)&&a.U("67");b==0&&a.U("1N");H\'<T 1g="\'+a.1K(" ")+\'">\'+c+"</T>"},3Q:6(a,b){K c="",d=a.1e("\\n").L,h=2u(J.V("2i-1s")),g=J.V("2z-1s-2t");I(g==R)g=(h+d-1).1q().L;Y I(3R(g)==R)g=0;O(K i=0;i<d;i++){K k=b?b[i]:h+i,j;I(k==0)j=e.13.1W;Y{j=g;O(K l=k.1q();l.L<j;)l="0"+l;j=l}a=j;c+=J.2r(i,k,a)}H c},49:6(a,b){a=x(a);K c=a.1e("\\n");J.V("2z-1s-2t");K d=2u(J.V("2i-1s"));a="";O(K h=J.V("1D"),g=0;g<c.L;g++){K i=c[g],k=/^(&2s;|\\s)+/.X(i),j=N,l=b?b[g]:d+g;I(k!=N){j=k[0].1q();i=i.1o(j.L);j=j.Q(" ",e.13.1W)}i=x(i);I(i.L==0)i=e.13.1W;a+=J.2r(g,l,(j!=N?\'<17 1g="\'+h+\' 5N">\'+j+"</17>":"")+i)}H a},4f:6(a){H a?"<4a>"+a+"</4a>":""},4b:6(a,b){6 c(l){H(l=l?l.1V||g:g)?l+" ":""}O(K d=0,h="",g=J.V("1D",""),i=0;i<b.L;i++){K k=b[i],j;I(!(k===N||k.L===0)){j=c(k);h+=u(a.1o(d,k.P-d),j+"48")+u(k.1T,j+k.23);d=k.P+k.L+(k.75||0)}}h+=u(a.1o(d),c()+"48");H h},1H:6(a){K b="",c=["20"],d;I(J.V("2k")==R)J.1n.16=J.1n.1u=11;1l="20";J.V("2l")==R&&c.U("47");I((1u=J.V("1u"))==11)c.U("6S");c.U(J.V("1g-27"));c.U(J.V("1D"));a=a.Q(/^[ ]*[\\n]+|[\\n]*[ ]*$/g,"").Q(/\\r/g," ");b=J.V("43-22");I(J.V("42-45")==R)a=n(a,b);Y{O(K h="",g=0;g<b;g++)h+=" ";a=a.Q(/\\t/g,h)}a=a;a:{b=a=a;h=/<2R\\s*\\/?>|&1y;2R\\s*\\/?&1G;/2T;I(e.13.46==R)b=b.Q(h,"\\n");I(e.13.44==R)b=b.Q(h,"");b=b.1e("\\n");h=/^\\s*/;g=4Q;O(K i=0;i<b.L&&g>0;i++){K k=b[i];I(x(k).L!=0){k=h.X(k);I(k==N){a=a;1N a}g=1Q.4q(k[0].L,g)}}I(g>0)O(i=0;i<b.L;i++)b[i]=b[i].1o(g);a=b.1K("\\n")}I(1u)d=J.4d(a);b=J.4c(J.2J,a);b=J.4b(a,b);b=J.49(b,d);I(J.V("41-40"))b=E(b);1j 2H!="1d"&&2H.3S&&2H.3S.1C(/5s/)&&c.U("5t");H b=\'<T 1c="\'+t(J.1c)+\'" 1g="\'+c.1K(" ")+\'">\'+(J.V("16")?e.16.1H(J):"")+\'<3Z 5z="0" 5H="0" 5J="0">\'+J.4f(J.V("1t"))+"<3T><3P>"+(1u?\'<2d 1g="1u">\'+J.3Q(a)+"</2d>":"")+\'<2d 1g="17"><T 1g="3O">\'+b+"</T></2d></3P></3T></3Z></T>"},2F:6(a){I(a===N)a="";J.17=a;K b=J.3Y("T");b.3X=J.1H(a);J.V("16")&&w(p(b,".16"),"5c",e.16.2b);J.V("3V-17")&&w(p(b,".17"),"56",f);H b},2Q:6(a){J.1c=""+1Q.5d(1Q.5n()*5k).1q();e.1Y.2A[t(J.1c)]=J;J.1n=C(e.2v,a||{});I(J.V("2k")==R)J.1n.16=J.1n.1u=11},5j:6(a){a=a.Q(/^\\s+|\\s+$/g,"").Q(/\\s+/g,"|");H"\\\\b(?:"+a+")\\\\b"},5f:6(a){J.28={18:{1I:a.18,23:"1k"},1b:{1I:a.1b,23:"1k"},17:1f M("(?<18>"+a.18.1m+")(?<17>.*?)(?<1b>"+a.1b.1m+")","5o")}}};H e}();1j 2e!="1d"&&(2e.1v=1v);',62,441,'||||||function|||||||||||||||||||||||||||||||||||||return|if|this|var|length|XRegExp|null|for|index|replace|true||div|push|getParam|call|exec|else|prototype||false|lastIndex|config|arguments|RegExp|toolbar|code|left|captureNames|slice|right|id|undefined|split|new|class|addToken|indexOf|typeof|script|className|source|params|substr|apply|toString|String|line|title|gutter|SyntaxHighlighter|_xregexp|strings|lt|html|test|OUTSIDE_CLASS|match|brush|document|target|gt|getHtml|regex|global|join|style|highlight|break|concat|window|Math|isRegExp|throw|value|brushes|brushName|space|alert|vars|http|syntaxhighlighter|expandSource|size|css|case|font|Fa|name|htmlScript|dA|can|handler|gm|td|exports|color|in|href|first|discoveredBrushes|light|collapse|object|cache|getButtonHtml|trigger|pattern|getLineHtml|nbsp|numbers|parseInt|defaults|com|items|www|pad|highlighters|execute|focus|func|all|getDiv|parentNode|navigator|INSIDE_CLASS|regexList|hasFlag|Match|useScriptTags|hasNamedCapture|text|help|init|br|input|gi|Error|values|span|list|250|height|width|screen|top|500|tagName|findElements|getElementsByTagName|aboutDialog|_blank|appendChild|charAt|Array|copyAsGlobal|setFlag|highlighter_|string|attachEvent|nodeName|floor|backref|output|the|TypeError|sticky|Za|iterate|freezeTokens|scope|type|textarea|alexgorbatchev|version|margin|2010|005896|gs|regexLib|body|center|align|noBrush|require|childNodes|DTD|xhtml1|head|org|w3|url|preventDefault|container|tr|getLineNumbersHtml|isNaN|userAgent|tbody|isLineHighlighted|quick|void|innerHTML|create|table|links|auto|smart|tab|stripBrs|tabs|bloggerMode|collapsed|plain|getCodeLinesHtml|caption|getMatchesHtml|findMatches|figureOutLineNumbers|removeNestedMatches|getTitleHtml|brushNotHtmlScript|substring|createElement|Highlighter|load|HtmlScript|Brush|pre|expand|multiline|min|Can|ignoreCase|find|blur|extended|toLowerCase|aliases|addEventListener|innerText|textContent|wasn|select|createTextNode|removeChild|option|same|frame|xmlns|dtd|twice|1999|equiv|meta|htmlscript|transitional|1E3|expected|PUBLIC|DOCTYPE|on|W3C|XHTML|TR|EN|Transitional||configured|srcElement|Object|after|run|dblclick|matchChain|valueOf|constructor|default|switch|click|round|execAt|forHtmlScript|token|gimy|functions|getKeywords|1E6|escape|within|random|sgi|another|finally|supply|MSIE|ie|toUpperCase|catch|returnValue|definition|event|border|imsx|constructing|one|Infinity|from|when|Content|cellpadding|flags|cellspacing|try|xhtml|Type|spaces|2930402|hosted_button_id|lastIndexOf|donate|active|development|keep|to|xclick|_s|Xml|please|like|you|paypal|cgi|cmd|webscr|bin|highlighted|scrollbars|aspScriptTags|phpScriptTags|sort|max|scriptScriptTags|toolbar_item|_|command|command_|number|getElementById|doubleQuotedString|singleLinePerlComments|singleLineCComments|multiLineCComments|singleQuotedString|multiLineDoubleQuotedString|xmlComments|alt|multiLineSingleQuotedString|If|https|1em|000|fff|background|5em|xx|bottom|75em|Gorbatchev|large|serif|CDATA|continue|utf|charset|content|About|family|sans|Helvetica|Arial|Geneva|3em|nogutter|Copyright|syntax|close|write|2004|Alex|open|JavaScript|highlighter|July|02|replaceChild|offset|83'.split('|'),0,{}))
diff --git a/railties/guides/assets/stylesheets/fixes.css b/railties/guides/assets/stylesheets/fixes.css
new file mode 100644
index 0000000000..54efa5b9b7
--- /dev/null
+++ b/railties/guides/assets/stylesheets/fixes.css
@@ -0,0 +1,16 @@
+/*
+ Fix a rendering issue affecting WebKits on Mac.
+ See https://github.com/lifo/docrails/issues#issue/16 for more information.
+*/
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ line-height: 1.2em !important;
+}
diff --git a/railties/guides/assets/stylesheets/main.css b/railties/guides/assets/stylesheets/main.css
index bab0b7a9d9..cf6e9e5cc8 100644
--- a/railties/guides/assets/stylesheets/main.css
+++ b/railties/guides/assets/stylesheets/main.css
@@ -22,9 +22,13 @@ ol { list-style-type: decimal; }
dl { margin: 0 0 1.5em 0; }
dl dt { font-weight: bold; }
dd { margin-left: 1.5em;}
-
-pre,code { margin: 1.5em 0; white-space: pre; overflow: auto; }
-pre,code,tt { font: 1em 'andale mono', 'lucida console', monospace; line-height: 1.5; }
+
+pre,code { margin: 1.5em 0; overflow: auto; color: #222;}
+pre,code,tt {
+ font-size: 1em;
+ font-family: "Anonymous Pro", "Inconsolata", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace;
+ line-height: 1.5;
+}
abbr, acronym { border-bottom: 1px dotted #666; }
address { margin: 0 0 1.5em; font-style: italic; }
@@ -53,7 +57,7 @@ table {
background: #FFF;
border-collapse: collapse;
}
-
+
table th, table td {
padding: 0.25em 1em;
border: 1px solid #CCC;
@@ -76,7 +80,7 @@ body {
font-family: Helvetica, Arial, sans-serif;
font-size: 87.5%;
line-height: 1.5em;
- background: #222;
+ background: #222;
color: #999;
}
@@ -114,7 +118,7 @@ body {
#mainCol {
width: 45em;
margin-left: 2em;
- }
+ }
#subCol {
position: absolute;
@@ -127,7 +131,7 @@ body {
font-size: 0.9285em;
line-height: 1.3846em;
}
-
+
#extraCol {display: none;}
#footer {
@@ -180,7 +184,7 @@ a, a:link, a:visited {
#header .nav .index a {
background: #980905 url(../images/nav_arrow.gif) no-repeat right top;
- padding-right: 1em;
+ padding-right: 1em;
position: relative;
z-index: 15;
padding-bottom: 0.125em;
@@ -246,7 +250,7 @@ h3 {
margin: 0.875em 0 0.2916em;
font-weight: bold;
}
-
+
h4 {
font-size: 1.2857em;
line-height: 1.2em;
@@ -261,7 +265,7 @@ h5 {
font-weight: bold;
}
-h6 {
+h6 {
font-size: 1em;
line-height: 1.5em;
margin: 1em 0 .5em;
@@ -329,7 +333,7 @@ h6 {
padding: 0.125em 0 0.25em 28px;*/
}
-#mainCol dd.ticket, #subCol dd.ticket {
+#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;
@@ -361,20 +365,9 @@ h6 {
font-weight: normal;
}
-tt {
- font-family: monaco, "Bitstream Vera Sans Mono", "Courier New", courier, monospace;
-}
-
div.code_container {
background: #EEE url(../images/tab_grey.gif) no-repeat left top;
- padding: 0.25em 1em 0.5em 48px;
-}
-
-code {
- font-family: monaco, "Bitstream Vera Sans Mono", "Courier New", courier, monospace;
- border: none;
- margin: 0.25em 0 1.5em 0;
- display: block;
+ padding: 0.25em 1em 0.5em 48px;
}
.note {
@@ -411,15 +404,15 @@ code {
padding: 0 0 1em;
font-size: 1.1667em;
}
-
+
/* Clearing
--------------------------------------- */
.clearfix:after {
- content: ".";
- display: block;
- height: 0;
- clear: both;
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
visibility: hidden;
}
diff --git a/railties/guides/assets/stylesheets/syntax.css b/railties/guides/assets/stylesheets/syntax.css
deleted file mode 100644
index 55fc5b209f..0000000000
--- a/railties/guides/assets/stylesheets/syntax.css
+++ /dev/null
@@ -1,31 +0,0 @@
-.html .tag {
- color : green;
-}
-
-.html .doctype {
- color: #708090;
-}
-
-.erb .tag {
- color : green;
-}
-
-.erb .doctype {
- color: #708090;
-}
-
-.ruby .keywords {
- color : red;
-}
-
-.ruby .ivar {
- color : blue;
-}
-
-.ruby .comment {
- color: #708090;
-}
-
-.ruby .symbol {
- color: green;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css
new file mode 100644
index 0000000000..34f6864a15
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css
new file mode 100644
index 0000000000..08f9e10e4e
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css
new file mode 100644
index 0000000000..1db1f70cb0
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css
new file mode 100644
index 0000000000..a45de9fd8e
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css
new file mode 100644
index 0000000000..706c77a0a8
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css
new file mode 100644
index 0000000000..6101eba51f
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css
new file mode 100644
index 0000000000..2923ce7367
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css
new file mode 100644
index 0000000000..e3733eed56
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css
new file mode 100644
index 0000000000..d09368384d
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css
new file mode 100644
index 0000000000..136541172d
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css
new file mode 100644
index 0000000000..d8b4313433
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css
new file mode 100644
index 0000000000..77377d9533
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css
new file mode 100644
index 0000000000..dae5053fea
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css
new file mode 100644
index 0000000000..8fbd871fb5
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css
new file mode 100755
index 0000000000..f4db39cd83
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css
new file mode 100644
index 0000000000..c49563cc9d
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css
new file mode 100644
index 0000000000..6305a10e4e
--- /dev/null
+++ b/railties/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/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css
new file mode 100644
index 0000000000..6d2edb2eb8
--- /dev/null
+++ b/railties/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/railties/guides/rails_guides.rb b/railties/guides/rails_guides.rb
index dfbb06cc76..feb5fe3937 100644
--- a/railties/guides/rails_guides.rb
+++ b/railties/guides/rails_guides.rb
@@ -24,14 +24,14 @@ rescue LoadError
end
begin
- gem 'RedCloth', '>= 4.1.1'
require 'redcloth'
rescue Gem::LoadError
+ # This can happen if doc:guides is executed in an application.
$stderr.puts('Generating guides requires RedCloth 4.1.1+.')
$stderr.puts(<<ERROR) if bundler?
Please add
- gem 'RedCloth', '>= 4.1.1'
+ gem 'RedCloth', '~> 4.2'
to the Gemfile, run
diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb
index bb7cdb6756..154355cac1 100644
--- a/railties/guides/rails_guides/generator.rb
+++ b/railties/guides/rails_guides/generator.rb
@@ -32,12 +32,16 @@
#
# Separate many using commas:
#
-# # generates only
+# # generates only association_basics.html and migrations.html
# ONLY=assoc,migrations ruby rails_guides.rb
#
# Note that if you are working on a guide generation will by default process
# only that one, so ONLY is rarely used nowadays.
#
+# LANGUAGE
+# Use LANGUAGE when you want to generate translated guides in <tt>source/<LANGUAGE></tt>
+# folder (such as <tt>source/es</tt>). Ignore it when generating English guides.
+#
# EDGE
# Set to "1" to indicate generated guides should be marked as edge. This
# inserts a badge and changes the preamble of the home page.
@@ -63,6 +67,7 @@ module RailsGuides
GUIDES_RE = /\.(?:textile|html\.erb)$/
def initialize(output=nil)
+ @lang = ENV['LANGUAGE']
initialize_dirs(output)
create_output_dir_if_needed
set_flags_from_environment
@@ -76,8 +81,8 @@ module RailsGuides
private
def initialize_dirs(output)
@guides_dir = File.join(File.dirname(__FILE__), '..')
- @source_dir = File.join(@guides_dir, "source")
- @output_dir = output || File.join(@guides_dir, "output")
+ @source_dir = File.join(@guides_dir, "source", @lang.to_s)
+ @output_dir = output || File.join(@guides_dir, "output", @lang.to_s)
end
def create_output_dir_if_needed
@@ -116,7 +121,7 @@ module RailsGuides
def output_file_for(guide)
guide.sub(GUIDES_RE, '.html')
end
-
+
def generate?(source_file, output_file)
fin = File.join(source_dir, source_file)
fout = File.join(output_dir, output_file)
@@ -207,15 +212,33 @@ module RailsGuides
# with code blocks by hand.
def with_workaround_for_notextile(body)
code_blocks = []
+
body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m|
- es = ERB::Util.h($2)
- css_class = ['erb', 'shell'].include?($1) ? 'html' : $1
- code_blocks << %{<div class="code_container"><code class="#{css_class}">#{es}</code></div>}
+ brush = case $1
+ when 'ruby', 'sql', 'plain'
+ $1
+ when 'erb'
+ 'ruby; html-script: true'
+ when 'html'
+ 'xml' # html is understood, but there are .xml rules in the CSS
+ else
+ 'plain'
+ end
+
+ code_blocks.push(<<HTML)
+<notextile>
+<div class="code_container">
+<pre class="brush: #{brush}; gutter: false; toolbar: false">
+#{ERB::Util.h($2).strip}
+</pre>
+</div>
+</notextile>
+HTML
"\ndirty_workaround_for_notextile_#{code_blocks.size - 1}\n"
end
-
+
body = yield body
-
+
body.gsub(%r{<p>dirty_workaround_for_notextile_(\d+)</p>}) do |_|
code_blocks[$1.to_i]
end
@@ -225,7 +248,7 @@ module RailsGuides
anchors = extract_anchors(html)
check_fragment_identifiers(html, anchors)
end
-
+
def extract_anchors(html)
# Textile generates headers with IDs computed from titles.
anchors = Set.new
@@ -237,11 +260,12 @@ module RailsGuides
end
end
- # Also, footnotes are rendered as paragraphs this way.
+ # 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
diff --git a/railties/guides/rails_guides/helpers.rb b/railties/guides/rails_guides/helpers.rb
index bf99538696..d466c76c7c 100644
--- a/railties/guides/rails_guides/helpers.rb
+++ b/railties/guides/rails_guides/helpers.rb
@@ -4,19 +4,14 @@ module RailsGuides
link = content_tag(:a, :href => url) { name }
result = content_tag(:dt, link)
- if ticket = options[:ticket]
- result << content_tag(:dd, lh(ticket), :class => 'ticket')
+ 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 lh(id, label = "Lighthouse Ticket")
- url = "http://rails.lighthouseapp.com/projects/16213/tickets/#{id}"
- content_tag(:a, label, :href => url)
- end
-
def author(name, nick, image = 'credits_pic_blank.gif', &block)
image = "images/#{image}"
diff --git a/railties/guides/rails_guides/indexer.rb b/railties/guides/rails_guides/indexer.rb
index bd817786ed..fb46491817 100644
--- a/railties/guides/rails_guides/indexer.rb
+++ b/railties/guides/rails_guides/indexer.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/object/blank'
require 'active_support/ordered_hash'
+require 'active_support/core_ext/string/inflections'
module RailsGuides
class Indexer
@@ -58,7 +59,7 @@ module RailsGuides
end
def title_to_idx(title)
- idx = title.strip.downcase.gsub(/\s+|_/, '-').delete('^a-z0-9-').sub(/^[^a-z]*/, '')
+ 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
diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile
index 5628d7e52f..8e2d528eee 100644
--- a/railties/guides/source/2_2_release_notes.textile
+++ b/railties/guides/source/2_2_release_notes.textile
@@ -260,15 +260,15 @@ h4. Other Action Controller Changes
* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
-* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type.
+* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type.
* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+.
h3. Action View
* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code.
-* The included Prototype javascript library has been upgraded to version 1.6.0.3.
-* +RJS#page.reload+ to reload the browser's current location via javascript
+* The included Prototype JavaScript library has been upgraded to version 1.6.0.3.
+* +RJS#page.reload+ to reload the browser's current location via JavaScript
* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions.
h3. Action Mailer
diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile
index f3530c4ddd..67743a4797 100644
--- a/railties/guides/source/2_3_release_notes.textile
+++ b/railties/guides/source/2_3_release_notes.textile
@@ -53,7 +53,7 @@ The "Ruby on Rails guides":http://guides.rubyonrails.org/ project has published
h3. 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.
+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.
h3. Active Record
@@ -77,7 +77,7 @@ Turning on nested attributes enables a number of things: automatic (and atomic)
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,
+accepts_nested_attributes_for :author,
:reject_if => proc { |attributes| attributes['name'].blank? }
</ruby>
@@ -149,7 +149,7 @@ 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+):
+* 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
@@ -278,7 +278,7 @@ Mime::JS =~ "text/javascript" => true
Mime::JS =~ "application/javascript" => true
</ruby>
-The other change is that the framework now uses the +Mime::JS+ when checking for javascript in various spots, making it handle those alternatives cleanly.
+The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly.
* Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons
@@ -449,7 +449,7 @@ returns
<option>joke</option>
<option>poem</option>
<option disabled=“disabled“>private</option>
-</select>
+</select>
</ruby>
You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled:
@@ -502,7 +502,7 @@ The support for XML parsing in ActiveSupport has been made more flexible by allo
XmlMini.backend = 'LibXML'
</ruby>
-* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/
+* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/
* Lead Contributor: "Aaron Patterson":http://tenderlovemaking.com/
h4. Fractional seconds for TimeWithZone
diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile
index 14da650e83..f75b245ed8 100644
--- a/railties/guides/source/3_0_release_notes.textile
+++ b/railties/guides/source/3_0_release_notes.textile
@@ -18,13 +18,11 @@ These release notes cover the major upgrades, but don't include every little bug
endprologue.
-WARNING: Rails 3.0 is currently in beta. This means that there are probably bugs and that you should "report them":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview if you see them. You also may not want to run the NORAD nuclear launch application off a beta version. But if you're starting development on a new application and you don't mind getting wind in your hair, please do jump on board!
-
-To install the last Rails 3 beta:
+To install Rails 3:
<shell>
# Use sudo if your setup requires it
-gem install rails --pre
+$ gem install rails
</shell>
@@ -49,8 +47,8 @@ h4. script/* replaced by script/rails
The new <tt>script/rails</tt> replaces all the scripts that used to be in the <tt>script</tt> directory. You do not run <tt>script/rails</tt> directly though, the +rails+ command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is:
<shell>
-rails console # instead of script/console
-rails g scaffold post title:string # instead of script/generate scaffold post title:string
+$ rails console # instead of script/console
+$ rails g scaffold post title:string # instead of script/generate scaffold post title:string
</shell>
Run <tt>rails --help</tt> for a list of all the options.
@@ -61,12 +59,12 @@ The +config.gem+ method is gone and has been replaced by using +bundler+ and a +
h4. Upgrade Process
-To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/rails/rails_upgrade has been created to automate part of it.
+To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/jm/rails_upgrade has been created to automate part of it.
Simply install the plugin, then run +rake rails:upgrade:check+ to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a +Gemfile+ based on your current +config.gem+ calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following:
<shell>
-ruby script/plugin install git://github.com/rails/rails_upgrade.git
+$ ruby script/plugin install git://github.com/jm/rails_upgrade.git
</shell>
You can see an example of how that works at "Rails Upgrade is now an Official Plugin":http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin
@@ -77,10 +75,8 @@ More information - "The Path to Rails 3: Approaching the upgrade":http://omgblog
h3. Creating a Rails 3.0 application
-The new installing rails sequence (for the beta) is:
-
<shell>
-$ gem install rails --prerelease
+# You should have the 'rails' rubygem installed
$ rails new myapp
$ cd myapp
</shell>
@@ -201,9 +197,9 @@ Finally a couple of enhancements were added to the rake tasks:
Railties now deprecates:
-* <tt>RAILS_ROOT</tt> in favour of <tt>Rails.root</tt>,
-* <tt>RAILS_ENV</tt> in favour of <tt>Rails.env</tt>, and
-* <tt>RAILS_DEFAULT_LOGGER</tt> in favour of <tt>Rails.logger</tt>.
+* <tt>RAILS_ROOT</tt> in favor of <tt>Rails.root</tt>,
+* <tt>RAILS_ENV</tt> in favor of <tt>Rails.env</tt>, and
+* <tt>RAILS_DEFAULT_LOGGER</tt> in favor of <tt>Rails.logger</tt>.
<tt>PLUGIN/rails/tasks</tt>, and <tt>PLUGIN/tasks</tt> are no longer loaded all tasks now must be in <tt>PLUGIN/lib/tasks</tt>.
@@ -241,7 +237,7 @@ h4. Action Controller
Deprecations:
-* <tt>filter_parameter_logging</tt> is deprecated in favour of <tt>config.filter_parameters << :password</tt>.
+* <tt>filter_parameter_logging</tt> is deprecated in favor of <tt>config.filter_parameters << :password</tt>.
More Information:
* "Render Options in Rails 3":http://www.engineyard.com/blog/2010/render-options-in-rails-3/
@@ -275,10 +271,10 @@ end
<ruby>
scope 'es' do
- resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'projeto'
+ resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'proyecto'
end
-# Gives you the edit action with /es/projeto/1/cambiar
+# Gives you the edit action with /es/proyecto/1/cambiar
</ruby>
* Added +root+ method to the router as a short cut for <tt>match '/', :to => path</tt>.
@@ -361,15 +357,15 @@ Validations have been moved from Active Record into Active Model, providing an i
* There is now a <tt>validates :attribute, options_hash</tt> shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method.
* The +validates+ method has the following options:
- * <tt>:acceptance => Boolean</tt>.
- * <tt>:confirmation => Boolean</tt>.
- * <tt>:exclusion => { :in => Ennumerable }</tt>.
- * <tt>:inclusion => { :in => Ennumerable }</tt>.
- * <tt>:format => { :with => Regexp, :on => :create }</tt>.
- * <tt>:length => { :maximum => Fixnum }</tt>.
- * <tt>:numericality => Boolean</tt>.
- * <tt>:presence => Boolean</tt>.
- * <tt>:uniqueness => Boolean</tt>.
+** <tt>:acceptance => Boolean</tt>.
+** <tt>:confirmation => Boolean</tt>.
+** <tt>:exclusion => { :in => Enumerable }</tt>.
+** <tt>:inclusion => { :in => Enumerable }</tt>.
+** <tt>:format => { :with => Regexp, :on => :create }</tt>.
+** <tt>:length => { :maximum => Fixnum }</tt>.
+** <tt>:numericality => Boolean</tt>.
+** <tt>:presence => Boolean</tt>.
+** <tt>:uniqueness => Boolean</tt>.
NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API.
@@ -452,7 +448,7 @@ h4. Patches and Deprecations
Additionally, many fixes in the Active Record branch:
-* SQLite 2 support has been dropped in favour of SQLite 3.
+* 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.
@@ -464,11 +460,11 @@ 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 <tt>:conditions => {}</tt> finder method, for example <tt>scope :since, lambda {|time| where("created_at > ?", time) }</tt>.
-* <tt>save(false)</tt> is deprecated, in favour of <tt>save(:validate => false)</tt>.
+* <tt>save(false)</tt> is deprecated, in favor of <tt>save(:validate => false)</tt>.
* I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to <tt>:en.errors.template</tt>.
-* <tt>model.errors.on</tt> is deprecated in favour of <tt>model.errors[]</tt>
+* <tt>model.errors.on</tt> is deprecated in favor of <tt>model.errors[]</tt>
* validates_presence_of => validates... :presence => true
-* <tt>ActiveRecord::Base.colorize_logging</tt> and <tt>config.active_record.colorize_logging</tt> are deprecated in favour of <tt>Rails::LogSubscriber.colorize_logging</tt> or <tt>config.colorize_logging</tt>
+* <tt>ActiveRecord::Base.colorize_logging</tt> and <tt>config.active_record.colorize_logging</tt> are deprecated in favor of <tt>Rails::LogSubscriber.colorize_logging</tt> or <tt>config.colorize_logging</tt>
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.
@@ -491,7 +487,7 @@ Active Resource was also extracted out to Active Model allowing you to use Activ
* Renamed <tt>SchemaDefinition</tt> to <tt>Schema</tt> and <tt>define_schema</tt> to <tt>schema</tt>.
* Use the <tt>format</tt> of Active Resources rather than the <tt>content-type</tt> of remote errors to load errors.
* Use <tt>instance_eval</tt> for schema block.
-* Fix <tt>ActiveResource::ConnectionError#to_s</tt> when +@response+ does not respond to #code or #message, handles Ruby 1.9 compat.
+* Fix <tt>ActiveResource::ConnectionError#to_s</tt> when +@response+ does not respond to #code or #message, handles Ruby 1.9 compatibility.
* Add support for errors in JSON format.
* Ensure <tt>load</tt> works with numeric arrays.
* Recognizes a 410 response from remote resource as the resource has been deleted.
@@ -500,7 +496,7 @@ Active Resource was also extracted out to Active Model allowing you to use Activ
Deprecations:
-* <tt>save(false)</tt> is deprecated, in favour of <tt>save(:validate => false)</tt>.
+* <tt>save(false)</tt> is deprecated, in favor of <tt>save(:validate => false)</tt>.
* Ruby 1.9.2: <tt>URI.parse</tt> and <tt>.decode</tt> are deprecated and are no longer used in the library.
@@ -551,7 +547,7 @@ The following methods have been removed because they are now available in Ruby 1
* <tt>Object#instance_variable_defined?</tt>
* <tt>Enumerable#none?</tt>
-The security patch for REXML remains in Active Support because early patchlevels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not.
+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:
@@ -579,7 +575,7 @@ Action Mailer has been given a new API with TMail being replaced out with the ne
Deprecations:
-* <tt>:charset</tt>, <tt>:content_type</tt>, <tt>:mime_version</tt>, <tt>:implicit_parts_order</tt> are all deprecated in favour of <tt>ActionMailer.default :key => value</tt> style declarations.
+* <tt>:charset</tt>, <tt>:content_type</tt>, <tt>:mime_version</tt>, <tt>:implicit_parts_order</tt> are all deprecated in favor of <tt>ActionMailer.default :key => value</tt> style declarations.
* Mailer dynamic <tt>create_method_name</tt> and <tt>deliver_method_name</tt> are deprecated, just call <tt>method_name</tt> which now returns a <tt>Mail::Message</tt> object.
* <tt>ActionMailer.deliver(message)</tt> is deprecated, just call <tt>message.deliver</tt>.
* <tt>template_root</tt> is deprecated, pass options to a render call inside a proc from the <tt>format.mime_type</tt> method inside the <tt>mail</tt> generation block
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index ec2d5b2787..ecb03a48e4 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -98,7 +98,7 @@ The value of +params[:ids]+ will now be +["1", "2", "3"]+. Note that parameter v
To send a hash you include the key name inside the brackets:
<html>
-<form action="/clients" method="post">
+<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" />
@@ -115,10 +115,7 @@ h4. 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>
-map.connect "/clients/:status",
- :controller => "clients",
- :action => "index",
- :foo => "bar"
+match '/clients/:status' => 'clients#index', :foo => "bar"
</ruby>
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".
@@ -161,7 +158,7 @@ If you need a different session storage mechanism, you can change it in the +con
<ruby>
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
-# (create the session table with "rake db:sessions:create")
+# (create the session table with "script/rails g session_migration")
# YourApp::Application.config.session_store :active_record_store
</ruby>
@@ -214,7 +211,7 @@ class ApplicationController < ActionController::Base
# logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] &&
- User.find(session[:current_user_id])
+ User.find_by_id(session[:current_user_id])
end
end
</ruby>
@@ -242,7 +239,7 @@ class LoginsController < ApplicationController
# "Delete" a login, aka "log the user out"
def destroy
# Remove the user id from the session
- session[:current_user_id] = nil
+ @_current_user = session[:current_user_id] = nil
redirect_to root_url
end
end
@@ -264,6 +261,13 @@ class LoginsController < ApplicationController
end
</ruby>
+Note it is also possible to assign a flash message as part of the redirection.
+
+<ruby>
+redirect_to root_url, :notice => "You have successfully logged out"
+</ruby>
+
+
The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
<ruby>
@@ -296,7 +300,7 @@ class MainController < ApplicationController
# Will persist all flash values.
flash.keep
- # You can also use a key to keep only some kind of value.
+ # You can also use a key to keep only some kind of value.
# flash.keep(:notice)
redirect_to users_url
end
@@ -364,19 +368,20 @@ class UsersController < ApplicationController
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users}
+ format.json { render :json => @users}
end
end
end
</ruby>
-Notice that in the above case code is <tt>render :xml => @users</tt> and not <tt>render :xml => @users.to_xml</tt>. That is because if the input is not string then rails automatically invokes +to_xml+ .
+Notice that in the above case code is <tt>render :xml => @users</tt> and not <tt>render :xml => @users.to_xml</tt>. That is because if the input is not string then rails automatically invokes +to_xml+ .
h3. Filters
-Filters are methods that are run before, after or "around" a controller action.
+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.
+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:
@@ -418,27 +423,36 @@ Now, the +LoginsController+'s +new+ and +create+ actions will work as before wit
h4. After Filters and Around Filters
-In addition to before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running.
+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 the action, but they can choose not to, which is the around filter's way of stopping it.
+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>
-# Example taken from the Rails API filter documentation:
-# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
-class ApplicationController < ActionController::Base
- around_filter :catch_exceptions
+class ChangesController < ActionController::Base
+ around_filter :wrap_in_transaction, :only => :show
private
- def catch_exceptions
- yield
- rescue => exception
- logger.debug "Caught exception! #{exception}"
- raise
+ def wrap_in_transaction
+ ActiveRecord::Base.transaction do
+ begin
+ yield
+ ensure
+ raise ActiveRecord::Rollback
+ end
+ end
end
end
</ruby>
+Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview.
+
+They can choose not to yield and build the response themselves, in which case the action is not run.
+
h4. Other Ways to Use Filters
While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
@@ -474,11 +488,9 @@ 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 +after+ method that are run before and after the action.
-The Rails API documentation has "more information on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html.
-
h3. Verification
-Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHttpRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
+Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHttpRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response.
Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
@@ -535,8 +547,8 @@ If you generate a form like this:
You will see how the token gets added as a hidden field:
<html>
-<form action="/users/1" method="post">
-<input type="hidden"
+<form accept-charset="UTF-8" action="/users/1" method="post">
+<input type="hidden"
value="67250ab105eb5ad10851c00a5621854a23af5489"
name="authenticity_token"/>
<!-- fields -->
@@ -555,7 +567,7 @@ In every controller there are two accessor methods pointing to the request and t
h4. 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/ActionController/AbstractRequest.html. Among the properties that you can access on this object are:
+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.|
@@ -659,7 +671,7 @@ class ClientsController < ApplicationController
# 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),
+ send_data generate_pdf(client),
:filename => "#{client.name}.pdf",
:type => "application/pdf"
end
@@ -734,16 +746,12 @@ GET /clients/1.pdf
h3. Parameter Filtering
-Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
<ruby>
-class ApplicationController < ActionController::Base
- filter_parameter_logging :password
-end
+config.filter_parameters << :password
</ruby>
-The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
-
h3. Rescue
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception.
@@ -810,8 +818,6 @@ NOTE: Certain exceptions are only rescuable from the +ApplicationController+ cla
h3. Changelog
-"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17
-
* February 17, 2009: Yet another proofread by Xavier Noria.
* November 4, 2008: First release version by Tore Darell
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index 8eb48e2751..56da360972 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -19,7 +19,7 @@ h4. Walkthrough to Generating a Mailer
h5. Create the Mailer
<shell>
-rails generate mailer UserMailer
+$ rails generate mailer UserMailer
create app/mailers/user_mailer.rb
invoke erb
create app/views/user_mailer
@@ -27,7 +27,7 @@ invoke test_unit
create test/functional/user_mailer_test.rb
</shell>
-So we got the mailer, the fixtures, and the tests.
+So we got the mailer, the views, and the tests.
h5. Edit the Mailer
@@ -144,7 +144,7 @@ This provides a much simpler implementation that does not require the registerin
The method +welcome_email+ returns a Mail::Message object which can then just be told +deliver+ to send itself out.
-NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+ however in Rails 3.0 this has been deprecated in favour of just calling the method name itself.
+NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+. This has been deprecated in Rails 3.0 in favour of just calling the method name itself.
WARNING: Sending out one email should only take a fraction of a second, if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like delayed job.
@@ -154,7 +154,7 @@ Action Mailer now handles the auto encoding of multibyte characters inside of he
If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and ActionMailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII.
-For more complex examples, such as defining alternate character sets or self encoding text first, please refer to the Mail library.
+For more complex examples such as defining alternate character sets or self encoding text first, please refer to the Mail library.
h4. Complete List of Action Mailer Methods
@@ -198,7 +198,7 @@ Adding attachments has been simplified in Action Mailer 3.0.
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
</ruby>
-NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
+NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
* Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.
@@ -213,9 +213,7 @@ NOTE: If you specify an encoding, Mail will assume that your content is already
h5. Making Inline Attachments
-Inline attachments are now possible in ActionMailer. While previously in the pre 3.0 version of Rails, you could do inline attachments, it involved a lot of hacking and determination to pull it off.
-
-ActionMailer now makes inline attachments as trivial as they should be.
+ActionMailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be.
* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call <tt>#inline</tt> on the attachments method within your Mailer:
@@ -242,9 +240,39 @@ end
:class => 'photos' %>
</erb>
+h5. Sending Email To Multiple Recipients
+
+It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The <tt>to:</tt> key however expects a string so you have join the list of recipients using a comma.
+
+<ruby>
+ class AdminMailer < ActionMailer::Base
+ default :to => Admin.all.map(&:email).join(", "),
+ :from => "notification@example.com"
+
+ def new_registration(user)
+ @user = user
+ mail(:subject => "New User Signup: #{@user.email}")
+ end
+ end
+</ruby>
+
+h5. Sending Email With Name
+
+Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is
+to format the email address in the format <tt>"Name &lt;email&gt;"</tt>.
+
+<ruby>
+ def welcome_email(user)
+ @user = user
+ email_with_name = "#{@user.name} <#{@user.email}>"
+ mail(:to => email_with_name,
+ :subject => "Welcome to My Awesome Site")
+ end
+</ruby>
+
h4. Mailer Views
-Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.
+Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.
To change the default mailer view for your action you do something like:
@@ -373,7 +401,7 @@ The above will send a multipart email with an attachment, properly nested with t
h3. Receiving Emails
-Receiving and parsing emails with Action Mailer can be a rather complex endeavour. 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:
+Receiving and parsing emails with Action Mailer can be a rather complex endeavour. 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.
@@ -411,12 +439,12 @@ h3. Action Mailer Configuration
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
|template_root|Determines the base from which template references will be made.|
-|logger|the logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.|
-|smtp_settings|Allows detailed configuration for :smtp delivery method: :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.|
-|sendmail_settings|Allows you to override options for the :sendmail delivery method. :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. :arguments - The command line arguments. Defaults to -i -t.|
+|logger|Generates information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.|
+|smtp_settings|Allows detailed configuration for :smtp delivery method:<ul><li>:address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>:port - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>:domain - If you need to specify a HELO domain, you can do it here.</li><li>:user_name - If your mail server requires authentication, set the username in this setting.</li><li>:password - If your mail server requires authentication, set the password in this setting.</li><li>:authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.</li></ul>|
+|sendmail_settings|Allows you to override options for the :sendmail delivery method.<ul><li>:location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.</li><li>:arguments - The command line arguments to be passed to sendmail. Defaults to -i -t.</li></ul>|
|raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.|
-|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.|
-|perform_deliveries|Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.|
+|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.|
h4. Example Action Mailer Configuration
@@ -462,7 +490,7 @@ class UserMailerTest < ActionMailer::TestCase
user = users(:some_user_in_your_fixtures)
# Send the email, then test that it got queued
- email = UserMailer.deliver_welcome_email(user)
+ email = UserMailer.welcome_email(user).deliver
assert !ActionMailer::Base.deliveries.empty?
# Test the body of the sent email contains what we expect it to
@@ -474,8 +502,8 @@ class UserMailerTest < ActionMailer::TestCase
end
</ruby>
-In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain the what we expect.
+In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect.
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/25
+* September 30, 2010: Fixed typos and reformatted Action Mailer configuration table for better understanding. "Jaime Iniesta":http://jaimeiniesta.com
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile
index 8b5eda0973..cfd71ad287 100644
--- a/railties/guides/source/action_view_overview.textile
+++ b/railties/guides/source/action_view_overview.textile
@@ -12,9 +12,9 @@ endprologue.
h3. 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 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.
+Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves.
Note: Some features of Action View are tied to Active Record, but that doesn't mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend.
@@ -24,13 +24,13 @@ TODO...
h3. Using Action View outside of Rails
-Action View works well with Action Record, but it can also be used with other Ruby tools. 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.
+Action View works well with Action Record, but it can also be used with other Ruby tools. 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:
<shell>
-gem install actionpack
-gem install rack
+$ gem install actionpack
+$ gem install rack
</shell>
Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Active Support.
@@ -52,20 +52,20 @@ Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567
We can see this all come together by starting up the application and then visiting +http://localhost:4567/+
<shell>
-ruby hello_world.rb
+$ ruby hello_world.rb
</shell>
-TODO needs a screenshot? I have one - not sure where to put it.
+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.
+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.
+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:
<shell>
-gem install actionpack
-gem install sinatra
+$ gem install actionpack
+$ gem install sinatra
</shell>
Now we'll create the same "Hello World" application in Sinatra.
@@ -85,12 +85,12 @@ end
Then, we can run the application:
<shell>
-ruby hello_world.rb
+$ ruby hello_world.rb
</shell>
Once the application is running, you can see Sinatra and Action View working together by visiting +http://localhost:4567/+
-TODO needs a screenshot? I have one - not sure where to put it.
+TODO needs a screenshot? I have one - not sure where to put it.
h3. Templates, Partials and Layouts
@@ -172,7 +172,7 @@ TODO...
h3. Overview of all the helpers provided by Action View
-The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point.
+The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point.
h4. ActiveRecordHelper
@@ -196,7 +196,7 @@ error_messages_for "post"
h5. form
-Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a +@post+ with attributes named +title+ of type +String+ and +body+ of type +Text+. Calling +form+ would produce a form to creating a new post with inputs for those attributes.
+Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a +@post+ with attributes named +title+ of type +String+ and +body+ of type +Text+. Calling +form+ would produce a form to creating a new post with inputs for those attributes.
<ruby>
form("post")
@@ -220,29 +220,29 @@ Typically, +form_for+ is used instead of +form+ because it doesn't automatically
h5. input
-Returns a default input tag for the type of object returned by the method.
+Returns a default input tag for the type of object returned by the method.
For example, if +@post+ has an attribute +title+ mapped to a +String+ column that holds "Hello World":
<ruby>
-input("post", "title") # =>
+input("post", "title") # =>
<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
</ruby>
h4. AssetTagHelper
-This module provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds.
+This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
-By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in your +config/environment.rb+. For example, let's say your asset host is +assets.example.com+:
+By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in the application configuration, typically in +config/environments/production.rb+. For example, let's say your asset host is +assets.example.com+:
<ruby>
ActionController::Base.asset_host = "assets.example.com"
-image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
+image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
</ruby>
h5. register_javascript_expansion
-Register one or more javascript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register javascript files that the plugin installed in public/javascripts.
+Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in +public/javascripts+.
<ruby>
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
@@ -253,9 +253,6 @@ javascript_include_tag :monkey # =>
<script type="text/javascript" src="/javascripts/tail.js"></script>
</ruby>
-h5. register_javascript_include_default
-
-Register one or more additional JavaScript files to be included when +javascript_include_tag :defaults+ is called. This method is typically intended to be called from plugin initialization to register additional +.js+ files that the plugin installed in +public/javascripts+.
h5. register_stylesheet_expansion
@@ -281,7 +278,7 @@ auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS
h5. image_path
-Computes the path to an image asset in the public images directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
+Computes the path to an image asset in the +public/images+ directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
<ruby>
image_path("edit.png") # => /images/edit.png
@@ -289,7 +286,7 @@ image_path("edit.png") # => /images/edit.png
h5. image_tag
-Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory.
+Returns an html image tag for the source. The source can be a full path or a file that exists in your +public/images+ directory.
<ruby>
image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
@@ -297,35 +294,35 @@ image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
h5. javascript_include_tag
-Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of javascript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
+Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of JavaScript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
<ruby>
javascript_include_tag "common" # =>
- <script type="text/javascript" src="/javascripts/common.js"></script>
+ <script type="text/javascript" src="/javascripts/common.js"></script>
</ruby>
-To include the Prototype and Scriptaculous javascript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
+To include the Prototype and Scriptaculous JavaScript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
<ruby>
javascript_include_tag :defaults
</ruby>
-You can also include all javascripts in the javascripts directory using +:all+ as the source.
+You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source.
<ruby>
javascript_include_tag :all
</ruby>
-You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).
+You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).
<ruby>
-javascript_include_tag :all, :cache => true # =>
- <script type="text/javascript" src="/javascripts/all.js"></script>
+javascript_include_tag :all, :cache => true # =>
+ <script type="text/javascript" src="/javascripts/all.js"></script>
</ruby>
h5. javascript_path
-Computes the path to a javascript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
+Computes the path to a JavaScript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
<ruby>
javascript_path "common" # => /javascripts/common.js
@@ -333,7 +330,7 @@ javascript_path "common" # => /javascripts/common.js
h5. 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.
+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" # =>
@@ -346,7 +343,7 @@ You can also include all styles in the stylesheet directory using :all as the so
stylesheet_link_tag :all
</ruby>
-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).
+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
@@ -355,7 +352,7 @@ stylesheet_link_tag :all, :cache => true
h5. stylesheet_path
-Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
+Computes the path to a stylesheet asset in the +public/stylesheets+ directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
<ruby>
stylesheet_path "application" # => /stylesheets/application.css
@@ -370,14 +367,14 @@ This helper makes building an ATOM feed easy. Here's a full usage example:
*config/routes.rb*
<ruby>
-map.resources :posts
+resources :posts
</ruby>
*app/controllers/posts_controller.rb*
<ruby>
def index
- @posts = Post.find(:all)
+ @posts = Post.all
respond_to do |format|
format.html
@@ -415,7 +412,7 @@ Allows you to measure the execution time of a block in a template and records th
<ruby>
<% benchmark "Process data files" do %>
<%= expensive_files_operation %>
-<% end %>
+<% end %>
</ruby>
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.
@@ -428,7 +425,7 @@ A method for caching fragments of a view rather than an entire action or page. T
<ruby>
<% cache do %>
- <%= render :partial => "shared/footer" %>
+ <%= render "shared/footer" %>
<% end %>
</ruby>
@@ -442,7 +439,7 @@ The +capture+ method allows you to extract part of a template into a variable. Y
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
-<ruby>
+</ruby>
The captured variable can then be used anywhere else.
@@ -455,7 +452,7 @@ The captured variable can then be used anywhere else.
<%= @greeting %>
</body>
</html>
-</ruby>
+</ruby>
h5. content_for
@@ -484,7 +481,7 @@ For example, let's say we have a standard application layout, but also a special
<% content_for :special_script do %>
<script type="text/javascript">alert('Hello!')</script>
-<% end %>
+<% end %>
</ruby>
h4. DateHelper
@@ -523,7 +520,7 @@ Returns a set of html select-tags (one for year, month, and day) pre-selected wi
select_date(Time.today + 6.days)
# Generates a date select that defaults to today (no specified date)
-select_date()
+select_date()
</ruby>
h5. select_datetime
@@ -535,7 +532,7 @@ Returns a set of html select-tags (one for year, month, day, hour, and minute) p
select_datetime(Time.now + 4.days)
# Generates a datetime select that defaults to today (no specified datetime)
-select_datetime()
+select_datetime()
</ruby>
h5. select_day
@@ -583,7 +580,7 @@ Returns a select tag with options for each of the seconds 0 through 59 with the
<ruby>
# Generates a select field for seconds that defaults to the seconds for the time provided
-select_second(Time.now + 16.minutes)
+select_second(Time.now + 16.minutes)
</ruby>
h5. select_time
@@ -592,7 +589,7 @@ 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_time(Time.now)
</ruby>
h5. select_year
@@ -621,7 +618,7 @@ Returns a set of select tags (one for hour, minute and optionally second) pre-se
<ruby>
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
-time_select("order", "submitted")
+time_select("order", "submitted")
</ruby>
h4. DebugHelper
@@ -654,7 +651,7 @@ The core method of this helper, form_for, gives you the ability to create a form
<ruby>
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
-<%= form_for :person, @person, :url => { :action => "create" } do |f| %>
+<%= form_for @person, :url => { :action => "create" } do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= submit_tag 'Create' %>
@@ -711,7 +708,7 @@ Returns an file upload input tag tailored for accessing a specified attribute.
<ruby>
file_field(:user, :avatar)
-# => <input type="file" id="user_avatar" name="user[avatar]" />
+# => <input type="file" id="user_avatar" name="user[avatar]" />
</ruby>
h5. form_for
@@ -733,7 +730,7 @@ 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}" />
+# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
</ruby>
h5. label
@@ -751,7 +748,7 @@ Returns an input tag of the "password" type tailored for accessing a specified a
<ruby>
password_field(:login, :pass)
-# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
+# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
</ruby>
h5. radio_button
@@ -812,7 +809,7 @@ end
Sample usage (selecting the associated Author for an instance of Post, +@post+):
<ruby>
-collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true})
+collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
</ruby>
If @post.author_id is already 1, this would return:
@@ -854,7 +851,7 @@ end
Sample usage:
-<ruby>
+<ruby>
option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
</ruby>
@@ -880,7 +877,7 @@ Note: Only the +optgroup+ and +option+ tags are returned, so you still have to w
h5. options_for_select
-Accepts a container (hash, array, enumerable, your type) and returns a string of option tags.
+Accepts a container (hash, array, enumerable, your type) and returns a string of option tags.
<ruby>
options_for_select([ "VISA", "MasterCard" ])
@@ -891,7 +888,7 @@ Note: Only the +option+ tags are returned, you have to wrap this call in a regul
h5. options_from_collection_for_select
-Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
+Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
<ruby>
# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
@@ -902,7 +899,7 @@ For example, imagine a loop iterating over each person in @project.people to gen
<ruby>
options_from_collection_for_select(@project.people, "id", "name")
# => <option value="#{person.id}">#{person.name}</option>
-</ruby>
+</ruby>
Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.
@@ -913,7 +910,7 @@ Create a select tag and a series of contained option tags for the provided objec
Example with @post.person_id => 1:
<ruby>
-select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
+select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
</ruby>
could become:
@@ -949,7 +946,7 @@ Creates a check box form input tag.
<ruby>
check_box_tag 'accept'
-# => <input id="accept" name="accept" type="checkbox" value="1" />
+# => <input id="accept" name="accept" type="checkbox" value="1" />
</ruby>
h5. field_set_tag
@@ -965,7 +962,7 @@ Creates a field set for grouping HTML form elements.
h5. file_field_tag
-Creates a file upload field.
+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:
@@ -1079,7 +1076,7 @@ h4. JavaScriptHelper
Provides functionality for working with JavaScript in your views.
-Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +&lt;%= javascript_include_tag :defaults, :cache => true %&gt;+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the public/javascripts directory.
+Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +&lt;%= javascript_include_tag :defaults, :cache => true %&gt;+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the +public/javascripts+ directory.
h5. button_to_function
@@ -1173,7 +1170,7 @@ number_with_delimiter(12345678) # => 12,345,678
h5. number_with_precision
-Formats a number with the specified level of +precision+, which defaults to 3.
+Formats a number with the specified level of +precision+, which defaults to 3.
<ruby>
number_with_precision(111.2345) # => 111.235
@@ -1207,7 +1204,7 @@ form_remote_tag :html => { :action => url_for(:controller => "some", :action =>
would generate the following:
<html>
-<form action="/some/place" method="post" onsubmit="new Ajax.Request('',
+<form action="/some/place" method="post" onsubmit="new Ajax.Request('',
{asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
</html>
@@ -1293,7 +1290,7 @@ Yields a JavaScriptGenerator and returns the generated JavaScript code. Use this
<ruby>
update_page do |page|
page.hide 'spinner'
-end
+end
</ruby>
h5. update_page_tag
@@ -1395,7 +1392,7 @@ h5. remove
Removes the DOM elements with the given ids from the page.
<ruby>
-page.remove 'person_23', 'person_9', 'person_2'
+page.remove 'person_23', 'person_9', 'person_2'
</ruby>
h5. replace
@@ -1420,7 +1417,7 @@ Returns a collection reference by finding it through a CSS pattern in the DOM.
<ruby>
page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
-</ruby>
+</ruby>
h5. show
@@ -1440,7 +1437,7 @@ Toggles the visibility of the DOM elements with the given ids. Example:
<ruby>
page.toggle 'person_14', 'person_12', 'person_23' # Hides the elements
-page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements
+page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements
</ruby>
h5. visual_effect
@@ -1455,11 +1452,11 @@ h3. 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.
+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+:
+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_filter :set_expert_locale
@@ -1471,11 +1468,9 @@ 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.
+You can read more about the Rails Internationalization (I18n) API "here":i18n.html.
h3. Changelog
-"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/71
-
-* September 3, 2009: Continuing work by Trevor Turk, leveraging the "Action Pack docs":http://ap.rubyonrails.org/ and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts
+* September 3, 2009: Continuing work by Trevor Turk, leveraging the Action Pack docs and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts
* April 5, 2009: Starting work by Trevor Turk, leveraging Mike Gunderloy's docs
diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile
index e6ef2cdd20..b7926f3a3b 100644
--- a/railties/guides/source/active_record_basics.textile
+++ b/railties/guides/source/active_record_basics.textile
@@ -16,7 +16,7 @@ Active Record is the M in "MVC":getting_started.html#the-mvc-architecture - the
h4. The Active Record Pattern
-Active Record was described by Martin Fowler 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.
+Active Record was described by Martin Fowler 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.
h4. Object Relational Mapping
@@ -132,7 +132,7 @@ CRUD is an acronym for the four verbs we use to operate on data: *C*reate, *R*ea
h4. Create
-Active Record objects can be created from a hash, a block or have its attributes manually set after creation. The _new_ method will return a new object while _create_ will return the object and save it to the database.
+Active Record objects can be created from a hash, a block or have its attributes manually set after creation. The _new_ method will return a new object while _create_ will return the object and save it to the database.
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:
@@ -180,7 +180,7 @@ Active Record provides a rich API for accessing data within a database. Below ar
<ruby>
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
- users = User.all(:conditions => { :name => 'David', :occupation => 'Code Artist'}, :order => 'created_at DESC')
+ users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
</ruby>
You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index 53095a2bd3..009d541106 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -19,8 +19,6 @@ Code examples throughout this guide will refer to one or more of the following m
TIP: All of the following models use +id+ as the primary key, unless specified otherwise.
-<br />
-
<ruby>
class Client < ActiveRecord::Base
has_one :address
@@ -65,6 +63,7 @@ The methods are:
* +lock+
* +readonly+
* +from+
+* +having+
All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>.
@@ -103,7 +102,7 @@ h5. +first+
<ruby>
client = Client.first
-=> #<Client id: 1, first_name: => "Lifo">
+=> #<Client id: 1, first_name: "Lifo">
</ruby>
SQL equivalent of the above is:
@@ -120,7 +119,7 @@ h5. +last+
<ruby>
client = Client.last
-=> #<Client id: 221, first_name: => "Russel">
+=> #<Client id: 221, first_name: "Russel">
</ruby>
SQL equivalent of the above is:
@@ -149,24 +148,24 @@ SQL equivalent of the above is:
SELECT * FROM clients WHERE (clients.id IN (1,10))
</sql>
-<tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
+WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
h4. Retrieving Multiple Objects in Batches
-Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc.
+Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc.
The following may seem very straight forward at first:
<ruby>
# Very inefficient when users table has thousands of rows.
-User.each do |user|
+User.all.each do |user|
NewsLetter.weekly_deliver(user)
end
</ruby>
But if the total number of rows in the table is very large, the above approach may vary from being under performant to just plain impossible.
-This is because +User.each+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory.
+This is because +User.all.each+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory.
h5. +find_each+
@@ -231,10 +230,10 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t
h4. Array Conditions
-Now what if that number could vary, say as an argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like:
+Now what if that number could vary, say as an argument from somewhere? The find then becomes something like:
<ruby>
-Client.where(["orders_count = ?", params[:orders]])
+Client.where("orders_count = ?", params[:orders])
</ruby>
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.
@@ -242,7 +241,7 @@ Active Record will go through the first element in the conditions value and any
Or if you want to specify two conditions, you can do it like:
<ruby>
-Client.where(["orders_count = ? AND locked = ?", params[:orders], false])
+Client.where("orders_count = ? AND locked = ?", params[:orders], false)
</ruby>
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.
@@ -250,7 +249,7 @@ In this example, the first question mark will be replaced with the value in +par
The reason for doing code like:
<ruby>
-Client.where(["orders_count = ?", params[:orders]])
+Client.where("orders_count = ?", params[:orders])
</ruby>
instead of:
@@ -268,8 +267,8 @@ h5. 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] }])
+Client.where("created_at >= :start_date AND created_at <= :end_date",
+ {:start_date => params[:start_date], :end_date => params[:end_date]})
</ruby>
This makes for clearer readability if you have a large number of variable conditions.
@@ -279,62 +278,15 @@ h5(#array-range_conditions). Range Conditions
If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
<ruby>
-Client.where(["created_at IN (?)",
- (params[:start_date].to_date)..(params[:end_date].to_date)])
+Client.where(:created_at => (params[:start_date].to_date)..(params[:end_date].to_date))
</ruby>
-This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
+This query will generate something similar to the following SQL:
<sql>
-SELECT * FROM users WHERE (created_at IN
- ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
- '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
- '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
- '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
- ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20',
- '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26',
- '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
+ SELECT "clients".* FROM "clients" WHERE ("clients"."created_at" BETWEEN '2010-09-29' AND '2010-11-30')
</sql>
-h5. Time and Date Conditions
-
-Things can get *really* messy if you pass in Time objects as it will attempt to compare your field to *every second* in that range:
-
-<ruby>
-Client.where(["created_at IN (?)",
- (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
-</ruby>
-
-<sql>
-SELECT * FROM users WHERE (created_at IN
- ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
- '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
-</sql>
-
-This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
-
-<shell>
-Got a packet bigger than 'max_allowed_packet' bytes: _query_
-</shell>
-
-Where _query_ is the actual query used to get that error.
-
-In this example it would be better to use greater-than and less-than operators in SQL, like so:
-
-<ruby>
-Client.where(
- ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
-</ruby>
-
-You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
-
-<ruby>
-Client.where(
- ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
-</ruby>
-
-Just like in Ruby. If you want a shorter syntax be sure to check out the "Hash Conditions":#hash-conditions section later on in the guide.
-
h4. 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:
@@ -344,13 +296,13 @@ NOTE: Only equality, range and subset checking are possible with Hash conditions
h5. Equality Conditions
<ruby>
-Client.where({ :locked => true })
+Client.where(:locked => true)
</ruby>
The field name can also be a string:
<ruby>
-Client.where({ 'locked' => true })
+Client.where('locked' => true)
</ruby>
h5(#hash-range_conditions). Range Conditions
@@ -358,7 +310,7 @@ h5(#hash-range_conditions). Range Conditions
The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.
<ruby>
-Client.where({ :created_at => (Time.now.midnight - 1.day)..Time.now.midnight})
+Client.where(:created_at => (Time.now.midnight - 1.day)..Time.now.midnight)
</ruby>
This will find all clients created yesterday by using a +BETWEEN+ SQL statement:
@@ -374,7 +326,7 @@ h5. 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] })
+Client.where(:orders_count => [1,3,5])
</ruby>
This code will generate SQL like this:
@@ -383,9 +335,9 @@ This code will generate SQL like this:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
</sql>
-h4. Ordering
+h3. Ordering
-To retrieve records from the database in a specific order, you can specify the +:order+ option to the +find+ call.
+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:
@@ -407,7 +359,7 @@ Or ordering by multiple fields:
Client.order("orders_count ASC, created_at DESC")
</ruby>
-h4. Selecting Specific Fields
+h3. Selecting Specific Fields
By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
@@ -443,7 +395,7 @@ You can also call SQL functions within the select option. For example, if you wo
Client.select("DISTINCT(name)")
</ruby>
-h4. Limit and Offset
+h3. Limit and Offset
To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +limit+ and +offset+ methods on the relation.
@@ -468,10 +420,10 @@ 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, 30
+SELECT * FROM clients LIMIT 5 OFFSET 30
</sql>
-h4. Group
+h3. Group
To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the +group+ method on the find.
@@ -486,17 +438,17 @@ And this will give you a single +Order+ object for each date where there are ord
The SQL that would be executed would be something like this:
<sql>
-SELECT * FROM orders GROUP BY date(created_at)
+SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at
</sql>
-h4. Having
+h3. Having
SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can add the +HAVING+ clause to the SQL fired by the +Model.find+ by adding the +:having+ option to the find.
For example:
<ruby>
-Order.group("date(created_at)".having(["created_at > ?", 1.month.ago])
+Order.group("date(created_at)").having("created_at > ?", 1.month.ago)
</ruby>
The SQL that would be executed would be something like this:
@@ -507,25 +459,49 @@ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
This will return single order objects for each day, but only for the last month.
-h4. Readonly Objects
+h3. Overriding Conditions
-To explicitly disallow modification/destruction of the matching records returned in a Relation object, you could chain the +readonly+ method as +true+ to the find call.
+You can specify certain conditions to be excepted by using the +except+ method.
-Any attempt to alter or destroy the readonly records will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. To set this option, specify it like this:
+For example:
<ruby>
-Client.first.readonly(true)
+Post.where('id > 10').limit(20).order('id asc').except(:order)
</ruby>
-For example, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 LIMIT 20
+</sql>
+
+You can also override conditions using the +only+ method.
+
+For example:
<ruby>
-client = Client.first.readonly(true)
-client.locked = false
+Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
+</ruby>
+
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
+</sql>
+
+h3. Readonly Objects
+
+Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception.
+
+<ruby>
+client = Client.readonly.first
+client.visits += 1
client.save
</ruby>
-h4. Locking Records for Update
+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_.
+
+h3. Locking Records for Update
Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
@@ -534,7 +510,7 @@ Active Record provides two locking mechanisms:
* Optimistic Locking
* Pessimistic Locking
-h5. Optimistic Locking
+h4. Optimistic Locking
Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored.
@@ -569,15 +545,15 @@ class Client < ActiveRecord::Base
end
</ruby>
-h5. Pessimistic Locking
+h4. Pessimistic Locking
-Pessimistic locking uses a locking mechanism provided by the underlying database. Passing +:lock => true+ to +Model.find+ obtains an exclusive lock on the selected rows. +Model.find+ using +:lock+ are usually wrapped inside a transaction for preventing deadlock conditions.
+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.first(:lock => true)
+ i = Item.lock.first
i.name = 'Jones'
i.save
end
@@ -592,25 +568,25 @@ Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `
SQL (0.8ms) COMMIT
</sql>
-You can also pass raw SQL to the +:lock+ option to allow 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:
+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.find(1, :lock => "LOCK IN SHARE MODE")
+ i = Item.lock("LOCK IN SHARE MODE").find(1)
i.increment!(:views)
end
</ruby>
h3. Joining Tables
-<tt>Model.find</tt> provides a +:joins+ option for specifying +JOIN+ clauses on the resulting SQL. There are multiple ways to specify the +:joins+ option:
+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.
h4. Using a String SQL Fragment
-You can just supply the raw SQL specifying the +JOIN+ clause to the +:joins+ option. For example:
+You can just supply the raw SQL specifying the +JOIN+ clause to +joins+:
<ruby>
-Client.all(:joins => 'LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
+Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
</ruby>
This will result in the following SQL:
@@ -621,11 +597,9 @@ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id =
h4. Using Array/Hash of Named Associations
-WARNING: This method only works with +INNER JOIN+,
+WARNING: This method only works with +INNER JOIN+.
-<br />
-
-Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying the +:joins+ option.
+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:
@@ -674,7 +648,7 @@ Post.joins(:category, :comments)
This produces:
<sql>
-SELECT posts.* FROM posts
+SELECT posts.* FROM posts
INNER JOIN categories ON posts.category_id = categories.id
INNER JOIN comments ON comments.post_id = posts.id
</sql>
@@ -718,7 +692,7 @@ Eager loading is the mechanism for loading the associated records of the objects
Consider the following code, which finds 10 clients and prints their postcodes:
<ruby>
-clients = Client.all(:limit => 10)
+clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
@@ -753,7 +727,7 @@ h4. 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.
-h5. Array of Multiple Associations
+h5. Array of Multiple Associations
<ruby>
Post.includes(:category, :comments)
@@ -771,17 +745,119 @@ This will find the category with id 1 and eager load all of the associated posts
h4. Specifying Conditions on Eager Loaded Associations
-Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead.
+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)
+</ruby>
+
+This would generate a query which contains a +LEFT OUTER JOIN+ whereas the +joins+ method would generate one using the +INNER JOIN+ function instead.
+
+<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)
+</ruby>
+
+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.
+
+h3. Scopes
+
+Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it.
+
+To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true)
+end
+</ruby>
+
+Just like before, these methods are also chainable:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true).joins(:category)
+end
+</ruby>
+
+Scopes are also chainable within scopes:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true)
+ scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
+end
+</ruby>
+
+To call this +published+ scope we can call it on either the class:
+
+<ruby>
+Post.published => [published posts]
+</ruby>
+
+Or on an association consisting of +Post+ objects:
+
+<ruby>
+category = Category.first
+category.posts.published => [published posts belonging to this category]
+</ruby>
+
+h4. Working with times
+
+If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :last_week, lambda { where("created_at < ?", Time.zone.now ) }
+end
+</ruby>
+
+Without the +lambda+, this +Time.zone.now+ will only be called once.
+
+h4. Passing in arguments
+
+When a +lambda+ is used for a +scope+, it can take arguments:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :1_week_before, lambda { |time| where("created_at < ?", time)
+end
+</ruby>
+
+This may then be called using this:
+
+<ruby>
+Post.1_week_before(Time.zone.now)
+</ruby>
+
+However, this is just duplicating the functionality that would be provided to you by a class method.
+
+<ruby>
+class Post < ActiveRecord::Base
+ def self.1_week_before(time)
+ where("created_at < ?", time)
+ end
+end
+</ruby>
+
+Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
+
+<ruby>
+category.posts.1_week_before(time)
+</ruby>
h3. Dynamic Finders
-For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have also have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+.
+For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods.
-You can do +find_last_by_*+ methods too which will find the last record matching your argument.
+You can also use +find_last_by_*+ methods which will find the last record matching your argument.
You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
-If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_first_name_and_locked("Ryan", true)+.
+If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+.
There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_first_name(params[:first_name])+. Using this will first perform a find and then create if the find returns +nil+. The SQL looks like this for +Client.find_or_create_by_first_name("Ryan")+:
@@ -807,8 +883,8 @@ h3. 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
+Client.find_by_sql("SELECT * FROM clients
+ INNER JOIN orders ON clients.id = orders.client_id
ORDER clients.created_at desc")
</ruby>
@@ -838,13 +914,13 @@ Client.exists?(1,2,3)
Client.exists?([1,2,3])
</ruby>
-The +exists+ method may also take a +conditions+ option much like find:
+It's even possible to use +exists?+ without any arguments on a model or a relation.
<ruby>
-Client.exists?(:conditions => "first_name = 'Ryan'")
+Client.where(:first_name => 'Ryan').exists?
</ruby>
-It's even possible to use +exists?+ without any arguments:
+The above returns +true+ if there is at least one client with the +first_name+ 'Ryan' and +false+ otherwise.
<ruby>
Client.exists?
@@ -856,22 +932,24 @@ h3. Calculations
This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
-<tt>count</tt> takes conditions much in the same way +exists?+ does:
+All calculation methods work directly on a model:
<ruby>
-Client.count(:conditions => "first_name = 'Ryan'")
+Client.count
+# SELECT count(*) AS count_all FROM clients
</ruby>
-Which will execute:
+Or on a relation :
-<sql>
-SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
-</sql>
+<ruby>
+Client.where(:first_name => 'Ryan').count
+# SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
+</ruby>
-You can also use the +includes+ or +joins+ methods for this to do something a little more complex:
+You can also use various finder methods on a relation for performing complex calculations:
<ruby>
-Client.where("clients.first_name = 'Ryan' AND orders.status = 'received'").includes("orders").count
+Client.includes("orders").where(:first_name => 'Ryan', :orders => {:status => 'received'}).count
</ruby>
Which will execute:
@@ -882,8 +960,6 @@ SELECT count(DISTINCT clients.id) AS count_all FROM clients
(clients.first_name = 'Ryan' AND orders.status = 'received')
</sql>
-This code specifies +clients.first_name+ just in case one of the join tables has a field also called +first_name+ and it uses +orders.status+ because that's the name of our join table.
-
h4. 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)+.
@@ -934,8 +1010,7 @@ For options, please see the parent section, "Calculations":#calculations.
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16
-
+* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":http://ryanbigg.com
* April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* February 3, 2010: Update to Rails 3 by "James Miller":credits.html#bensie
* February 7, 2009: Second version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile
index 37a65d211e..e5349d546c 100644
--- a/railties/guides/source/active_record_validations_callbacks.textile
+++ b/railties/guides/source/active_record_validations_callbacks.textile
@@ -16,7 +16,7 @@ endprologue.
h3. 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.
+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.
Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state.
@@ -33,7 +33,7 @@ There are several ways to validate data before it is saved into your database, i
* 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":http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model, as it will make your application a pleasure to work with in the long run.
-* 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.
+* 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.
h4. When Does Validation Happen?
@@ -57,7 +57,7 @@ We can see how it works by looking at some +rails console+ output:
=> false
</shell>
-Creating and saving a new record will send a SQL +INSERT+ operation to the database. Updating an existing record will send a SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
+Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
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.
@@ -96,7 +96,7 @@ To verify whether or not an object is valid, Rails uses the +valid?+ method. You
<ruby>
class Person < ActiveRecord::Base
- validates_presence_of :name
+ validates :name, :presence => true
end
Person.create(:name => "John Doe").valid? # => true
@@ -109,14 +109,14 @@ Note that an object instantiated with +new+ will not report errors even if it's
<ruby>
class Person < ActiveRecord::Base
- validates_presence_of :name
+ validates :name, :presence => true
end
>> p = Person.new
=> #<Person id: nil, name: nil>
>> p.errors
=> {}
-
+
>> p.valid?
=> false
>> p.errors
@@ -126,7 +126,7 @@ end
=> #<Person id: nil, name: nil>
>> p.errors
=> {:name=>["can't be blank"]}
-
+
>> p.save
=> false
@@ -141,13 +141,13 @@ end
h4(#validations_overview-errors). +errors[]+
-To verify whether or not a particular attribute of an object is valid, you can use +errors[:attribute]+ that returns an array with all attribute errors, when there are no errors on the specified attribute, an empty array is returned.
+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_presence_of :name
+ validates :name, :presence => true
end
>> Person.new.errors[:name].any? # => false
@@ -197,7 +197,7 @@ 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.
+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.
@@ -235,7 +235,7 @@ This helper validates that the attributes' values are not included in a given se
<ruby>
class Account < ActiveRecord::Base
- validates_exclusion_of :subdomain, :in => %w(www),
+ validates_exclusion_of :subdomain, :in => %w(www us ca jp),
:message => "Subdomain %{value} is reserved."
end
</ruby>
@@ -314,6 +314,8 @@ class Essay < ActiveRecord::Base
end
</ruby>
+Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when +:minimum+ is 1 you should provide a personalized message or use +validates_presence_of+ instead. When +:in+ or +:within+ have a lower limit of 1, you should either provide a personalized message or call +validates_presence_of+ prior to +validates_length_of+.
+
The +validates_size_of+ helper is an alias for +validates_length_of+.
h4. +validates_numericality_of+
@@ -355,7 +357,7 @@ This helper validates that the specified attributes are not empty. It uses the +
<ruby>
class Person < ActiveRecord::Base
- validates_presence_of :name, :login, :email
+ validates :name, :login, :email, :presence => true
end
</ruby>
@@ -368,7 +370,7 @@ class LineItem < ActiveRecord::Base
end
</ruby>
-Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use +validates_inclusion_of :field_name, :in => [true, false]+.
+Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use +validates_inclusion_of :field_name, :in => [true, false]+.
The default error message for +validates_presence_of+ is "_can't be empty_".
@@ -382,7 +384,7 @@ class Account < ActiveRecord::Base
end
</ruby>
-The validation happens by performing a SQL query into the model's table, searching for an existing record with the same value in that attribute.
+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:
@@ -414,8 +416,8 @@ class Person < ActiveRecord::Base
validates_with GoodnessValidator
end
-class GoodnessValidator < ActiveRecord::Validator
- def validate
+class GoodnessValidator < ActiveModel::Validator
+ def validate(record)
if record.first_name == "Evil"
record.errors[:base] << "This person is evil"
end
@@ -425,10 +427,7 @@ end
The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class.
-The validator class has two attributes by default:
-
-* +record+ - the record to be validated
-* +options+ - the extra options that were passed to +validates_with+
+To implement the validate method, you must have an +record+ parameter defined, which is the record to be validated.
Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+:
@@ -437,8 +436,8 @@ class Person < ActiveRecord::Base
validates_with GoodnessValidator, :fields => [:first_name, :last_name]
end
-class GoodnessValidator < ActiveRecord::Validator
- def validate
+class GoodnessValidator < ActiveModel::Validator
+ def validate(record)
if options[:fields].any?{|field| record.send(field) == "Evil" }
record.errors[:base] << "This person is evil"
end
@@ -462,11 +461,11 @@ The block receives the model, the attribute's name and the attribute's value. Yo
h3. Common Validation Options
-There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which are discussed later in "Conditional Validation":#conditional-validation.
+These are common validation options:
h4. +:allow_nil+
-The +:allow_nil+ option skips the validation when the value being validated is +nil+. Using +:allow_nil+ with +validates_presence_of+ allows for +nil+, but any other +blank?+ value will still be rejected.
+The +:allow_nil+ option skips the validation when the value being validated is +nil+.
<ruby>
class Coffee < ActiveRecord::Base
@@ -475,6 +474,8 @@ class Coffee < ActiveRecord::Base
end
</ruby>
+TIP: +:allow_nil+ is ignored by the presence validator.
+
h4. +: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.
@@ -488,6 +489,8 @@ Topic.create("title" => "").valid? # => true
Topic.create("title" => nil).valid? # => true
</ruby>
+TIP: +:allow_blank+ is ignored by the presence validator.
+
h4. +: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.
@@ -505,7 +508,7 @@ class Person < ActiveRecord::Base
validates_numericality_of :age, :on => :update
# the default (validates on both create and update)
- validates_presence_of :name, :on => :save
+ validates :name, :presence => true, :on => :save
end
</ruby>
@@ -550,9 +553,9 @@ end
h3. Creating Custom Validation Methods
-When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
+When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
-Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
+Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
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.
@@ -593,7 +596,7 @@ end
h3. 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.
+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 +ActiveRecord::Errors+ documentation for a list of all the available methods.
@@ -603,7 +606,7 @@ Returns an OrderedHash with all errors. Each key is the attribute name and the v
<ruby>
class Person < ActiveRecord::Base
- validates_presence_of :name
+ validates :name, :presence => true
validates_length_of :name, :minimum => 3
end
@@ -611,7 +614,7 @@ 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 # => []
@@ -623,7 +626,7 @@ h4(#working_with_validation_errors-errors-2). +errors[]+
<ruby>
class Person < ActiveRecord::Base
- validates_presence_of :name
+ validates :name, :presence => true
validates_length_of :name, :minimum => 3
end
@@ -660,7 +663,7 @@ person.errors[:name]
person.errors.full_messages
# => ["Name cannot contain the characters !@#%*()_-+="]
</ruby>
-
+
Another way to do this is using +[]=+ setter
<ruby>
@@ -699,7 +702,7 @@ The +clear+ method is used when you intentionally want to clear all the messages
<ruby>
class Person < ActiveRecord::Base
- validates_presence_of :name
+ validates :name, :presence => true
validates_length_of :name, :minimum => 3
end
@@ -723,7 +726,7 @@ The +size+ method returns the total number of error messages for the object.
<ruby>
class Person < ActiveRecord::Base
- validates_presence_of :name
+ validates :name, :presence => true
validates_length_of :name, :minimum => 3
validates_presence_of :email
end
@@ -739,7 +742,20 @@ person.errors.size # => 0
h3. Displaying Validation Errors in the View
-Rails provides built-in helpers to display the error messages of your models in your view templates.
+Rails maintains an official plugin that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem.
+
+h4. Installing as a plugin
+<shell>
+$ rails plugin install git://github.com/joelmoss/dynamic_form.git
+</shell>
+
+h4 Installing as a Gem
+Add this line on your Gemfile:
+<ruby>
+gem "dynamic_form"
+</ruby>
+
+Now you will have access to these two methods in your view templates:
h4. +error_messages+ and +error_messages_for+
@@ -811,7 +827,7 @@ The name of the class and the id can be changed with the +:class+ and +:id+ opti
h4. Customizing the Error Messages HTML
-By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that.
+By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that.
The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters:
@@ -824,10 +840,10 @@ Here is a simple example where we change the Rails behaviour to always display t
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if instance.error_message.kind_of?(Array)
%(#{html_tag}<span class="validation-error">&nbsp;
- #{instance.error_message.join(',')}</span>)
+ #{instance.error_message.join(',')}</span>).html_safe
else
%(#{html_tag}<span class="validation-error">&nbsp;
- #{instance.error_message}</span>)
+ #{instance.error_message}</span>).html_safe
end
end
</ruby>
@@ -865,7 +881,7 @@ The macro-style class methods can also receive a block. Consider using this styl
class User < ActiveRecord::Base
validates_presence_of :login, :email
- before_create {|user| user.name = user.login.capitalize
+ before_create {|user| user.name = user.login.capitalize
if user.name.blank?}
end
</ruby>
@@ -967,7 +983,7 @@ The +after_initialize+ callback is triggered every time a new object of the clas
h3. Skipping Callbacks
-Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
+Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
* +decrement+
* +decrement_counter+
@@ -982,7 +998,7 @@ Just as with validations, it's also possible to skip callbacks. These methods sh
h3. Halting Execution
-As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
+As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
@@ -990,11 +1006,11 @@ WARNING. Raising an arbitrary exception may break code that expects +save+ and f
h3. Relational Callbacks
-Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model.
+Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model.
<ruby>
class User < ActiveRecord::Base
- has_many :posts, :dependent => :destroy
+ has_many :posts, :dependent => :destroy
end
class Post < ActiveRecord::Base
@@ -1069,7 +1085,7 @@ Here's an example where we create a class with an +after_destroy+ callback for a
<ruby>
class PictureFileCallbacks
def after_destroy(picture_file)
- File.delete(picture_file.filepath)
+ File.delete(picture_file.filepath)
if File.exists?(picture_file.filepath)
end
end
@@ -1088,7 +1104,7 @@ Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we
<ruby>
class PictureFileCallbacks
def self.after_destroy(picture_file)
- File.delete(picture_file.filepath)
+ File.delete(picture_file.filepath)
if File.exists?(picture_file.filepath)
end
end
@@ -1113,7 +1129,7 @@ h4. Creating Observers
For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality.
<shell>
-rails generate observer User
+$ rails generate observer User
</shell>
<ruby>
@@ -1128,14 +1144,14 @@ As with callback classes, the observer's methods receive the observed model as a
h4. Registering Observers
-Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/environment.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/environment.rb+ this way:
+Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/application.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/application.rb+ this way:
<ruby>
# Activate observers that should always be running
config.active_record.observers = :user_observer
</ruby>
-As usual, settings in +config/environments+ take precedence over those in +config/environment.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead.
+As usual, settings in +config/environments+ take precedence over those in +config/application.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead.
h4. Sharing Observers
@@ -1144,24 +1160,57 @@ By default, Rails will simply strip "Observer" from an observer's name to find t
<ruby>
class MailerObserver < ActiveRecord::Observer
observe :registration, :user
-
+
def after_create(model)
# code to send confirmation email...
end
end
</ruby>
-In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/environment.rb+ in order to take effect.
+In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect.
<ruby>
# Activate observers that should always be running
config.active_record.observers = :mailer_observer
</ruby>
-h3. Changelog
+h3. Transaction Callbacks
+
+There are two additional callbacks that are triggered by the completion of a database transaction: +after_commit+ and +after_rollback+. These callbacks are very similar to the +after_save+ callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
+Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after a record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error.
+
+<ruby>
+PictureFile.transaction do
+ picture_file_1.destroy
+ picture_file_2.save!
+end
+</ruby>
+
+By using the +after_commit+ callback we can account for this case.
+
+<ruby>
+class PictureFile < ActiveRecord::Base
+ attr_accessor :delete_file
+
+ after_destroy do |picture_file|
+ picture_file.delete_file = picture_file.filepath
+ end
+
+ after_commit do |picture_file|
+ if picture_file.delete_file && File.exist?(picture_file.delete_file)
+ File.delete(picture_file.delete_file)
+ picture_file.delete_file = nil
+ end
+ end
+end
+</ruby>
+
+The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.
+
+h3. Changelog
+* February 17, 2011: Add description of transaction callbacks.
* July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com
* May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* May 15, 2010: Validation Errors section updated by "Emili Parreño":http://www.eparreno.com
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index 54f766fffd..788f528654 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -1,8 +1,10 @@
h2. Active Support Core Extensions
-Active Support is the 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 Rails itself.
+Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.
-By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Rails.
+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.
+
+By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Active Support.
endprologue.
@@ -18,7 +20,7 @@ Thus, after a simple require like:
require 'active_support'
</ruby>
-objects do not even respond to +blank?+, let's see how to load its definition.
+objects do not even respond to +blank?+. Let's see how to load its definition.
h5. Cherry-picking a Definition
@@ -40,7 +42,7 @@ h5. Loading Grouped Core Extensions
The next level is to simply load all extensions to +Object+. As a rule of thumb, extensions to +SomeClass+ are available in one shot by loading +active_support/core_ext/some_class+.
-Thus, if that would do, to have +blank?+ available we could just load all extensions to +Object+:
+Thus, to load all extensions to +Object+ (including +blank?+):
<ruby>
require 'active_support/core_ext/object'
@@ -84,32 +86,25 @@ The following values are considered to be blank in a Rails application:
WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank.
-For example, this method from +ActionDispatch::Response+ uses +blank?+ to easily be robust to +nil+ and whitespace strings in one shot:
+For example, this method from +ActionDispatch::Session::AbstractStore+ uses +blank?+ for checking whether a session key is present:
<ruby>
-def charset
- charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
- charset.blank? ? nil : charset.strip.split("=")[1]
+def ensure_session_key!
+ if @key.blank?
+ raise ArgumentError, 'A key is required...'
+ end
end
</ruby>
-That's a typical use case for +blank?+.
-
-Here, the method Rails runs to instantiate observers upon initialization has nothing to do if there are none:
+The method +present?+ is equivalent to +!blank?+. This example is taken from +ActionDispatch::Http::Cache::Response+:
<ruby>
-def instantiate_observers
- return if @observers.blank?
- # ...
+def set_conditional_cache_control!
+ return if self["Cache-Control"].present?
+ ...
end
</ruby>
-The method +present?+ is equivalent to +!blank?+:
-
-<ruby>
-assert @response.body.present? # same as !@response.body.blank?
-</ruby>
-
NOTE: Defined in +active_support/core_ext/object/blank.rb+.
h4. +presence+
@@ -151,36 +146,31 @@ Active Support provides +duplicable?+ to programmatically query an object about
false.duplicable? # => false
</ruby>
-By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class objects.
+By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class and module objects.
-WARNING. Using +duplicable?+ is discouraged because it depends on a hard-coded list. Classes have means to disallow duplication like removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell.
+WARNING. Any class can disallow duplication removing +dup+ and +clone+ or raising exceptions from them, 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+.
h4. +try+
-Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first.
+Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first. +try+ is like +Object#send+ except that it returns +nil+ if sent to +nil+.
-For instance, note how this method of +ActiveRecord::ConnectionAdapters::AbstractAdapter+ checks if there's a +@logger+:
+For instance, in this code from +ActiveRecord::ConnectionAdapters::AbstractAdapter+ +@logger+ could be +nil+, but you save the check and write in an optimistic style:
<ruby>
def log_info(sql, name, ms)
- if @logger && @logger.debug?
+ if @logger.try(:debug?)
name = '%s (%.1fms)' % [name || 'SQL', ms]
@logger.debug(format_log_entry(name, sql.squeeze(' ')))
end
end
</ruby>
-You can shorten that using +Object#try+. This method is a synonym for +Object#send+ except that it returns +nil+ if sent to +nil+. The previous example could then be rewritten as:
++try+ can also be called without arguments but a block, which will only be executed if the object is not nil:
<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
+@person.try { |p| "#{p.first_name} #{p.last_name}" }
</ruby>
NOTE: Defined in +active_support/core_ext/object/try.rb+.
@@ -364,7 +354,7 @@ That idiom may convey _grouping_ to the reader as well. For example, say you wan
<ruby>
I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
subject i18n.t :subject
- body i18n.t :body, :user_name => user.name
+ body i18n.t :body, :user_name => user.name
end
</ruby>
@@ -411,39 +401,6 @@ C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
-h5. +copy_instance_variables_from(object, exclude = [])+
-
-Copies the instance variables of +object+ into +self+.
-
-Instance variable names in the +exclude+ array are ignored. If +object+
-responds to +protected_instance_variables+ the ones returned are
-also ignored. For example, Rails controllers implement that method.
-
-In both arrays strings and symbols are understood, and they have to include
-the at sign.
-
-<ruby>
-class C
- def initialize(x, y, z)
- @x, @y, @z = x, y, z
- end
-
- def protected_instance_variables
- %w(@z)
- end
-end
-
-a = C.new(0, 1, 2)
-b = C.new(3, 4, 5)
-
-a.copy_instance_variables_from(b, [:@y])
-# a is now: @x = 3, @y = 1, @z = 2
-</ruby>
-
-In the example +object+ and +self+ are of the same type, but they don't need to.
-
-NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
-
h4. 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:
@@ -475,7 +432,7 @@ h4. +require_library_or_gem+
The convenience method +require_library_or_gem+ tries to load its argument with a regular +require+ first. If it fails loads +rubygems+ and tries again.
-If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. On the other hand, if +rubygems+ is available but the argument is not loadable as a gem, the method gives up and +LoadError+ is also raised.
+If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. A +LoadError+ is also raised if +rubygems+ is available but the argument is not loadable as a gem.
For example, that's the way the MySQL adapter loads the MySQL library:
@@ -541,12 +498,12 @@ h4. Attributes
h5. +alias_attribute+
-Model attributes have a reader, a writer, and a predicate. You can aliase a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
+Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
<ruby>
class User < ActiveRecord::Base
# let me refer to the email column as "login",
- # much meaningful for authentication code
+ # possibly meaningful for authentication code
alias_attribute :login, :email
end
</ruby>
@@ -571,7 +528,7 @@ The default value can be also specified with a block, which is called in the con
class User
attr_accessor :name, :surname
attr_accessor_with_default(:full_name) {
- [name, surname].compact.join(" ")
+ [name, surname].compact.join(" ")
}
end
@@ -606,7 +563,7 @@ h5. Internal Attributes
When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.
-Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
+Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
@@ -778,7 +735,7 @@ class Counter
end
</ruby>
-The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block.
+The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block.
NOTE: Defined in +active_support/core_ext/module/synchronization.rb+.
@@ -1034,7 +991,7 @@ a2.x # => 2, overridden in a2
The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in
<ruby>
-module AcitveRecord
+module ActiveRecord
class Base
class_attribute :table_name_prefix, :instance_writer => false
self.table_name_prefix = ""
@@ -1044,7 +1001,7 @@ end
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
-For convenience +class_attribute+ defines also an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
+For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
NOTE: Defined in +active_support/core_ext/class/attribute.rb+
@@ -1088,6 +1045,8 @@ NOTE: Defined in +active_support/core_ext/class/attribute_accessors.rb+.
h4. Class Inheritable Attributes
+WARNING: Class Inheritable Attributes are deprecated. It's recommended that you use +Class#class_attribute+ instead.
+
Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide accessors for class-level data which is inherited but not shared with children:
<ruby>
@@ -1123,7 +1082,7 @@ module ActiveRecord
end
</ruby>
-Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point.
+Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point.
NOTE: Defined in +active_support/core_ext/class/inheritable_attributes.rb+.
@@ -1155,7 +1114,7 @@ NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
h5. +descendants+
-The +descendants+ method returns all classes that are <tt>&lt;</tt> than its receiver:
+The +descendants+ method returns all classes that are <tt>&lt;</tt> than its receiver:
<ruby>
class C; end
@@ -1232,6 +1191,12 @@ To insert something verbatim use the +raw+ helper rather than calling +html_safe
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
</erb>
+or, equivalently, use <tt><%==</tt>:
+
+<erb>
+<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
+</erb>
+
The +raw+ helper calls +html_safe+ for you:
<ruby>
@@ -1276,7 +1241,7 @@ 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 dea..."
"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ')
# => "Oh dear! Oh..."
</ruby>
@@ -1301,7 +1266,7 @@ Active Support adds that functionality to <tt>%</tt> in previous versions of Rub
NOTE: Defined in +active_support/core_ext/string/interpolation.rb+.
-h4. +starts_with?+ and +ends_width?+
+h4. +starts_with?+ and +ends_with?+
Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:
@@ -1312,6 +1277,31 @@ Active Support defines 3rd person aliases of +String#start_with?+ and +String#en
NOTE: Defined in +active_support/core_ext/string/starts_ends_with.rb+.
+h4. +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
+</ruby>
+
+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+.
+
h4. Access
h5. +at(position)+
@@ -1580,7 +1570,7 @@ The method +tableize+ is +underscore+ followed by +pluralize+.
"InvoiceLine".tableize # => "invoice_lines"
</ruby>
-As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes de class name and checks a few options that may affect the returned string.
+As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
@@ -1701,27 +1691,7 @@ foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-h4. Conversions
-
-h5. +constantize+
-
-The method +constantize+ expects the receiver to contain the name of a constant, and tries to get you the object stored in there, assuming it is defined:
-
-<ruby>
-"ActiveRecord::Base".constantize # => ActiveRecord::Base
-</ruby>
-
-The name is assumed to be top-level, no matter whether it starts with "::" or not. No lexical context is taken into account:
-
-<ruby>
-C = 1
-module M
- C = 2
- "C".constantize # => 1, same as "::C".constantize
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
+h4(#string-conversions). Conversions
h5. +ord+
@@ -1767,7 +1737,7 @@ The methods +to_date+, +to_time+, and +to_datetime+ are basically convenience wr
<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
+"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
</ruby>
+to_time+ receives an optional argument +:utc+ or +:local+, to indicate which time zone you want the time in:
@@ -1848,7 +1818,7 @@ h3. Extensions to +Float+
h4. +round+
-The built-in method +Float#round+ rounds a float to the nearest integer. Active Support adds an optional parameter to let you specify a precision:
+The built-in method +Float#round+ rounds a float to the nearest integer. In Ruby 1.9 this method takes an optional argument to let you specify a precision. Active Support adds that functionality to +round+ in previous versions of Ruby:
<ruby>
Math::E.round(4) # => 2.7183
@@ -1900,7 +1870,7 @@ The sum of an empty collection is zero by default, but this is customizable:
[].sum(1) # => 1
</ruby>
-If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
+If a block is given, +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
<ruby>
(1..5).sum {|n| n * 2 } # => 30
@@ -1928,7 +1898,7 @@ h4. +each_with_object+
The +inject+ method offers iteration with an accumulator:
<ruby>
-[2, 3, 4].inject(1) {|acc, i| product*i } # => 24
+[2, 3, 4].inject(1) {|product, i| product*i } # => 24
</ruby>
The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:
@@ -1974,7 +1944,7 @@ The method +many?+ is shorthand for +collection.size > 1+:
<% end %>
</erb>
-If an optional block is given +many?+ only takes into account those elements that return true:
+If an optional block is given, +many?+ only takes into account those elements that return true:
<ruby>
@see_more = videos.many? {|video| video.category == params[:category]}
@@ -1984,7 +1954,7 @@ NOTE: Defined in +active_support/core_ext/enumerable.rb+.
h4. +exclude?+
-The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+:
+The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the built-in +include?+:
<ruby>
to_visit << node if visited.exclude?(node)
@@ -2039,9 +2009,9 @@ User.exists?(:email => params[:email])
That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
-If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role.
+If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
-In those cases, you may give an options hash a distinguished treatment with +extract_options!+. That method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise returns an empty hash.
+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:
@@ -2057,7 +2027,7 @@ This method receives an arbitrary number of action names, and an optional hash o
NOTE: Defined in +active_support/core_ext/array/extract_options.rb+.
-h4. Conversions
+h4(#array-conversions). Conversions
h5. +to_sentence+
@@ -2222,7 +2192,7 @@ Array.wrap(0) # => [0]
This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Arraw.wrap</tt> returns such a +nil+ right away.
+* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns +nil+ right away.
* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
* It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
@@ -2242,7 +2212,7 @@ There's also a related idiom that uses the splat operator:
[*object]
</ruby>
-which returns +[nil]+ for +nil+, and calls to <tt>Array(object)</tt> otherwise
+which in Ruby 1.8 returns +[nil]+ for +nil+, and calls to <tt>Array(object)</tt> 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 <tt>Kernel#Array</tt> explained above apply to the rest of +object+s.
@@ -2745,6 +2715,14 @@ WARNING: The original +Range#include?+ is still the one aliased to +Range#===+.
NOTE: Defined in +active_support/core_ext/range/include_range.rb+.
+h4. +cover?+
+
+Ruby 1.9 provides +cover?+, and Active Support defines it for previous versions as an alias for +include?+.
+
+The method +include?+ in Ruby 1.9 is different from the one in 1.8 for non-numeric ranges: instead of being based on comparisons between the value and the range's endpoints, it walks the range with +succ+ looking for value. This works better for ranges with holes, but it has different complexity and may not finish in some other cases.
+
+In Ruby 1.9 the old behavior is still available in the new +cover?+, which Active Support backports for forward compatibility. For example, Rails uses +cover?+ for ranges in +validates_inclusion_of+.
+
h4. +overlaps?+
The method +Range#overlaps?+ says whether any two given ranges have non-void intersection:
@@ -2815,6 +2793,8 @@ h5. +Date.current+
Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors the user time zone, if defined. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+.
+When making Date comparisons using methods which honor the user time zone, make sure to use +Date.current+ and not +Date.today+. There are cases where the user time zone might be in the future compared to the system time zone, which +Date.today+ uses by default. This means +Date.today+ may equal +Date.yesterday+.
+
h5. Named dates
h6. +prev_year+, +next_year+
@@ -2870,9 +2850,9 @@ d.end_of_week # => Sun, 09 May 2010
+beginning_of_week+ is aliased to +monday+ and +at_beginning_of_week+. +end_of_week+ is aliased to +sunday+ and +at_end_of_week+.
-h6. +next_week+
+h6. +prev_week+, +next_week+
-+next_week+ receives a symbol with a day name in English (in lowercase, default is +:monday+) and it returns the date corresponding to that day in the next week:
+The method +next_week+ receives a symbol with a day name in English (in lowercase, default is +:monday+) and it returns the date corresponding to that day:
<ruby>
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
@@ -2880,6 +2860,14 @@ d.next_week # => Mon, 10 May 2010
d.next_week(:saturday) # => Sat, 15 May 2010
</ruby>
+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
+</ruby>
+
h6. +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:
@@ -2957,6 +2945,15 @@ Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
</ruby>
+h6. +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
+</ruby>
+
h6. +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:
@@ -3001,7 +2998,7 @@ Date.new(2010, 1, 31).change(:month => 2)
# => ArgumentError: invalid date
</ruby>
-h5. Durations
+h5(#date-durations). Durations
Durations can be added and substracted to dates:
@@ -3048,14 +3045,14 @@ h6. +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 = Date.current # => Fri, 11 Jun 2010
date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
</ruby>
Similarly, +since+ moves forward:
<ruby>
-date = Date.current # => Fri, 11 Jun 2010
+date = Date.current # => Fri, 11 Jun 2010
date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
</ruby>
@@ -3078,6 +3075,8 @@ yesterday
tomorrow
beginning_of_week (monday, at_beginning_of_week)
end_on_week (at_end_of_week)
+weeks_ago
+prev_week
next_week
months_ago
months_since
@@ -3110,7 +3109,7 @@ h5. Named Datetimes
h6. +DateTime.current+
-Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines instance predicates +past?+, and +future?+ relative to +DateTime.current+.
+Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines +DateTime.yesterday+ and +DateTime.tomorrow+, and the instance predicates +past?+, and +future?+ relative to +DateTime.current+.
h5. Other Extensions
@@ -3207,7 +3206,7 @@ DateTime.current.change(:month => 2, :day => 30)
# => ArgumentError: invalid date
</ruby>
-h5. Durations
+h5(#datetime-durations). Durations
Durations can be added and substracted to datetimes:
@@ -3250,6 +3249,8 @@ beginning_of_day (midnight, at_midnight, at_beginning_of_day)
end_of_day
beginning_of_week (monday, at_beginning_of_week)
end_on_week (at_end_of_week)
+weeks_ago
+prev_week
next_week
months_ago
months_since
@@ -3285,6 +3286,12 @@ t.advance(:seconds => 1)
* If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead.
+h5. +Time.current+
+
+Active Support defines +Time.current+ to be today in the current time zone. That's like +Time.now+, except that it honors the user time zone, if defined. It also defines +Time.yesterday+ and +Time.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Time.current+.
+
+When making Time comparisons using methods which honor the user time zone, make sure to use +Time.current+ and not +Time.now+. There are cases where the user time zone might be in the future compared to the system time zone, which +Time.today+ uses by default. This means +Time.now+ may equal +Time.yesterday+.
+
h4. Time Constructors
Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+:
@@ -3320,7 +3327,7 @@ Both +local_time+ and +utc_time+ accept up to seven positional arguments: year,
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.
-h5. Durations
+h5(#time-durations). Durations
Durations can be added and substracted to time objects:
@@ -3370,6 +3377,49 @@ The auxiliary file is written in a standard directory for temporary files, but y
NOTE: Defined in +active_support/core_ext/file/atomic.rb+.
+h3. Extensions to +Logger+
+
+h4. +around_[level]+
+
+Takes two arguments, a +before_message+ and +after_message+ and calls the current level method on the +Logger+ instance, passing in the +before_message+, then the specified message, then the +after_message+:
+
+<ruby>
+ logger = Logger.new("log/development.log")
+ logger.around_info("before", "after") { |logger| logger.info("during") }
+</ruby>
+
+h4. +silence+
+
+Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.
+
+<ruby>
+ logger = Logger.new("log/development.log")
+ logger.silence(Logger::INFO) do
+ logger.debug("In space, no one can hear you scream.")
+ logger.info("Scream all you want, small mailman!")
+ end
+</ruby>
+
+h4. +datetime_format=+
+
+Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a +datetime_format+ method then this is ignored.
+
+<ruby>
+ class Logger::FormatWithTime < Logger::Formatter
+ cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
+
+ def self.call(severity, timestamp, progname, msg)
+ "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
+ end
+ end
+
+ logger = Logger.new("log/development.log")
+ logger.formatter = Logger::FormatWithTime
+ logger.info("<- is the current time")
+</ruby>
+
+NOTE: Defined in +active_support/core_ext/logger.rb+.
+
h3. Extensions to +NameError+
Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument.
@@ -3418,7 +3468,5 @@ NOTE: Defined in +active_support/core_ext/load_error.rb+.
h3. Changelog
-"Lighthouse ticket":https://rails.lighthouseapp.com/projects/16213/tickets/67
-
* August 10, 2010: Starts to take shape, added to the index.
* April 18, 2009: Initial version by "Xavier Noria":credits.html#fxn
diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile
index 8a38cf2dc2..b80df4aa58 100644
--- a/railties/guides/source/ajax_on_rails.textile
+++ b/railties/guides/source/ajax_on_rails.textile
@@ -1,10 +1,10 @@
h2. AJAX on Rails
-This guide covers the built-in Ajax/Javascript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
+This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
* Quick introduction to AJAX and related technologies
-* Handling Javascript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
-* Testing Javascript functionality
+* Handling JavaScript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
+* Testing JavaScript functionality
endprologue.
@@ -12,7 +12,7 @@ h3. Hello AJAX - a Quick Intro
If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails.
-h4. Asynchronous Javascript + XML
+h4. Asynchronous JavaScript + XML
Basic terminology, new style of creating web apps
@@ -31,7 +31,7 @@ How do 'standard' and AJAX requests differ, why does this matter for understandi
h3. Built-in Rails Helpers
-Rails' Javascript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose Javascript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other Javascript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
+Rails' JavaScript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose JavaScript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other JavaScript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
To get access to these helpers, all you have to do is to include the prototype framework in your pages - typically in your master layout, application.html.erb - like so:
<ruby>
@@ -42,12 +42,12 @@ You are ready to add some AJAX love to your Rails app!
h4. The Quintessential AJAX Rails Helper: link_to_remote
-Let's start with the the probably most often used helper: +link_to_remote+, which has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers.
+Let's start with what is probably the most often used helper: +link_to_remote+. It has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers.
The signature of +link_to_remote+ function is the same as that of the standard +link_to+ helper:
<ruby>
-def link_to_remote(name, options = {}, html_options = nil)
+def link_to_remote(name, options = {}, html_options = nil)
</ruby>
And here is a simple example of link_to_remote in action:
@@ -98,7 +98,7 @@ link_to_remote "Delete the item",
Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy.
** *JavaScript filters* You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one:
-*** +:confirm+ =&gt; +msg+ Pops up a JavaScript confirmation dialog, displaying +msg+. If the user chooses 'OK', the request is launched, otherwise canceled.
+*** +:confirm+ =&gt; +msg+ Pops up a JavaScript confirmation dialog, displaying +msg+. If the user chooses 'OK', the request is launched, otherwise canceled.
*** +:condition+ =&gt; +code+ Evaluates +code+ (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
*** +:before+ =&gt; +code+ Evaluates the +code+ just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example).
*** +:after+ =&gt; +code+ Evaluates the +code+ after launching the request. Note that this is different from the +:success+ or +:complete+ callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to +:after+ is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed.
@@ -115,8 +115,8 @@ link_to_remote "Update record",
This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id).
** *Callbacks* Since an AJAX call is typically asynchronous, as it's name suggests (this is not a rule, and you can fire a synchronous request - see the last option, +:type+) your only way of communicating with a request once it is fired is via specifying callbacks. There are six options at your disposal (in fact 508, counting all possible response types, but these six are the most frequent and therefore specified by a constant):
-*** +:loading:+ =&gt; +code+ The request is in the process of receiving the data, but the transfer is not completed yet.
-*** +:loaded:+ =&gt; +code+ The transfer is completed, but the data is not processed and returned yet
+*** +:loading:+ =&gt; +code+ The request is in the process of receiving the data, but the transfer is not completed yet.
+*** +:loaded:+ =&gt; +code+ The transfer is completed, but the data is not processed and returned yet
*** +:interactive:+ =&gt; +code+ One step after +:loaded+: The data is fully received and being processed
*** +:success:+ =&gt; +code+ The data is fully received, parsed and the server responded with "200 OK"
*** +:failure:+ =&gt; +code+ The data is fully received, parsed and the server responded with *anything* but "200 OK" (typically 404 or 500, but in general with any status code ranging from 100 to 509)
@@ -136,24 +136,24 @@ link_to_remote "Add new item",
:before => "$('progress').show()",
:complete => "$('progress').hide()",
:success => "display_item_added(request)",
- :failure => "display_error(request)",
+ :failure => "display_error(request)"
</ruby>
** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+.
* Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though:
** If you specify the +href+ parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser
** +link_to_remote+ gains it's AJAX behavior by specifying the remote call in the onclick handler of the link. If you supply +html_options[:onclick]+ you override the default behavior, so use this with care!
-We are finished with +link_to_remote+. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections.
+We are finished with +link_to_remote+. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections.
h4. AJAX Forms
There are three different ways of adding AJAX forms to your view using Rails Prototype helpers. They are slightly different, but striving for the same goal: instead of submitting the form using the standard HTTP request/response cycle, it is submitted asynchronously, thus not reloading the page. These methods are the following:
* +remote_form_for+ (and it's alias +form_remote_for+) is tied to Rails most tightly of the three since it takes a resource, model or array of resources (in case of a nested resource) as a parameter.
-* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background
-* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
+* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background
+* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
-Let's se them in action one by one!
+Let's see them in action one by one!
h5. +remote_form_for+
@@ -161,7 +161,7 @@ h5. +form_remote_tag+
h5. +submit_to_remote+
-h4. Observing Elements
+h4. Observing Elements
h5. +observe_field+
@@ -183,13 +183,13 @@ h3. JavaScript the Rails way: RJS
In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code.
-h4. Javascript without RJS
+h4. JavaScript without RJS
First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood.
-
+
<ruby>
def javascript_test
- render :text => "alert('Hello, world!')",
+ render :text => "alert('Hello, world!')",
:content_type => "text/javascript"
end
</ruby>
@@ -207,14 +207,14 @@ def javascript_test
render :update do |page|
page.alert "Hello from inline RJS"
end
-end
+end
</ruby>
-The above code snippet does exactly the same as the one in the previous section - going about it much more elegantly though. You don't need to worry about headers,write ugly JavaScript code into a string etc. When the first parameter to +render+ is +:update+, Rails expects a block with a single parameter (+page+ in our case, which is the traditional naming convention) which is an instance of the JavaScriptGenerator:"http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html" object. As it's name suggests, JavaScriptGenerator is responsible for generating JavaScript from your Ruby code. You can execute multiple method calls on the +page+ instance - it's all turned into JavaScript code and sent to the server with the appropriate Content Type, "text/javascript".
+The above code snippet does exactly the same as the one in the previous section - going about it much more elegantly though. You don't need to worry about headers,write ugly JavaScript code into a string etc. When the first parameter to +render+ is +:update+, Rails expects a block with a single parameter (+page+ in our case, which is the traditional naming convention) which is an instance of the JavaScriptGenerator:"http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html" object. As it's name suggests, JavaScriptGenerator is responsible for generating JavaScript from your Ruby code. You can execute multiple method calls on the +page+ instance - it's all turned into JavaScript code and sent to the server with the appropriate Content Type, "text/javascript".
h4. RJS Templates
-If you don't want to clutter your controllers with view code (especially when your inline RJS is more than a few lines), you can move your RJS code to a template file. RJS templates should go to the +/app/views/+ directory, just as +.html.erb+ or any other view files of the appropriate controller, conventionally named +js.rjs+.
+If you don't want to clutter your controllers with view code (especially when your inline RJS is more than a few lines), you can move your RJS code to a template file. RJS templates should go to the +/app/views/+ directory, just as +.html.erb+ or any other view files of the appropriate controller, conventionally named +js.rjs+.
To rewrite the above example, you can leave the body of the action empty, and create a RJS template named +javascript_test.js.rjs+, containing the following line:
@@ -265,7 +265,7 @@ The third parameter can either be a string, or a hash of options to be passed to
page.insert_html :top, :result, :partial => "the_answer"
</ruby>
-You can replace the contents (innerHTML) of an element with the +replace_html+ method. The only difference is that since it's clear where should the new content go, there is no need for a position parameter - so +replace_html+ takes only two arguments,
+You can replace the contents (innerHTML) of an element with the +replace_html+ method. The only difference is that since it's clear where should the new content go, there is no need for a position parameter - so +replace_html+ takes only two arguments,
the DOM id of the element you wish to modify and a string or a hash of options to be passed to ActionView::Base#render.
h6. Delay
@@ -273,7 +273,7 @@ h6. Delay
You can delay the execution of a block of code with +delay+:
<ruby>
-page.delay(10) { page.alert('Hey! Just waited 10 seconds') }
+page.delay(10) { page.alert('Hey! Just waited 10 seconds') }
</ruby>
+delay+ takes one parameter (time to wait in seconds) and a block which will be executed after the specified time has passed - whatever else follows a +page.delay+ line is executed immediately, the delay affects only the code in the block.
@@ -283,7 +283,7 @@ h6. Reloading and Redirecting
You can reload the page with the +reload+ method:
<ruby>
-page.reload
+page.reload
</ruby>
When using AJAX, you can't rely on the standard +redirect_to+ controller method - you have to use the +page+'s instance method, also called +redirect_to+:
@@ -292,7 +292,7 @@ When using AJAX, you can't rely on the standard +redirect_to+ controller method
page.redirect_to some_url
</ruby>
-h6. Generating Arbitrary JavaScript
+h6. Generating Arbitrary JavaScript
Sometimes even the full power of RJS is not enough to accomplish everything, but you still don't want to drop to pure JavaScript. A nice golden mean is offered by the combination of +<<+, +assign+ and +call+ methods:
@@ -329,9 +329,9 @@ h4. Drag and Drop
-h3. Testing Javascript
+h3. Testing JavaScript
-Javascript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with Javascript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
+JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
* (Fire)Watir
* Selenium
@@ -339,4 +339,4 @@ Javascript testing reminds me the definition of the world 'classic' by Mark Twai
* Cucumber+Webrat
* Mention stuff like screw.unit/jsSpec
-Note to self: check out the RailsConf JS testing video \ No newline at end of file
+Note to self: check out the RailsConf JS testing video
diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile
index 9f201de49b..7433507866 100644
--- a/railties/guides/source/api_documentation_guidelines.textile
+++ b/railties/guides/source/api_documentation_guidelines.textile
@@ -6,7 +6,7 @@ endprologue.
h3. RDoc
-The Rails API documentation is generated with RDoc 2.5. Please consult the "RDoc documentation":http://rdoc.rubyforge.org/RDoc.htmlFor for help with its markup.
+The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc/Markup.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html.
h3. Wording
@@ -25,11 +25,13 @@ end
Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the recommended idioms 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?
+Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?
-The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :).
+The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal.
-Spell names correctly: HTML, MySQL, JavaScript, ERb. Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database".
+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".
h3. Example Code
@@ -44,10 +46,10 @@ Short docs do not need an explicit "Examples" label to introduce snippets, they
# Converts a collection of elements into a formatted string by calling
# <tt>to_s</tt> on all elements and joining them.
#
-# Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post"
+# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
</ruby>
-On the other hand big chunks of structured documentation may have a separate "Examples" section:
+On the other hand, big chunks of structured documentation may have a separate "Examples" section:
<ruby>
# ==== Examples
@@ -114,18 +116,16 @@ Use fixed-width fonts for:
* file names
<ruby>
-# Copies the instance variables of +object+ into +self+.
-#
-# Instance variable names in the +exclude+ array are ignored. If +object+
-# responds to <tt>protected_instance_variables</tt> the ones returned are
-# also ignored. For example, Rails controllers implement that method.
-# ...
-def copy_instance_variables_from(object, exclude = [])
- ...
+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
</ruby>
-WARNING: Using a pair of +&#43;...&#43;+ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w&#43;\z</tt>. For anything else use +&lt;tt&gt;...&lt;/tt&gt;+, notably symbols, setters, inline snippets, etc:
+WARNING: Using a pair of +&#43;...&#43;+ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w&#43;\z</tt>. For anything else use +&lt;tt&gt;...&lt;/tt&gt;+, notably symbols, setters, inline snippets, etc:
h4. Regular Font
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index b1ee4b8be4..e5b8c73c43 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -30,7 +30,7 @@ Now, suppose we wanted to add a new order for an existing customer. We'd need to
Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
<ruby>
-@orders = Order.find_all_by_customer_id(@customer.id)
+@orders = Order.where(:customer_id => @customer.id)
@orders.each do |order|
order.destroy
end
@@ -65,7 +65,7 @@ To learn more about the different types of associations, read the next section o
h3. The Types of Associations
-In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
+In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations:
* +belongs_to+
* +has_one+
@@ -165,6 +165,12 @@ class Paragraph < ActiveRecord::Base
end
</ruby>
+With +:through => :sections+ specified, Rails will now understand:
+
+<ruby>
+@document.paragraphs
+</ruby>
+
h4. The +has_one :through+ Association
A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
@@ -550,7 +556,9 @@ build_customer
create_customer
</ruby>
-h6. _association_(force_reload = false)
+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.
+
+h6(#belongs_to-association). <tt><em>association</em>(force_reload = false)</tt>
The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
@@ -560,7 +568,7 @@ The <tt><em>association</em></tt> method returns the associated object, if any.
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.
-h6. _association_=(associate)
+h6(#belongs_to-association_equal). <tt>_association_=(associate)</tt>
The <tt><em>association</em>=</tt> 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.
@@ -568,7 +576,7 @@ The <tt><em>association</em>=</tt> method assigns an associated object to this o
@order.customer = @customer
</ruby>
-h6. build_<em>association</em>(attributes = {})
+h6(#belongs_to-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
@@ -577,7 +585,7 @@ The <tt>build_<em>association</em></tt> method returns a new object of the assoc
:customer_name => "John Doe")
</ruby>
-h6. create_<em>association</em>(attributes = {})
+h6(#belongs_to-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
@@ -629,7 +637,7 @@ end
h6(#belongs_to-conditions). +:conditions+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
<ruby>
class Order < ActiveRecord::Base
@@ -637,7 +645,7 @@ class Order < ActiveRecord::Base
end
</ruby>
-h6. +:counter_cache+
+h6(#belongs_to-counter_cache). +:counter_cache+
The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
@@ -733,7 +741,7 @@ end
NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
-h6. +:polymorphic+
+h6(#belongs_to-polymorphic). +: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>.
@@ -747,7 +755,7 @@ The +:select+ option lets you override the SQL +SELECT+ clause that is used to r
TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.
-h6. +:touch+
+h6(#belongs_to-touch). +:touch+
If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
@@ -817,7 +825,9 @@ build_account
create_account
</ruby>
-h6. <tt><em>association</em>(force_reload = false)</tt>
+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.
+
+h6(#has_one-association). <tt><em>association</em>(force_reload = false)</tt>
The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
@@ -827,7 +837,7 @@ The <tt><em>association</em></tt> method returns the associated object, if any.
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.
-h6. <tt><em>association</em>=(associate)</tt>
+h6(#has_one-association_equal). <tt><em>association</em>=(associate)</tt>
The <tt><em>association</em>=</tt> 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.
@@ -835,7 +845,7 @@ The <tt><em>association</em>=</tt> method assigns an associated object to this o
@supplier.account = @account
</ruby>
-h6. <tt>build_<em>association</em>(attributes = {})</tt>
+h6(#has_one-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
@@ -843,7 +853,7 @@ The <tt>build_<em>association</em></tt> method returns a new object of the assoc
@account = @supplier.build_account(:terms => "Net 30")
</ruby>
-h6. <tt>create_<em>association</em>(attributes = {})</tt>
+h6(#has_one-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
@@ -899,7 +909,7 @@ end
h6(#has_one-conditions). +:conditions+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
<ruby>
class Supplier < ActiveRecord::Base
@@ -961,7 +971,7 @@ end
h6(#has_one-order). +:order+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
h6(#has_one-primary_key). +:primary_key+
@@ -985,7 +995,7 @@ The +:source_type+ option specifies the source association type for a +has_one :
h6(#has_one-through). +:through+
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has-one-through-association">earlier in this guide</a>.
+The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.
h6(#has_one-validate). +:validate+
@@ -1029,6 +1039,7 @@ When you declare a +has_many+ association, the declaring class automatically gai
* <tt><em>collection</em>.empty?</tt>
* <tt><em>collection</em>.size</tt>
* <tt><em>collection</em>.find(...)</tt>
+* <tt><em>collection</em>.where(...)</tt>
* <tt><em>collection</em>.exists?(...)</tt>
* <tt><em>collection</em>.build(attributes = {}, ...)</tt>
* <tt><em>collection</em>.create(attributes = {})</tt>
@@ -1054,6 +1065,7 @@ orders.clear
orders.empty?
orders.size
orders.find(...)
+orders.where(...)
orders.exists?(...)
orders.build(attributes = {}, ...)
orders.create(attributes = {})
@@ -1083,10 +1095,10 @@ The <tt><em>collection</em>.delete</tt> method removes one or more objects from
@customer.orders.delete(@order1)
</ruby>
-WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
+WARNING: Additionally, objects will be destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
-h6(#has_many-collection_equal). <tt><em>collection</em>=objects</tt>
+h6(#has_many-collection-equal). <tt><em>collection</em>=objects</tt>
The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
@@ -1102,11 +1114,11 @@ h6(#has_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=
The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-h6(#has_many-collection_clear). <tt><em>collection</em>.clear</tt>
+h6(#has_many-collection-clear). <tt><em>collection</em>.clear</tt>
The <tt><em>collection</em>.clear</tt> 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+.
-h6. <tt><em>collection</em>.empty?</tt>
+h6(#has_many-collection-empty). <tt><em>collection</em>.empty?</tt>
The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
@@ -1116,7 +1128,7 @@ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection
<% end %>
</ruby>
-h6. <tt><em>collection</em>.size</tt>
+h6(#has_many-collection-size). <tt><em>collection</em>.size</tt>
The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
@@ -1124,19 +1136,30 @@ The <tt><em>collection</em>.size</tt> method returns the number of objects in th
@order_count = @customer.orders.size
</ruby>
-h6. <tt><em>collection</em>.find(...)</tt>
+h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt>
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
<ruby>
-@open_orders = @customer.orders.find(:all, :conditions => "open = 1")
+@open_orders = @customer.orders.all(:conditions => "open = 1")
</ruby>
-h6. <tt><em>collection</em>.exists?(...)</tt>
+NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
+
+h6(#has_many-collection-where). <tt><em>collection</em>.where(...)</tt>
+
+The <tt><em>collection</em>.where</tt> 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>
+@open_orders = @customer.orders.where(:open => true) # No query yet
+@open_order = @open_orders.first # Now the database will be queried
+</ruby>
+
+h6(#has_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
-h6. <tt><em>collection</em>.build(attributes = {}, ...)</tt>
+h6(#has_many-collection-build). <tt><em>collection</em>.build(attributes = {}, ...)</tt>
The <tt><em>collection</em>.build</tt> 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.
@@ -1145,7 +1168,7 @@ The <tt><em>collection</em>.build</tt> method returns one or more new objects of
:order_number => "A12345")
</ruby>
-h6. <tt><em>collection</em>.create(attributes = {})</tt>
+h6(#has_many-collection-create). <tt><em>collection</em>.create(attributes = {})</tt>
The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
@@ -1193,7 +1216,7 @@ h6(#has_many-as). +:as+
Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
-h6. +:autosave+
+h6(#has_many-autosave). +: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.
@@ -1209,7 +1232,7 @@ end
h6(#has_many-conditions). +:conditions+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
<ruby>
class Customer < ActiveRecord::Base
@@ -1335,7 +1358,7 @@ The +:offset+ option lets you specify the starting offset for fetching objects v
h6(#has_many-order). +:order+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+The +:order+ option 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
@@ -1367,7 +1390,7 @@ The +:source_type+ option specifies the source association type for a +has_many
h6(#has_many-through). +: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>.
+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>.
h6(#has_many-uniq). +:uniq+
@@ -1401,8 +1424,8 @@ 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>]
+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>]
</ruby>
In the above case there are still two readings. However +person.posts+ shows only one post because the collection loads only unique records.
@@ -1439,11 +1462,12 @@ When you declare a +has_and_belongs_to_many+ association, the declaring class au
* <tt><em>collection</em>.empty?</tt>
* <tt><em>collection</em>.size</tt>
* <tt><em>collection</em>.find(...)</tt>
+* <tt><em>collection</em>.where(...)</tt>
* <tt><em>collection</em>.exists?(...)</tt>
* <tt><em>collection</em>.build(attributes = {})</tt>
* <tt><em>collection</em>.create(attributes = {})</tt>
-In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:
+In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol. For example, given the declaration:
<ruby>
class Part < ActiveRecord::Base
@@ -1464,6 +1488,7 @@ assemblies.clear
assemblies.empty?
assemblies.size
assemblies.find(...)
+assemblies.where(...)
assemblies.exists?(...)
assemblies.build(attributes = {}, ...)
assemblies.create(attributes = {})
@@ -1476,7 +1501,7 @@ If the join table for a +has_and_belongs_to_many+ association has additional col
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+.
-h6. <tt><em>collection</em>(force_reload = false)</tt>
+h6(#has_and_belongs_to_many-collection). <tt><em>collection</em>(force_reload = false)</tt>
The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
@@ -1484,7 +1509,7 @@ The <tt><em>collection</em></tt> method returns an array of all of the associate
@assemblies = @part.assemblies
</ruby>
-h6. <tt><em>collection</em><<(object, ...)</tt>
+h6(#has_and_belongs_to_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt>
The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.
@@ -1494,7 +1519,7 @@ The <tt><em>collection</em><<</tt> method adds one or more objects to the collec
NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.
-h6. <tt><em>collection</em>.delete(object, ...)</tt>
+h6(#has_and_belongs_to_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt>
The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
@@ -1502,11 +1527,11 @@ The <tt><em>collection</em>.delete</tt> method removes one or more objects from
@part.assemblies.delete(@assembly1)
</ruby>
-h6. <tt><em>collection</em>=objects</tt>
+h6(#has_and_belongs_to_many-collection-equal). <tt><em>collection</em>=objects</tt>
The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
-h6. <tt><em>collection_singular</em>_ids</tt>
+h6(#has_and_belongs_to_many-collection_singular). <tt><em>collection_singular</em>_ids</tt>
The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
@@ -1514,11 +1539,11 @@ The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids
@assembly_ids = @part.assembly_ids
</ruby>
-h6. <tt><em>collection_singular</em>_ids=ids</tt>
+h6(#has_and_belongs_to_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt>
The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-h6. <tt><em>collection</em>.clear</tt>
+h6(#has_and_belongs_to_many-collection-clear). <tt><em>collection</em>.clear</tt>
The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
@@ -1545,15 +1570,25 @@ h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)<
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
<ruby>
-@new_assemblies = @part.assemblies.find(:all,
+@new_assemblies = @part.assemblies.all(
:conditions => ["created_at > ?", 2.days.ago])
</ruby>
+NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
+
+h6(#has_and_belongs_to_many-collection-where). <tt><em>collection</em>.where(...)</tt>
+
+The <tt><em>collection</em>.where</tt> 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>
+@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
+</ruby>
+
h6(#has_and_belongs_to_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
-h6. <tt><em>collection</em>.build(attributes = {})</tt>
+h6(#has_and_belongs_to_many-collection-build). <tt><em>collection</em>.build(attributes = {})</tt>
The <tt><em>collection</em>.build</tt> 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.
@@ -1605,7 +1640,7 @@ The +has_and_belongs_to_many+ association supports these options:
* +:uniq+
* +:validate+
-h6. +:association_foreign_key+
+h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
@@ -1635,7 +1670,7 @@ end
h6(#has_and_belongs_to_many-conditions). +:conditions+
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
<ruby>
class Parts < ActiveRecord::Base
@@ -1661,7 +1696,7 @@ Normally Rails automatically generates the proper SQL to count the association m
NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
-h6. +:delete_sql+
+h6(#has_and_belongs_to_many-delete_sql). +:delete_sql+
Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
@@ -1699,11 +1734,11 @@ h6(#has_and_belongs_to_many-include). +:include+
You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used.
-h6. +:insert_sql+
+h6(#has_and_belongs_to_many-insert_sql). +:insert_sql+
Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
-h6. +:join_table+
+h6(#has_and_belongs_to_many-join_table). +: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.
@@ -1724,7 +1759,7 @@ The +:offset+ option lets you specify the starting offset for fetching objects v
h6(#has_and_belongs_to_many-order). +:order+
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+The +:order+ option 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
@@ -1760,9 +1795,9 @@ If you want to assign an object to a +has_and_belongs_to_many+ association witho
h4. Association Callbacks
-Normal callbacks hook into the lifecycle 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.
+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 lifecycle of a collection. There are four available association callbacks:
+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+
@@ -1821,7 +1856,7 @@ If you have an extension that should be shared by many associations, you can use
<ruby>
module FindRecentExtension
def find_recent
- find(:all, :conditions => ["created_at > ?", 5.days.ago])
+ where("created_at > ?", 5.days.ago)
end
end
@@ -1851,8 +1886,6 @@ Extensions can refer to the internals of the association proxy using these three
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11
-
* April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* April 19, 2009: Added +:touch+ option to +belongs_to+ associations by "Mike Gunderloy":credits.html#mgunderloy
* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile
index 6dee4b9c61..297ba2d661 100644
--- a/railties/guides/source/caching_with_rails.textile
+++ b/railties/guides/source/caching_with_rails.textile
@@ -65,7 +65,7 @@ end
If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.
-Note: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL!
+NOTE: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL!
INFO: Page caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
@@ -98,7 +98,7 @@ You can also use +:if+ (or +:unless+) to pass a Proc that specifies when the act
You can modify the default action cache path by passing a +:cache_path+ option. This will be passed directly to +ActionCachePath.path_for+. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.
-Finally, if you are using memcached, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store.
+Finally, if you are using memcached, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store.
INFO: Action caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
@@ -238,86 +238,95 @@ h3. Cache Stores
Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.
-Rails 2.1 and above provide +ActiveSupport::Cache::Store+ which can be used to cache strings. Some cache store implementations, like +MemoryStore+, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that.
+h4. Configuration
-The default cache stores provided with Rails include:
+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.
-1) +ActiveSupport::Cache::MemoryStore+: A cache store implementation which stores everything into memory in the same process. If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won't be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using +MemoryStore+ is ok. Otherwise, consider carefully whether you should be using this cache store.
-
-+MemoryStore+ is not only able to store strings, but also arbitrary Ruby objects.
-
-+MemoryStore+ is not thread-safe. Use +SynchronizedMemoryStore+ instead if you need thread-safety.
-
<ruby>
-ActionController::Base.cache_store = :memory_store
+config.cache_store = :memory_store
</ruby>
-2) +ActiveSupport::Cache::FileStore+: Cached data is stored on the disk, this is the default store and the default path for this store is +tmp/cache+. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If +tmp/cache+ does not exist, the default store becomes +MemoryStore+.
+Alternatively, you can call +ActionController::Base.cache_store+ outside of a configuration block.
-<ruby>
-ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
-</ruby>
+You can access the cache by calling +Rails.cache+.
-3) +ActiveSupport::Cache::DRbStore+: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process.
+h4. ActiveSupport::Cache::Store
-<ruby>
-ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
-</ruby>
+This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.
+
+The main methods to call are +read+, +write+, +delete+, +exist?+, and +fetch+. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists.
-4) +ActiveSupport::Cache::MemCacheStore+: Works like +DRbStore+, but uses Danga's +memcached+ instead. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites.
+There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries.
-Special features:
+* +:namespace+ - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment.
-* Clustering and load balancing. One can specify multiple memcached servers, and +MemCacheStore+ will load balance between all available servers. If a server goes down, then +MemCacheStore+ will ignore it until it goes back online.
-* Time-based expiry support. See +write+ and the +:expires_in+ option.
-* Per-request in memory cache for all communication with the +memcached+ server(s).
+* +:compress+ - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network.
-It also accepts a hash of additional options:
+* +:compress_threshold+ - This options is used in conjunction with the +:compress+ option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes.
-* +:namespace+: specifies a string that will automatically be prepended to keys when accessing the memcached store.
-* +:readonly+: a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
-* +:multithread+: a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality.
+* +:expires_in+ - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.
-The read and write methods of the +MemCacheStore+ accept an options hash too. When reading you can specify +:raw => true+ to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to +Marshal.load+ before being returned to you.)
+* +:race_condition_ttl+ - This option is used in conjunction with the +:expires_in+ option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the +:expires_in+ option.
-When writing to the cache it is also possible to specify +:raw => true+ means the value is not passed to +Marshal.dump+ before being stored in the cache (by default this is false).
+h4. ActiveSupport::Cache::MemoryStore
-The write method also accepts an +:unless_exist+ flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an +:expires_in+ option that specifies the time-to-live for the cached item in seconds.
+This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the +:size+ options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
<ruby>
-ActionController::Base.cache_store = :mem_cache_store, "localhost"
+ActionController::Base.cache_store = :memory_store, :size => 64.megabytes
</ruby>
-5) +ActiveSupport::Cache::SynchronizedMemoryStore+: Like +MemoryStore+ but thread-safe.
+If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
+
+This is the default cache store implementation.
+
+h4. ActiveSupport::Cache::FileStore
+
+This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
<ruby>
-ActionController::Base.cache_store = :synchronized_memory_store
+ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
</ruby>
-6) +ActiveSupport::Cache::CompressedMemCacheStore+: Works just like the regular +MemCacheStore+ but uses GZip to decompress/compress on read/write.
+With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
+
+Note that the cache will grow until the disk is full unless you periodically clear out old entries.
+
+h4. ActiveSupport::Cache::MemCacheStore
+
+This cache store uses Danga's +memcached+ server to provide a centralized cache for your application. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very a high performance and redundancy.
+
+When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
+
+The +write+ and +fetch+ methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify +:raw+ to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like +increment+ and +decrement+ only on raw values. You can also specify +:unless_exist+ if you don't want memcached to overwrite an existing entry.
<ruby>
-ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost"
+ActionController::Base.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
</ruby>
-7) Custom store: You can define your own cache store (new in Rails 2.1).
+h4. Custom Cache Stores
+
+You can create your own custom cache store by simply extending +ActiveSupport::Cache::Store+ and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.
+
+To use a custom cache store, simple set the cache store to a new instance of the class.
<ruby>
-ActionController::Base.cache_store = MyOwnStore.new("parameter")
+ActionController::Base.cache_store = MyCacheStore.new
</ruby>
-NOTE: +config.cache_store+ can be used in place of +ActionController::Base.cache_store+ in your +Rails::Initializer.run+ block in +environment.rb+
+h4. Cache Keys
-In addition to all of this, Rails also adds the +ActiveRecord::Base#cache_key+ method that generates a key using the class name, +id+ and +updated_at+ timestamp (if available).
+The keys used in a cache can be any object that responds to either +:cache_key+ or to +:to_param+. You can implement the +:cache_key+ method on your classes if you need to generate custom keys. ActiveRecord will generate keys based on the class name and record id.
-You can access these cache stores at a low level for storing queries and other objects. Here's an example:
+You can use Hashes and Arrays of values as cache keys.
<ruby>
-Rails.cache.read("city") # => nil
-Rails.cache.write("city", "Duckburgh")
-Rails.cache.read("city") # => "Duckburgh"
+# This is a legal cache key
+Rails.cache.read(:site => "mysite", :owners => [owner_1, owner2])
</ruby>
+The keys you use on +Rails.cache+ will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with +Rails.cache+ and then try to pull them out with the +memcache-client+ gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.
+
h3. Conditional GET support
Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.
@@ -362,25 +371,14 @@ class ProductsController < ApplicationController
end
</ruby>
-h3. Advanced Caching
-
-Along with the built-in mechanisms outlined above, a number of excellent plugins exist to help with finer grained control over caching. These include Chris Wanstrath's excellent cache_fu plugin (more info "here": http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's interlock plugin (more info "here": http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both of these plugins play nice with memcached and are a must-see for anyone
-seriously considering optimizing their caching needs.
-
-Also the new "Cache money":http://github.com/nkallen/cache-money/tree/master plugin is supposed to be mad cool.
-
-h3. References
+h3. Further reading
* "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails
-* "RailsEnvy, Rails Caching Tutorial, Part 1":http://www.railsenvy.com/2007/2/28/rails-caching-tutorial
-* "RailsEnvy, Rails Caching Tutorial, Part 2":http://www.railsenvy.com/2007/3/20/ruby-on-rails-caching-tutorial-part-2
-* "ActiveSupport::Cache documentation":http://api.rubyonrails.org/classes/ActiveSupport/Cache.html
-* "Rails 2.1 integrated caching tutorial":http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/10-guide-to-caching
+* Feb 17, 2011: Document 3.0.0 changes to ActiveSupport::Cache
* May 02, 2009: Formatting cleanups
* April 26, 2009: Clean up typos in submitted patch
* April 1, 2009: Made a bunch of small fixes
diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile
index fb625f7a44..581fece1ab 100644
--- a/railties/guides/source/command_line.textile
+++ b/railties/guides/source/command_line.textile
@@ -31,11 +31,11 @@ h4. +rails new+
The first thing we'll want to do is create a new Rails application by running the +rails new+ command after installing Rails.
-WARNING: You know you need the rails gem installed by typing +gem install rails+ first, if you don't have this installed, follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html
+WARNING: You can install the rails gem by typing +gem install rails+, if you don't have it already. Follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html
<shell>
$ rails new commandsapp
- create
+ create
create README
create .gitignore
create Rakefile
@@ -73,7 +73,7 @@ $ rails server
[2010-04-18 03:20:33] INFO WEBrick::HTTPServer#start: pid=26086 port=3000
</shell>
-With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic rails app running.
+With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running.
h4. +rails generate+
@@ -81,7 +81,7 @@ The +rails generate+ command uses templates to create a whole lot of things. You
<shell>
$ rails generate
-Usage: rails generate generator [options] [args]
+Usage: rails generate generator [args] [options]
...
...
@@ -101,11 +101,11 @@ Using generators will save you a large amount of time by writing *boilerplate co
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
-INFO: All Rails console utilities have help text. As with most *NIX utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+.
+INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+.
<shell>
$ rails generate controller
-Usage: rails generate controller ControllerName [options]
+Usage: rails generate controller NAME [action action] [options]
...
...
@@ -122,7 +122,7 @@ Example:
Modules Example:
rails generate controller 'admin/credit_card' suspend late_fee
- Credit card admin controller with URLs /admin/credit_card/suspend.
+ Credit card admin controller with URLs like /admin/credit_card/suspend.
Controller: app/controllers/admin/credit_card_controller.rb
Views: app/views/admin/credit_card/debit.html.erb [...]
Helper: app/helpers/admin/credit_card_helper.rb
@@ -134,25 +134,28 @@ The controller generator is expecting parameters in the form of +generate contro
<shell>
$ rails generate controller Greetings hello
create app/controllers/greetings_controller.rb
+ route get "greetings/hello"
invoke erb
create app/views/greetings
create app/views/greetings/hello.html.erb
- error rspec [not found]
+ invoke test_unit
+ create test/functional/greetings_controller_test.rb
invoke helper
create app/helpers/greetings_helper.rb
- error rspec [not found]
+ invoke test_unit
+ create test/unit/helpers/greetings_helper_test.rb
+
</shell>
What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file.
-Check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+):ma
+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
</ruby>
@@ -163,7 +166,7 @@ Then the view, to display our message (in +app/views/greetings/hello.html.erb+):
<p><%= @message %></p>
</html>
-Deal. Go check it out in your browser. Fire up your server. Remember? +rails server+ at the root of your Rails application should do it.
+Deal. Go check it out in your browser. Fire up your server using +rails server+.
<shell>
$ rails server
@@ -180,7 +183,7 @@ Rails comes with a generator for data models too:
<shell>
$ rails generate model
-Usage: rails generate model ModelName [field:type, field:type]
+Usage: rails generate model NAME [field:type field:type] [options]
...
@@ -197,6 +200,8 @@ Examples:
Creates a Post model with a string title, text body, and published flag.
</shell>
+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.
@@ -220,7 +225,7 @@ $ rails generate scaffold HighScore game:string score:integer
create app/controllers/high_scores_controller.rb
create test/functional/high_scores_controller_test.rb
create app/helpers/high_scores_helper.rb
- route map.resources :high_scores
+ route resources :high_scores
dependency model
exists app/models/
exists test/unit/
@@ -259,6 +264,15 @@ h4. +rails console+
The +console+ command lets you interact with your Rails application from the command line. On the underside, +rails console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
+If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+.
+
+<shell>
+$ rails console --sandbox
+Loading development environment in sandbox (Rails 3.0.0)
+Any modifications you make will be rolled back on exit
+irb(main):001:0>
+</shell>
+
h4. +rails dbconsole+
+rails dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
@@ -272,14 +286,14 @@ Let's say you're creating a website for a client who wants a small accounting sy
There is such a thing! The plugin we're installing is called +acts_as_paranoid+, and it lets models implement a +deleted_at+ column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things.
<shell>
-$ rails plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid
+$ rails plugin install https://github.com/technoweenie/acts_as_paranoid.git
+ ./CHANGELOG
+ ./MIT-LICENSE
...
...
</shell>
-h4. +runner+
+h4. +rails runner+
<tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance:
@@ -287,7 +301,7 @@ h4. +runner+
$ rails runner "Model.long_running_method"
</shell>
-h4. +destroy+
+h4. +rails destroy+
Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times!
@@ -316,7 +330,7 @@ $ rails destroy model Oops
notempty app
</shell>
-h4. +about+
+h4. +rake about+
Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! +about+ is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
@@ -339,7 +353,7 @@ Environment development
h3. The Rails Advanced Command Line
-The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
+More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
h4. Rails with Databases and SCM
@@ -364,8 +378,8 @@ $ rails new . --git --database=postgresql
add 'Rakefile'
create README
add 'README'
- create app/controllers/application_controller_.rb
-add 'app/controllers/application_controller_.rb'
+ create app/controllers/application_controller.rb
+add 'app/controllers/application_controller.rb'
create app/helpers/application_helper.rb
...
create log/test.log
@@ -437,7 +451,7 @@ The Rails generator by default looks in these places for available generators, w
* Inside any plugin with a directory like "generators" or "rails_generators"
* ~/.rails/generators
* Inside any Gem you have installed with a name ending in "_generator"
-* Inside *any* Gem installed with a "rails_generators" path, and a file ending in "_generator.rb"
+* Inside any Gem installed with a "rails_generators" path, and a file ending in "_generator.rb"
* Finally, the builtin Rails generators (controller, model, mailer, etc.)
Let's try the fourth option (in our home directory), which will be easy to clean up later:
@@ -472,7 +486,7 @@ We take whatever args are supplied, save them to an instance variable, and liter
* Check there's a *public* directory. You bet there is.
* Run the ERb template called "tutorial.erb".
* Save it into "Rails.root/public/tutorial.txt".
-* Pass in the arguments we saved through the +:assign+ parameter.
+* Pass in the arguments we saved through the +:assigns+ parameter.
Next we'll build the template:
@@ -525,7 +539,7 @@ Rake is a standalone Ruby utility that replaces the Unix utility 'make', and use
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need.
<shell>
- rake --tasks
+$ rake --tasks
(in /home/foobar/commandsapp)
rake db:abort_if_pending_migrations # Raises an error if there are pending migrations
rake db:charset # Retrieves the charset for the current environment's database
@@ -538,8 +552,6 @@ rake tmp:sessions:clear # Clears all files in tmp/sessions
rake tmp:sockets:clear # Clears all files in tmp/sockets
</shell>
-Let's take a look at some of these 80 or so rake tasks.
-
h5. +db:+ Database
The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database.
@@ -548,29 +560,15 @@ h5. +doc:+ Documentation
If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
-h5. +gems:+ Ruby gems
-
-You can specify which gems your application uses, and +rake gems:install+ will install them for you. Look at your environment.rb to learn how with the *config.gem* directive.
-
-NOTE: +gems:unpack+ will unpack, that is internalize your application's Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run +rake gems:install+, or finding and installing the gems your application uses.
-
h5. +notes:+ Code note enumeration
These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them.
-h5. +rails:+ Rails-specific tasks
-
-In addition to the +gems:unpack+ task above, you can also unpack the Rails backend specific gems into vendor/rails by calling +rake rails:freeze:gems+, to unpack the version of Rails you are currently using, or +rake rails:freeze:edge+ to unpack the most recent (cutting, bleeding edge) version.
-
-When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can "thaw" by running +rake rails:unfreeze+.
-
-After upgrading Rails, it is useful to run +rails:update+, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous).
-
h5. +test:+ Rails tests
INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
-Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should.
+Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should.
The +test:+ namespace helps in running the different tests you will (hopefully!) write.
@@ -580,16 +578,13 @@ You can list all the timezones Rails knows about with +rake time:zones:all+, whi
h5. +tmp:+ Temporary files
-The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of an +rm -rf *+ gone awry.
+The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of deletions gone awry.
h5. Miscellaneous Tasks
+rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
- +rake secret+ will give you a psuedo-random key to use for your session secret.
+ +rake secret+ will give you a pseudo-random key to use for your session secret.
+rake routes+ will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
-h3. Changelog
-
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/29
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
index 9e0c7cd060..62b846e871 100644
--- a/railties/guides/source/configuring.textile
+++ b/railties/guides/source/configuring.textile
@@ -13,7 +13,7 @@ Rails offers (at least) four good spots to place initialization code:
* application.rb
* Environment-specific Configuration Files
-* Initializers (load_application_initializers)
+* Initializers
* After-Initializers
h3. Running Code Before Rails
@@ -23,65 +23,178 @@ To run some code before Rails itself is loaded, simply put it above the call to
h3. Configuring Rails Components
-In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The +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 Rails 2.3 +application.rb+ file includes one setting:
+In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The +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 Rails 3.0 +application.rb+ file includes this setting:
<ruby>
-config.filter_parameters << :password
+ config.filter_parameters += [:password]
</ruby>
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:
<ruby>
-config.active_record.colorize_logging = false
+ config.active_record.timestamped_migrations = false
</ruby>
Rails will use that particular setting to configure Active Record.
h4. Rails General Configuration
-* +config.routes_configuration_file+ overrides the default path for the routes configuration file. This defaults to +config/routes.rb+.
+* +config.after_initialize+ takes a block which will be ran _after_ Rails has finished initializing. Useful for configuring values set up by other initializers:
-* +config.cache_classes+ controls whether or not application classes should be reloaded on each request.
+<ruby>
+config.after_initialize do
+ ActionView::Base.sanitized_allowed_tags.delete 'div'
+end
+</ruby>
+
+* +config.allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +false+ by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Can also be enabled with +threadsafe!+.
+
+* +config.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. Shorter version of +config.action_controller.asset_host+.
-* +config.cache_store+ configures which cache store to use for Rails caching. Options include +:memory_store+, +:file_store+, +:mem_cache_store+ or the name of your own custom class.
+* +config.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+.
-* +config.controller_paths+ accepts an array of paths that will be searched for controllers. Defaults to +app/controllers+.
+<ruby>
+ config.asset_path = proc { |asset_path| "assets/#{asset_path}" }
+</ruby>
-* +config.database_configuration_file+ overrides the default path for the database configuration file. Default to +config/database.yml+.
+* +config.autoload_once_paths+ accepts an array of paths from which Rails will automatically load from only once. All elements of this array must also be in +autoload_paths+.
-* +config.dependency_loading+ enables or disables dependency loading during the request cycle. Setting dependency_loading to _true_ will allow new classes to be loaded during a request and setting it to _false_ will disable this behavior.
+* +config.autoload_paths+ accepts an array of additional paths to prepend to the load path. By default, all app, lib, vendor and mock paths are included in this list.
-* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. All elements of this array must also be in +load_paths+.
+* +config.cache_classes+ controls whether or not application classes should be reloaded on each request. Defaults to _true_ in development, _false_ in test and production. Can also be enabled with +threadsafe!+.
-* +config.load_once_paths+ accepts an array of paths from which Rails will automatically load from only once. All elements of this array must also be in +load_paths+.
+* +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.load_paths+ accepts an array of additional paths to prepend to the load path. By default, all app, lib, vendor and mock paths are included in this list.
+* +config.cache_store+ configures which cache store to use for Rails caching. Options include +:memory_store+, +:file_store+, +:mem_cache_store+ or the name of your own custom class. Defaults to +:file_store+.
-* +config.log_level+ defines the verbosity of the Rails logger. In production mode, this defaults to +:info+. In development mode, it defaults to +:debug+.
+* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to _true_.
-* +config.log_path+ overrides the path to the log file to use. Defaults to +log/#{environment}.log+ (e.g. log/development.log or log/production.log).
+* +config.consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ in controllers to specify which requests should provide debugging information on errors.
-* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging.
+* +config.controller_paths+ configures where Rails can find controllers for this application.
+
+* +config.dependency_loading+ enables or disables dependency loading during the request cycle. Setting dependency_loading to _true_ will allow new classes to be loaded during a request and setting it to _false_ will disable this behavior. Can also be enabled with +threadsafe!+.
+
+* +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. All elements of this array must also be in +load_paths+.
+
+* +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8.
-* +config.plugin_loader+ overrides the class that handles loading each plugin. Defaults to +Rails::Plugin::Loader+.
+* +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.plugin_locators+ overrides the class that handle finding the desired plugins that you‘d like to load for your application. By default it is the +Rails::Plugin::FileSystemLocator+.
+* +config.helper_paths+ configures where Rails can find helpers for this application.
-* +config.plugin_paths+ overrides the path to the root of the plugins directory. Defaults to +vendor/plugins+.
+* +config.log_level+ defines the verbosity of the Rails logger. In production mode, this defaults to +:info+. In development mode, it defaults to +:debug+.
+
+* +config.log_path+ overrides the path to the log file to use. Defaults to +log/#{environment}.log+ (e.g. log/development.log or log/production.log).
+
+* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging.
+
+* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware" section below.
* +config.plugins+ accepts the list of plugins to load. If this is set to nil, all plugins will be loaded. If this is set to [], no plugins will be loaded. Otherwise, plugins will be loaded in the order specified.
-* +config.preload_frameworks+ enables or disables preloading all frameworks at startup.
+* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Can also be enabled with +threadsafe!+. Defaults to +nil+, so is disabled.
+
+* +config.reload_plugins+ enables or disables plugin reloading.
+
+* +config.root+ configures the root path of the application.
-* +config.reload_plugins+ enables or disables plugin reloading.
+* +config.secret_token+ used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering.
+
+* +config.serve_static_assets+ configures Rails to serve static assets. Defaults to _true_, but in the production environment is turned off. The server software used to run the application should be used to serve the assets instead.
+
+* +config.session_store+ is usually set up in +config/initializers/session_store.rb+ and specifies what class to use to store the session. Custom session stores can be specified like so:
+
+<ruby>
+ config.session_store = :my_custom_store
+</ruby>
-* +config.root_path+ configures the root path of the application.
+This custom store must be defined as +ActionDispatch::Session::MyCustomStore+.
+
+* +config.threadsafe!+ enables +allow_concurrency+, +cache_classes+, +dependency_loading+ and +preload_frameworks+ to make the application threadsafe.
+
+WARNING: Threadsafe operation is incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+.
* +config.time_zone+ sets the default time zone for the application and enables time zone awareness for Active Record.
-* +config.view_path+ sets the path of the root of an application's views. Defaults to +app/views+.
+* +config.whiny_nils+ enables or disables warnings when any methods of nil are invoked. Defaults to _true_ in development and test environments.
+
+h4. Configuring Generators
+
+Rails 3 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
+</ruby>
+
+The full set of methods that can be used in this block are as follows:
+
+* +force_plural+ allows pluralized model names. Defaults to _false_.
+* +helper+ defines whether or not to generate helpers. Defaults to _true_.
+* +orm+ defines which orm to use. Defaults to _nil_, so will use Active Record by default.
+* +integration_tool+ defines which integration tool to use. Defaults to _nil_.
+* +performance_tool+ defines which performance tool to use. Defaults to _nil_.
+* +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 ran, but this hook can be used in other generates as well.
+* +test_framework+ defines which test framework to use. Defaults to _nil_, so will use Test::Unit by default.
+* +template_engine+ defines which template engine to use, such as ERB or Haml. Defaults to +:erb+.
+
+h4. Configuring Middleware
+
+Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
+
+* +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is _true_.
+* +Rack::Lock+ Will wrap the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to _false_, which it is by default.
+* +ActiveSupport::Cache::Strategy::LocalCache+ Serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
+* +Rack::Runtime+ Sets an +X-Runtime+ header, containing the time (in seconds) taken to execute the request.
+* +Rails::Rack::Logger+ Will notify the logs that the request has began. After request is complete, flushes all the logs.
+* +ActionDispatch::ShowExceptions+ rescues any exception returned by the application and renders nice exception pages if the request is local or if +config.consider_all_requests_local+ is set to _true_. If +config.action_dispatch.show_exceptions+ is set to _false_, exceptions will be raised regardless.
+* +ActionDispatch::RemoteIp+ checks for IP spoofing attacks. Configurable with the +config.action_dispatch.ip_spoofing_check+ and +config.action_dispatch.trusted_proxies+ settings.
+* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch.x_sendfile_header+
+* +ActionDispatch::Callbacks+ Runs the prepare callbacks before serving the request.
+* +ActiveRecord::ConnectionAdapters::ConnectionManagement+ cleans active connections after each request, unless the +rack.test+ key in the request environment is set to _true_.
+* +ActiveRecord::QueryCache+ caches all +SELECT+ queries generated in a request. If an +INSERT+ or +UPDATE+ takes place then the cache is cleaned.
+* +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 PUT and DELETE HTTP method types.
+* +ActionDispatch::Head+ converts HEAD requests to GET requests and serves them as so.
+* +ActionDispatch::BestStandardsSupport+ enables "best standards support" so that IE8 renders some elements correctly.
+
+Besides these usual middleware, you can add your own by using the +config.middleware.use+ method:
+
+<ruby>
+ config.middleware.use Magical::Unicorns
+</ruby>
+
+This will put the +Magical::Unicorns+ middleware on the end of the stack. If you wish to put this middleware before another use +insert_before+:
+
+<ruby>
+ config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
+</ruby>
+
+There's also +insert_after+ which will insert a middleware _after_ another:
+
+<ruby>
+ config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
+</ruby>
+
+Middlewares can also be completely swapped out and replaced with others:
+
+<ruby>
+ config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns
+</ruby>
+
+They can also be removed from the stack completely:
-* +config.whiny_nils+ enables or disabled warnings when an methods of nil are invoked. Defaults to _false_.
+<ruby>
+ config.middleware.delete ActionDispatch::BestStandardsSupport
+</ruby>
h4. Configuring i18n
@@ -105,9 +218,7 @@ h4. Configuring Active Record
* +config.active_record.pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to +true+ (the default), then the Customer class will use the +customers+ table. If set to +false+, then the Customers class will use the +customer+ table.
-* +config.active_record.colorize_logging+ (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord.
-
-* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:local+.
+* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:utc+ for Rails, although ActiveRecord defaults to +:local+ when used outside of Rails.
* +config.active_record.schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements.
@@ -127,41 +238,29 @@ h4. Configuring Action Controller
<tt>config.action_controller</tt> includes a number of configuration settings:
-* +config.action_controller.asset_host+ provides a string that is prepended to all of the URL-generating helpers in +AssetHelper+. This is designed to allow moving all javascript, CSS, and image files to a separate asset host.
+* +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.asset_path+ allows you to override the default asset path generation by providing your own instructions.
+* +config.action_controller.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+.
-* +config.action_controller.consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ to specify which requests should provide debugging information on errors.
+* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. For Rails, this directory has already been set to +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>). Changing this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your web server to look in the new location for cached files.
-* +config.action_controller.allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +false+ by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Instead, you should simply call +config.threadsafe!+ inside your +production.rb+ file, which makes all the necessary adjustments.
+* +config.action_controller.page_cache_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+
-WARNING: Threadsafe operation is incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+.
-
-* +config.action_controller.param_parsers+ provides an array of handlers that can extract information from incoming HTTP requests and add it to the +params+ hash. By default, parsers for multipart forms, URL-encoded forms, XML, and JSON are active.
+* +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_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 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging.
-* +config.action_controller.resource_action_separator+ gives the token to be used between resources and actions when building or interpreting RESTful URLs. By default, this is "/".
-
-* +config.action_controller.resource_path_names+ is a hash of default names for several RESTful actions. By default, the new action is named +new+ and the edit action is named +edit+.
-
* +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.optimise_named_routes+ turns on some optimizations in generating the routing table. It is set to +true+ by default.
-
-* +config.action_controller.use_accept_header+ sets the rules for determining the response format. If this is set to +true+ (the default) then +respond_to+ and +Request#format+ will take the Accept header into account. If it is set to false then the request format will be determined solely by examining +params[:format]+. If there is no +format+ parameter, then the response format will be either HTML or Javascript depending on whether the request is an AJAX request.
-
* +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_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.
-
The caching code adds two additional settings:
-* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to +Rails.root + "/public"+).
+* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>).
* +ActionController::Base.page_cache_extension+ sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is +.html+.
@@ -173,13 +272,23 @@ The Active Record session store can also be configured:
* +ActiveRecord::SessionStore::Session.data_column_name+ sets the name of the column which stores marshaled session data. Defaults to +data+.
+h4. Configuring Action Dispatch
+
+* +config.action_dispatch.session_store+ sets the name of the store for session data. The default is +:cookie_store+; other valid options include +:active_record_store+, +:mem_cache_store+ or the name of your own custom class.
+
+* +config.action_dispatch.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.
+
h4. Configuring Action View
There are only a few configuration options for Action View, starting with four on +ActionView::Base+:
-* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+.
-
-* +config.action_view.warn_cache_misses+ tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is +false+.
+* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alerts the caught exception (and then re-raises it). The default is +false+.
* +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is <tt>Proc.new{ |html_tag, instance| %Q(%&lt;div class=&quot;field_with_errors&quot;&gt;#{html_tag}&lt;/div&gt;).html_safe }</tt>
@@ -189,12 +298,36 @@ There are only a few configuration options for Action View, starting with four o
* +config.action_view.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the "ERB documentation":http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/ for more information.
+* +config.action_view.javascript_expansions+ is a hash containing expansions that can be used for the JavaScript include tag. By default, this is defined as:
+
+<ruby>
+ config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] }
+</ruby>
+
+However, you may add to this by defining others:
+
+<ruby>
+ config.action_view.javascript_expansions[:jquery] = ["jquery", "jquery-ui"]
+</ruby>
+
+And can reference in the view with the following code:
+
+<ruby>
+ <%= javascript_include_tag :jquery %>
+</ruby>
+
+* +config.action_view.stylesheet_expansions+ works in much the same way as +javascript_expansions+, but has no default key. Keys defined for this hash can be referenced in the view like such:
+
+<ruby>
+ <%= stylesheet_link_tag :special %>
+</ruby>
+
+* +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ With the cache enabled, the asset tag helper methods will make fewer expensive file system calls (the default implementation checks the file system timestamp). However this prevents you from modifying any asset files while the server is running.
+
h4. Configuring Action Mailer
There are a number of settings available on +config.action_mailer+:
-* +config.action_mailer.template_root+ gives the root folder for Action Mailer templates.
-
* +config.action_mailer.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ 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:
@@ -215,15 +348,13 @@ There are a number of settings available on +config.action_mailer+:
* +config.action_mailer.perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing.
-* +config.action_mailer.default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+.
-
-* +config.action_mailer.default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain"
-
-* +config.action_mailer.default_mime_version+ is the default MIME version for the message. It defaults to +1.0+.
-
-* +config.action_mailer.default_implicit_parts_order+ - When a message is built implicitly (i.e. multiple parts are assembled from templates
-which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to +["text/html", "text/enriched", "text/plain"]+. Items that appear first in the array have higher priority in the mail client
-and appear last in the mime encoded message.
+* +config.action_mailer.default+ configures Action Mailer defaults. These default to:
+<ruby>
+ :mime_version => "1.0",
+ :charset => "UTF-8",
+ :content_type => "text/plain",
+ :parts_order => [ "text/plain", "text/enriched", "text/html" ]
+</ruby>
h4. Configuring Active Resource
@@ -235,6 +366,8 @@ h4. 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 +true+.
* +config.active_support.use_standard_json_time_format+ enables or disables serializing dates to ISO 8601 format. Defaults to +false+.
@@ -243,46 +376,196 @@ There are a few configuration options available in Active Support:
* +ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations.
+* +ActiveSupport::Deprecation.behavior+ alternative setter to +config.active_support.deprecation+ which configures the behavior of deprecation warnings for Rails.
+
+* +ActiveSupport::Deprecation.silence+ takes a block in which all deprecation warnings are silenced.
+
+* +ActiveSupport::Deprecation.silenced+ sets whether or not to display deprecation warnings.
+
* +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+.
-h3. Using Initializers
-After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.
+h3. Rails Environment Settings
-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.
+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_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets.
+
+* +ENV["RAILS_CACHE_ID"]+ and +ENV["RAILS_APP_VERSION"]+ are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application.
+
+
+h3. Using Initializer Files
+
+After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts.
+
+NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down.
TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+.
-h3. Using an After-Initializer
+h3. Initialization events
+
+Rails has 5 initialization events which can be hooked into (listed in order that they are ran):
+
+* +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 ran for all Railties (including the application itself), but before eager loading and the middleware stack is built.
+
+* +before_eager_load+: This is run directly before eager loading occurs, which is the default behaviour for the _production_ environment and not for the +development+ enviroment.
+
+* +after_initialize+: Run directly after the initialization of the application, but before the application initializers are run.
-After-initializers are run (as you might guess) after any initializers are loaded. You can supply an +after_initialize+ block (or an array of such blocks) by setting up +config.after_initialize+ in any of the Rails configuration files:
+
+WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called.
+
+h4. +Rails::Railtie#initializer+
+
+Rails has several initializers that run on startup that are all defined by using the +initializer+ method from +Rails::Railtie+. Here's an example of the +initialize_whiny_nils+ initializer from Active Support:
<ruby>
-config.after_initialize do
- SomeClass.init
+initializer "active_support.initialize_whiny_nils" do |app|
+ require 'active_support/whiny_nil' if app.config.whiny_nils
end
</ruby>
-WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called.
+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_.
-h3. Rails Environment Settings
+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.
-Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails:
+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.
-* +ENV['RAILS_ENV']+ defines the Rails environment (production, development, test, and so on) that Rails will run under.
+The block's argument of the +initialize+ is the instance of the application itself, and so we can access the configuration on it by using the +config+ method as this initializer does.
-* +ENV['RAILS_RELATIVE_URL_ROOT']+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory.
+Because +Rails::Application+ inherits from +Rails::Railtie+ (indirectly), you can use the +initializer+ method in +config/application.rb+ to define initializers for the application.
-* +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets.
+h4. Initializers
-* +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.
+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).
-* +ENV['RAILS_GEM_VERSION']+ defines the version of the Rails gems to use, if +RAILS_GEM_VERSION+ is not defined in your +environment.rb+ file.
+*+load_environment_hook+*
+Serves as a placeholder so that +:load_environment_config+ can be defined to run before it.
-h3. Changelog
+*+load_active_support+* Requires +active_support/dependencies+ which sets up the basis for Active Support. Optionally requires +active_support/all+ if +config.active_support.bare+ is un-truthful, which is the default.
+
+*+preload_frameworks+* Will load all autoload dependencies of Rails automatically if +config.preload_frameworks+ is +true+ or "truthful". By default this configuration option is disabled. In Rails, when internal classes are referenced for the first time they are autoloaded. +:preload_frameworks+ loads all of this at once on initialization.
+
+*+initialize_logger+* Initializes the logger (an +ActiveSupport::BufferedLogger+ object) for the application and makes it accessible at +Rails.logger+, providing that there's no initializer inserted before this point that has defined +Rails.logger+.
+
+*+initialize_cache+* If +RAILS_CACHE+ isn't yet set, 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 set to +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+* Will require +active_support/whiny_nil+ if +config.whiny_nils+ is set to +true+. This file will output errors such as:
+
+<plain>
+ Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
+</plain>
+
+And:
+
+<plain>
+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
+</plain>
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28
+*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +:log+ for development, +:notify+ for production and +:stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file. Can be set to an array of values.
+
+*+active_support.initialize_time_zone+* Sets the default time zone for the application based off the +config.time_zone+ setting, which defaults to "UTC".
+
+*+action_dispatch.configure+* Configures the +ActionDispatch::Http::URL.tld_length+ to be set to the value of +config.action_dispatch.tld_length+.
+
+*+action_view.cache_asset_ids+* Will set +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ to +false+ when Active Support loads, but only if +config.cache_classes+ is too.
+
+*+action_view.javascript_expansions+* Registers the expansions set up by +config.action_view.javascript_expansions+ and +config.action_view.stylesheet_expansions+ to be recognised by Action View and therefore usable in the views.
+
+*+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 length of time Active Record calls took for the request back to the logger.
+
+*+active_record.set_dispatch_hooks+* If +config.cache_classes+ is set to false, all reloadable connections to the database will be reset.
+
+*+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.
+
+*+active_resource.set_configs+* Sets up Active Resource by using the settings in +config.active_resource+ by +send+'ing the method names as setters to +ActiveResource::Base+ and passing the values through.
+
+*+set_load_path+* This initializer runs before +bootstrap_hook+. Adds the +vendor+, +lib+, all directories of +app+ and any paths specified by +config.load_paths+ to +$LOAD_PATH+.
+
+*+set_autoload_path+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+.
+
+*+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 and plugins are loaded.
+
+NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the +initializers+ folder on down.
+
+TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+.
+
+*+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 ran.
+
+*+add_generator_templates+* Finds templates for generators at +lib/templates+ for the application, railities 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.cache_classes+ is +true+, runs the +config.before_eager_load+ hooks and then calls +eager_load!+ which will load all the Ruby files from +config.eager_load_paths+.
+
+*+finisher_hook+* Provides a hook for after the initialization of process of the application is complete, as well as running all the +config.after_initialize+ blocks for the application, railties and engines.
+
+*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+.
+
+*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.cache_classes+ is set to +true+ and +config.dependency_loading+ is set to +false+.
+
+h3. Changelog
+* December 3, 2010: Added initialization events for Rails 3 ("Ryan Bigg":http://ryanbigg.com)
+* November 26, 2010: Removed all config settings not available in Rails 3 ("Ryan Bigg":http://ryanbigg.com)
* August 13, 2009: Updated with config syntax and added general configuration options by "John Pignata"
* January 3, 2009: First reasonably complete draft by "Mike Gunderloy":credits.html#mgunderloy
* November 5, 2008: Rough outline by "Mike Gunderloy":credits.html#mgunderloy
diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile
index 88c5c79e9d..4bd527d4c7 100644
--- a/railties/guides/source/contribute.textile
+++ b/railties/guides/source/contribute.textile
@@ -1,20 +1,20 @@
h2. Contribute to the Rails Guides
-Rails Guides aim to improve the Rails documentation and to make the barrier to entry as low as possible. A reasonably experienced developer should be able to use the Guides to come up to speed on Rails quickly. You can track the overall effort at the "Rails Guides Lighthouse":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets. Our sponsors have contributed prizes for those who write an entire guide, but there are many other ways to contribute.
+Rails Guides aim to improve the Rails documentation and to make the barrier to entry as low as possible. A reasonably experienced developer should be able to use the guides to come up to speed on Rails quickly. Our sponsors have contributed prizes for those who write an entire guide, but there are many other ways to contribute.
endprologue.
h3. How to Contribute?
* We have an open commit policy: anyone is welcome to contribute and to review contributions.
-* "docrails is hosted on GitHub":http://github.com/lifo/docrails and has public write access.
+* "docrails is hosted on GitHub":https://github.com/lifo/docrails and has public write access.
* Guides are written in Textile, and reside at +railties/guides/source+ in the docrails project.
-* Follow the "Rails Guides Conventions":http://wiki.github.com/lifo/docrails/rails-guides-conventions.
+* Follow the "Rails Guides Conventions":https://wiki.github.com/lifo/docrails/rails-guides-conventions.
* Assets are stored in the +railties/guides/assets+ directory.
-* Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile.
+* Sample format : "Active Record Associations":https://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile.
* Sample output : "Active Record Associations":association_basics.html.
-* You can build the Guides during testing by running +rake generate_guides+ in the +railties+ directory.
-* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +rake validate_guides+ in the +railties+ directory.
+* You can build the Guides during testing by running +bundle exec rake generate_guides+ in the +railties+ directory.
+* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +bundle exec rake validate_guides+ in the +railties+ directory.
* Edge guides "can be consulted online":http://edgeguides.rubyonrails.org/. That website is generated periodically from docrails.
h3. What to Contribute?
@@ -53,11 +53,11 @@ h3. Rules
* If the same guide writer wants to write multiple guides, that's ideally the situation we'd love to be in! However, that guide writer will only receive the cash prize for all the subsequent guides (and not the GitHub or RPM prizes).
* Our review team will have the final say on whether the guide is complete and of good enough quality.
-All authors should read and follow the "Rails Guides Conventions":http://wiki.github.com/lifo/docrails/rails-guides-conventions and the "Rails API Documentation Conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions.
+All authors should read and follow the "Rails Guides Conventions":https://wiki.github.com/lifo/docrails/rails-guides-conventions and the "Rails API Documentation Conventions":https://wiki.github.com/lifo/docrails/rails-api-documentation-conventions.
h3. Translations
-The translation effort for the Rails Guides is just getting underway. We know about projects to translate the Guides into Spanish, Portuguese, Polish, and French. For more details or to get involved see the "Translating Rails Guides":http://wiki.github.com/lifo/docrails/translating-rails-guides page.
+The translation effort for the Rails Guides is just getting underway. We know about projects to translate the Guides into Spanish, Portuguese, Polish, and French. For more details or to get involved see the "Translating Rails Guides":https://wiki.github.com/lifo/docrails/translating-rails-guides page.
h3. Mailing List
diff --git a/railties/guides/source/contributing_to_rails.textile b/railties/guides/source/contributing_to_rails.textile
deleted file mode 100644
index fb81bab98d..0000000000
--- a/railties/guides/source/contributing_to_rails.textile
+++ /dev/null
@@ -1,308 +0,0 @@
-h2. Contributing to Rails
-
-This guide covers ways in which _you_ can become a part of the ongoing development of Rails. After reading it, you should be familiar with:
-
-* Using Lighthouse to report issues with Rails
-* Cloning edge Rails and running the test suite
-* Helping to resolve existing issues
-* Contributing to the Rails documentation
-* Contributing to the Rails code
-
-Rails is not "someone else's framework." Over the years, hundreds of people have contributed code ranging from a single character to massive architectural changes, all with the goal of making Rails better for everyone. Even if you don't feel up to writing code yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches to contributing documentation.
-
-endprologue.
-
-h3. Reporting a Rails Issue
-
-Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload tests or patches.
-
-NOTE: Bugs in the most recent released version of Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this Guide you'll find out how to get edge Rails for testing.
-
-h4. Creating a Bug Report
-
-If you've found a problem in Rails, you can start by "adding a new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new to the Rails Lighthouse. At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
-
-You shouldn't assign the bug to a particular core developer (through the *Who's Responsible* select list) unless you know for sure which developer will be handling any patch. The core team periodically reviews issues and assigns developers and milestones to them.
-
-You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the *Choose some tags* textbox), rather than creating new tags.
-
-Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
-
-h4. Special Treatment for Security Issues
-
-If you've found a security vulnerability in Rails, please do *not* report it via a Lighthouse ticket. Lighthouse tickets are public as soon as they are entered. Instead, you should use the dedicated email address "security@rubyonrails.org":mailto:security@rubyonrails.org to report any vulnerabilities. This alias is monitored and the core team will work with you to quickly and completely address any such vulnerabilities.
-
-WARNING: Just to emphasize the point, _please do not report security vulnerabilities on public Lighthouse tickets_. This will only expose your fellow Rails developers to needless risks.
-
-You should receive an acknowledgement and detailed response to any reported security issue within 48 hours. If you don't think you're getting adequate response from the security alias, refer to the "Rails security policy page":http://rubyonrails.org/security for direct emails for the current Rails security coordinators.
-
-h4. What About Feature Requests?
-
-Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
-
-h3. Running the Rails Test Suite
-
-To move on from submitting bugs to helping resolve existing issues or contributing your own code to Rails, you _must_ be able to run the Rails test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
-
-h4. Install git
-
-Rails uses git for source code control. You won’t be able to do anything without the Rails source code, and this is a prerequisite. The "git homepage":http://git-scm.com/ has installation instructions. If you’re on OS X, use the "Git for OS X":http://code.google.com/p/git-osx-installer/ installer. If you're unfamiliar with git, there are a variety of resources on the net that will help you learn more:
-
-* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by.
-* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow.
-* "GitHub":http://github.com/guides/home offers links to a variety of git resources.
-* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license.
-
-h4. Get the Rails Source Code
-
-Don’t fork the main Rails repository. Instead, you want to clone it to your own computer. Navigate to the folder where you want the source code (it will create its own /rails subdirectory) and run:
-
-<shell>
-git clone git://github.com/rails/rails.git
-cd rails
-</shell>
-
-h4. Set up and Run the Tests
-
-All of the Rails tests must pass with any code you submit, otherwise you have no chance of getting code accepted. This means you need to be able to run the tests. First, you need to install all Rails dependencies with bundler:
-
-NOTE: Ensure you install bundler v1.0
-
-<shell>
-gem install -v=1.0.0.rc.2 bundler
-bundle install --without db
-</shell>
-
-The second command will install all dependencies, except MySQL and PostgreSQL. We will come back at these soon. With dependencies installed, you can run the whole Rails test suite with:
-
-<shell>
-rake test
-</shell>
-
-You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command:
-
-<shell>
-cd actionpack
-rake test
-</shell>
-
-h4. Testing Active Record
-
-By default, when you run Active Record tests, it will execute the test suite three times, one for each of the main databases: SQLite3, MySQL and PostgreSQL. If you are adding a feature that is not specific to the database, you can run the test suite (or just one file) for just one of them. Here is an example for SQLite3:
-
-<shell>
-cd activerecord
-rake test_sqlite3
-rake test_sqlite3 TEST=test/cases/validations_test.rb
-</shell>
-
-If you want to use another database, as MySQL, you need to create a user named +rails+ with privileges on the test databases.
-
-<shell>
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
- to 'rails'@'localhost';
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
- to 'rails'@'localhost';
-</shell>
-
-Then ensure you run bundle install without the +--without db+ option:
-
-<shell>
-bundle install
-</shell>
-
-Finally, enter this from the +activerecord+ directory to create the test databases:
-
-<shell>
-rake mysql:build_databases
-</shell>
-
-NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
-
-If you’re using another database, check the files under +activerecord/test/connections+ in the Rails source code for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails.
-
-You can now run tests as you did for +sqlite3+:
-
-<shell>
-rake test_mysql
-</shell>
-
-You can also +myqsl+ with +postgresql+, +jdbcmysql+, +jdbcsqlite3+ or +jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the Rails continuous integration server runs.
-
-NOTE: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite 3. Subtle differences between the various Active Record database adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
-
-h4. Older versions of Rails
-
-If you want to work add a fix to older versions of Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to Rails 2.3 branch:
-
-<shell>
-git branch --track 2-3-stable origin/2-3-stable
-git checkout 2-3-stable
-</shell>
-
-TIP: You may want to "put your git branch name in your shell prompt":http://github.com/guides/put-your-git-branch-name-in-your-shell-prompt to make it easier to remember which version of the code you're working with.
-
-h3. Helping to Resolve Existing Issues
-
-As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find hundreds of issues already requiring attention. What can you do for these? Quite a bit, actually:
-
-h4. Verifying Bug Reports
-
-For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing.
-
-If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
-
-If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the Rails source: looking at the existing test files will teach you how to write more tests for Rails. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
-
-Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
-
-h4. Testing Patches
-
-You can also help out by examining patches that have been submitted to Rails via Lighthouse. To apply someone's changes you need to first create a branch of the Rails source code:
-
-<shell>
-git checkout -b testing_branch
-</shell>
-
-Then you can apply their patch:
-
-<shell>
-git apply their-patch-file.diff
-</shell>
-
-After applying a patch, test it out! Here are some things to think about:
-
-* Does the patch actually work?
-* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
-* Does the documentation still seem right to you?
-* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
-
-Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
-
-<blockquote>
-I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
-</blockquote>
-
-If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things.
-
-h3. Contributing to the Rails Documentation
-
-Another area where you can help out if you're not yet ready to take the plunge to writing Rails core code is with Rails documentation. You can help with the Rails Guides or the Rails API documentation.
-
-TIP: "docrails":http://github.com/lifo/docrails/tree/master is the documentation branch for Rails with an *open commit policy*. You can simply PM "lifo":http://github.com/lifo on Github and ask for the commit rights. Documentation changes made as part of the "docrails":http://github.com/lifo/docrails/tree/master project are merged back to the Rails master code from time to time. Check out the "original announcement":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch for more details.
-
-h4. The Rails Guides
-
-The "Rails Guides":http://guides.rubyonrails.org/ are a set of online resources that are designed to make people productive with Rails and to understand how all of the pieces fit together. These guides (including this one!) are written as part of the "docrails":http://github.com/lifo/docrails/tree/master project. If you have an idea for a new guide, or improvements for an existing guide, you can refer to the "contribution page":contribute.html for instructions on getting involved.
-
-h4. The Rails API Documentation
-
-The "Rails API documentation":http://api.rubyonrails.org/ is automatically generated from the Rails source code via "RDoc":http://rdoc.rubyforge.org/. If you find some part of the documentation to be incomplete, confusing, or just plain wrong, you can step in and fix it.
-
-To contribute an update to the API documentation, you can contact "lifo":http://github.com/lifo on GitHub and ask for commit rights to the docrails repository and push your changes to the docrails repository. Please follow the "docrails RDoc conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions when contributing the changes.
-
-h3. The Rails Wiki
-
-The "Rails wiki":http://wiki.rubyonrails.org/ is a collection of user-generated and freely-editable information about Rails. It covers everything from getting started to FAQs to how-tos and popular plugins. To contribute to the wiki, just find some useful information that isn't there already and add it. There are style guidelines to help keep the wiki a coherent resources; see the section on "contributing to the wiki":http://wiki.rubyonrails.org/#contributing_to_the_wiki for more details.
-
-h3. Contributing to the Rails Code
-
-When you're ready to take the plunge, one of the most helpful ways to contribute to Rails is to actually submit source code. Here's a step-by-step listing of the things you need to do to make this a successful experience.
-
-h4. Learn the Language and the Framework
-
-Learn at least _something_ about Ruby and Rails. If you don’t understand the syntax of the language, common Ruby idioms, and the code that already exists in Rails, you’re unlikely to be able to build a good patch (that is, one that will get accepted). You don’t have to know every in-and-out of the language and the framework; some of the Rails code is fiendishly complex. But Rails is probably not appropriate as the first place that you ever write Ruby code. You should at least understand (though not necessarily memorize) "The Ruby Programming Language":http://www.amazon.com/gp/product/0596516177?ie=UTF8&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596516177 and have browsed the Rails source code.
-
-h4. Fork the Rails Source Code
-
-Fork Rails. You’re not going to put your patches right into the master branch, OK? This is where you need that copy of Rails that you cloned earlier. Think of a name for your new branch and run
-
-<shell>
-git checkout -b my_new_branch
-</shell>
-
-It doesn’t really matter what name you use, because this branch will only exist on your local computer.
-
-h4. Write Your Code
-
-Now get busy and add your code to Rails (or edit the existing code). You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
-
-* Get the code right
-* Use Rails idioms and helpers
-* Include tests that fail without your code, and pass with it
-* Update the documentation
-
-h4. Follow the Coding Conventions
-
-Rails follows a simple set of coding style conventions.
-
-* Two spaces, no tabs
-* Prefer +&amp;&amp;+/+||+ over +and+/+or+
-* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+
-* Follow the conventions you see used in the source already
-
-h4. Sanity Check
-
-You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
-
-You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
-
-h4. Commit Your Changes
-
-When you're happy with the code on your computer, you need to commit the changes to git:
-
-<shell>
-git commit -a -m "Here is a commit message"
-</shell>
-
-h4. Update Rails
-
-Update your copy of Rails. It’s pretty likely that other changes to core Rails have happened while you were working. Go get them:
-
-<shell>
-git checkout master
-git pull
-</shell>
-
-Now reapply your patch on top of the latest changes:
-
-<shell>
-git checkout my_new_branch
-git rebase master
-</shell>
-
-No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
-
-h4. Create a Patch
-
-Now you can create a patch file to share with other developers (and with the Rails core team). Still in your branch, run
-
-<shell>
-git commit -a
-git format-patch master --stdout > my_new_patch.diff
-</shell>
-
-Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in.
-
-h4. Create a Lighthouse Ticket
-
-Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense.
-
-h4. Get Some Feedback
-
-Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
-
-h4. Iterate as Necessary
-
-It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
-
-And then...think about your next contribution!
-
-h3. Changelog
-
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/64
-
-* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
-* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy
-* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy
-
diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile
new file mode 100644
index 0000000000..1fcc4fd7e3
--- /dev/null
+++ b/railties/guides/source/contributing_to_ruby_on_rails.textile
@@ -0,0 +1,392 @@
+h2. Contributing to Ruby on Rails
+
+This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with:
+
+* Using Lighthouse to report issues
+* Cloning master and running the test suite
+* Helping to resolve existing issues
+* Contributing to the Ruby on Rails documentation
+* Contributing to the Ruby on Rails code
+
+Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation. All with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
+
+endprologue.
+
+h3. Reporting an Issue
+
+Ruby on Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload patches.
+
+NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.
+
+h4. Creating a Bug Report
+
+If you've found a problem in Ruby on Rails which is not a security risk do a search in Lighthouse in case it was already reported. If you find no ticket addressing it you can "add a new one":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new. (See the next section for reporting security issues.)
+
+At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
+
+You shouldn't assign the bug to a particular core developer unless you know for sure which developer will be handling that issue. The core team periodically reviews issues and assigns developers and milestones to them.
+
+You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the "Choose some tags" textbox), rather than creating new tags.
+
+Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
+
+h4. Special Treatment for Security Issues
+
+WARNING: Please do not report security vulnerabilities on public Lighthouse tickets. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues.
+
+h4. What About Feature Requests?
+
+Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
+
+h3. Running the Test Suite
+
+To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
+
+h4. Install git
+
+Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git:
+
+* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by.
+* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow.
+* "GitHub":https://github.com/guides/home offers links to a variety of git resources.
+* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license.
+
+h4. Clone the Ruby on Rails Repository
+
+Navigate to the folder where you want the Ruby on Rails source code (it will create its own +rails+ subdirectory) and run:
+
+<shell>
+$ git clone git://github.com/rails/rails.git
+$ cd rails
+</shell>
+
+h4. Set up and Run the Tests
+
+The test suite must pass with any submitted code. No matter whether you are writing a new patch, or evaluating someone else's, you need to be able to run the tests.
+
+Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's
+
+<shell>
+$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev
+</shell>
+
+Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with
+
+<shell>
+$ sudo apt-get install sqlite3 libsqlite3-dev
+</shell>
+
+Get a recent version of "Bundler":http://gembundler.com/:
+
+<shell>
+$ gem install bundler
+</shell>
+
+and run:
+
+<shell>
+$ bundle install --without db
+</shell>
+
+This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back at these soon. With dependencies installed, you can run the test suite with:
+
+<shell>
+$ rake test
+</shell>
+
+You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command:
+
+<shell>
+$ cd actionpack
+$ rake test
+</shell>
+
+If you want to run tests from the specific directory use the +TEST_DIR+ environment variable. For example, this will run tests inside +railties/test/generators+ directory only:
+
+<shell>
+$ cd railties
+$ TEST_DIR=generators rake test
+</shell>
+
+
+h4. Warnings
+
+The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no warning, but there may be a few, and also some from third-party libraries. Please ignore (or fix!) them if any, and submit patches that do not issue new warnings.
+
+As of this writing they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
+
+<shell>
+$ RUBYOPT=-W0 rake test
+</shell>
+
+h4. Testing Active Record
+
+The test suite of Active Record attempts to run four times, once for SQLite3, once for each of the two MySQL gems (+mysql+ and +mysql2+), and once for PostgreSQL. We are going to see now how to setup the environment for them.
+
+WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
+
+h5. SQLite3
+
+The gem +sqlite3-ruby+ does not belong to the "db" group indeed, if you followed the instructions above you're ready. This is how you run the Active Record test suite only for SQLite3:
+
+<shell>
+$ cd activerecord
+$ rake test_sqlite3
+</shell>
+
+h5. MySQL and PostgreSQL
+
+To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run
+
+<shell>
+$ sudo apt-get install mysql-server libmysqlclient15-dev
+$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
+</shell>
+
+After that run:
+
+<shell>
+$ rm .bundle/config
+$ bundle install
+</shell>
+
+We need first to delete +.bundle/config+ because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file).
+
+In order to be able to run the test suite against MySQL you need to create a user named +rails+ with privileges on the test databases:
+
+<shell>
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
+ to 'rails'@'localhost';
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
+ to 'rails'@'localhost';
+</shell>
+
+and create the test databases:
+
+<shell>
+$ cd activerecord
+$ rake mysql:build_databases
+</shell>
+
+PostgreSQL's authentication works differently. A simple way to setup the development environment for example is to run with your development account
+
+<shell>
+$ sudo -u postgres createuser --superuser $USER
+</shell>
+
+and after that create the test databases with
+
+<shell>
+$ cd activerecord
+$ rake postgresql:build_databases
+</shell>
+
+NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
+
+If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails.
+
+You can now run tests as you did for +sqlite3+, the tasks are
+
+<shell>
+test_mysql
+test_mysql2
+test_postgresql
+</shell>
+
+respectively. As we mentioned before
+
+<shell>
+$ rake test
+</shell>
+
+will now run the four of them in turn.
+
+You can also invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the continuous integration server runs.
+
+h4. Older versions of Ruby on Rails
+
+If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 2-3-stable branch:
+
+<shell>
+$ git branch --track 2-3-stable origin/2-3-stable
+$ git checkout 2-3-stable
+</shell>
+
+TIP: You may want to "put your git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with.
+
+h3. Helping to Resolve Existing Issues
+
+As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
+
+h4. Verifying Bug Reports
+
+For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing.
+
+If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
+
+If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
+
+Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
+
+h4. Testing Patches
+
+You can also help out by examining patches that have been submitted to Ruby on Rails via Lighthouse. To apply someone's changes you need to first create a dedicated branch:
+
+<shell>
+$ git checkout -b testing_branch
+</shell>
+
+Then you can apply their patch:
+
+<shell>
+$ git am their-patch-file.diff
+</shell>
+
+After applying a patch, test it out! Here are some things to think about:
+
+* Does the patch actually work?
+* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
+* Does it have proper documentation coverage? Should documentation elsewhere be updated?
+* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
+
+Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
+
+<blockquote>
+I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
+</blockquote>
+
+If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things.
+
+h3. Contributing to the Rails Documentation
+
+Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference.
+
+You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":https://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
+
+When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html.
+
+NOTE: As explained above, ordinary code patches should have proper documentation coverage. docrails is only used for isolated documentation improvements.
+
+WARNING: docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails.
+
+If you have an idea for a new guide you can refer to the "contribution page":contribute.html for instructions on getting involved.
+
+h3. Contributing to the Rails Code
+
+h4. Clone the Rails Repository
+
+The first thing you need to do to be able to contribute code is to clone the repository:
+
+<shell>
+$ git clone git://github.com/rails/rails.git
+</shell>
+
+and create a dedicated branch:
+
+<shell>
+$ cd rails
+$ git checkout -b my_new_branch
+</shell>
+
+It doesn’t really matter what name you use, because this branch will only exist on your local computer.
+
+h4. Write Your Code
+
+Now get busy and add or edit code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
+
+* Get the code right
+* Use Rails idioms and helpers
+* Include tests that fail without your code, and pass with it
+* Update the documentation, the surrounding one, examples elsewhere, guides, whatever is affected by your contribution
+
+h4. Follow the Coding Conventions
+
+Rails follows a simple set of coding style conventions.
+
+* Two spaces, no tabs
+* Prefer +&amp;&amp;+/+||+ over +and+/+or+
+* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+
+* Follow the conventions you see used in the source already
+
+h4. Sanity Check
+
+You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
+
+You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
+
+h4. Commit Your Changes
+
+When you're happy with the code on your computer, you need to commit the changes to git:
+
+<shell>
+$ git commit -a -m "Here is a commit message"
+</shell>
+
+h4. Update master
+
+It’s pretty likely that other changes to master have happened while you were working. Go get them:
+
+<shell>
+$ git checkout master
+$ git pull
+</shell>
+
+Now reapply your patch on top of the latest changes:
+
+<shell>
+$ git checkout my_new_branch
+$ git rebase master
+</shell>
+
+No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
+
+h4. Create a Patch
+
+Now you can create a patch file to share with other developers (and with the core team). Still in your branch, run
+
+<shell>
+$ git commit -a
+$ git format-patch master --stdout > my_new_patch.diff
+</shell>
+
+Open the diff file in your text editor of choice to sanity check the results, and make sure that no unintended changes crept in.
+
+You can also perform an extra check by applying the patch to a different dedicated branch:
+
+<shell>
+$ git checkout -b testing_branch
+$ git apply --check my_new_patch.diff
+</shell>
+
+Please make sure the patch does not introduce whitespace errors:
+
+<shell>
+$ git apply --whitespace=error-all mynew_patch.diff
+</shell>
+
+
+h4. Create a Lighthouse Ticket
+
+Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense.
+
+h4. Get Some Feedback
+
+Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the "rubyonrails-core mailing list":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.
+
+h4. Iterate as Necessary
+
+It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
+
+And then...think about your next contribution!
+
+h3. Rails Contributors
+
+All contributions, either via master or docrails, get credit in "Rails Contributors":http://contributors.rubyonrails.org.
+
+h3. Changelog
+
+* December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn
+* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
+* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy
+* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy
+
diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb
index 825e042628..65e396be95 100644
--- a/railties/guides/source/credits.html.erb
+++ b/railties/guides/source/credits.html.erb
@@ -20,7 +20,7 @@ Ruby on Rails Guides: Credits
<% end %>
<%= author('Xavier Noria', 'fxn', 'fxn.png') do %>
- Xavier has been into Rails since 2005, he is currently a Rails consultant. Xavier is Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as &quot;fxn&quot;.
+ Xavier Noria has been into Ruby on Rails since 2005. He is a Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently a Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as &quot;fxn&quot;.
<% end %>
<h3 class="section">Rails Guides Designers</h3>
@@ -44,7 +44,7 @@ Ruby on Rails Guides: Credits
<% end %>
<%= author('Mikel Lindsaar', 'raasdnil') do %>
- Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby <a href="http://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>.
+ 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 %>
@@ -52,7 +52,7 @@ Ruby on Rails Guides: Credits
<% end %>
<%= author('James Miller', 'bensie') do %>
- James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. Find me on GitHub, Gmail, Twitter, and Freenode as &quot;bensie&quot;.
+ James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as &quot;bensie&quot;.
<% end %>
<%= author('Emilio Tagua', 'miloops') do %>
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index 26aee82ae1..045b8823ca 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -48,7 +48,7 @@ Title: Rails debugging guide
h4. +to_yaml+
-Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:
+Displaying an instance variable, or any other object or method, in YAML format can be achieved this way:
<html>
<%= simple_format @post.to_yaml %>
@@ -96,23 +96,25 @@ Will be rendered as follows:
Title: Rails debugging guide
</pre>
-h4. Debugging JavaScript
+h4. Debugging RJS
-Rails has built-in support to debug RJS, to active it, set +ActionView::Base.debug_rjs+ to _true_, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).
+Rails has optional built-in support to debug RJS. When enabled, responses are wrapped in a try/catch block that displays the caught exception using +alert()+, and then re-raises it.
-To enable it, add the following in the +Rails::Initializer do |config|+ block inside +environment.rb+:
+The flag to enable RJS debugging in your configuration files is +config.action_view.debug_rjs+:
<ruby>
-config.action_view[:debug_rjs] = true
+config.action_view.debug_rjs = true
</ruby>
-Or, at any time, setting +ActionView::Base.debug_rjs+ to _true_:
+or at any time setting +ActionView::Base.debug_rjs+:
<ruby>
ActionView::Base.debug_rjs = true
</ruby>
-TIP: For more information on debugging javascript refer to "Firebug":http://getfirebug.com/, the popular debugger for Firefox.
+It is enabled by default in development mode, and disabled in the rest.
+
+TIP: For more information on debugging JavaScript, refer to "Firebug":http://getfirebug.com/, the popular debugger for Firefox.
h3. The Logger
@@ -120,13 +122,13 @@ It can also be useful to save information to log files at runtime. Rails maintai
h4. What is the Logger?
-Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4R+ if you wish.
+Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4r+ if you wish.
You can specify an alternative logger in your +environment.rb+ or any environment file:
<ruby>
-ActiveRecord::Base.logger = Logger.new(STDOUT)
-ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")
+Rails.logger = Logger.new(STDOUT)
+Rails.logger = Log4r::Logger.new("Application Log")
</ruby>
Or in the +Initializer+ section, add _any_ of the following
@@ -140,13 +142,13 @@ TIP: By default, each log is created under +Rails.root/log/+ and the log file na
h4. 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 +ActiveRecord::Base.logger.level+ method.
+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+, and +:fatal+, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use
<ruby>
config.log_level = Logger::WARN # In any environment initializer, or
-ActiveRecord::Base.logger.level = 0 # at any time
+Rails.logger.level = 0 # at any time
</ruby>
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.
@@ -176,7 +178,7 @@ class PostsController < ApplicationController
if @post.save
flash[:notice] = 'Post was successfully created.'
- logger.debug "The post was saved and now is the user is going to be redirected..."
+ logger.debug "The post was saved and now the user is going to be redirected..."
redirect_to(@post)
else
render :action => "new"
@@ -202,7 +204,7 @@ Post should be valid: true
Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
"created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
-The post was saved and now is the user is going to be redirected...
+The post was saved and now the user is going to be redirected...
Redirected to #<Post:0x20af760>
Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
</shell>
@@ -223,6 +225,8 @@ The debugger used by Rails, +ruby-debug+, comes as a gem. To install it, just ru
$ sudo gem install ruby-debug
</shell>
+TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +sudo gem install ruby-debug19+
+
In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/.
Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method.
@@ -247,8 +251,8 @@ If you see the message in the console or logs:
Make sure you have started your web server with the option +--debugger+:
<shell>
-~/PathTo/rails_project$ rails server --debugger
-=> Booting Mongrel (use 'rails server webrick' to force WEBrick)
+$ rails server --debugger
+=> Booting WEBrick
=> Rails 3.0.0 application starting on http://0.0.0.0:3000
=> Debugger enabled
...
@@ -256,8 +260,6 @@ Make sure you have started your web server with the option +--debugger+:
TIP: In development mode, you can dynamically +require \'ruby-debug\'+ instead of restarting the server, if it was started without +--debugger+.
-In order to use Rails debugging you'll need to be running either *WEBrick* or *Mongrel*. For the moment, no alternative servers are supported.
-
h4. 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 ruby-debug'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.
@@ -267,7 +269,7 @@ If you got there by a browser request, the browser tab containing the request wi
For example:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:7)
</shell>
@@ -300,7 +302,7 @@ This command shows you where you are in the code by printing 10 lines centered a
3 # GET /posts.xml
4 def index
5 debugger
-=> 6 @posts = Post.find(:all)
+=> 6 @posts = Post.all
7
8 respond_to do |format|
9 format.html # index.html.erb
@@ -378,7 +380,7 @@ Any expression can be evaluated in the current context. To evaluate an expressio
This example shows how you can print the instance_variables defined within the current context:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:11) instance_variables
["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
</shell>
@@ -475,7 +477,7 @@ end
TIP: You can use ruby-debug while using +rails console+. Just remember to +require "ruby-debug"+ before calling the +debugger+ method.
<shell>
-/PathTo/project $ rails console
+$ rails console
Loading development environment (Rails 2.1.0)
>> require "ruby-debug"
=> []
@@ -599,7 +601,7 @@ There are some settings that can be configured in ruby-debug to make it easier t
You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command.
-TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded. and configure itself accordingly.
+TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded and configure itself accordingly.
Here's a good start for an +.rdebugrc+:
@@ -613,18 +615,18 @@ h3. Debugging Memory Leaks
A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.
-In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.
+In this section, you will learn how to find and fix such leaks by using tools such as BleakHouse and Valgrind.
h4. BleakHouse
-"BleakHouse":http://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks.
+"BleakHouse":https://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks.
If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.
To install it run:
<shell>
-sudo gem install bleak_house
+$ sudo gem install bleak_house
</shell>
Then setup your application for profiling. Then add the following at the bottom of config/environment.rb:
@@ -636,7 +638,7 @@ require 'bleak_house' if ENV['BLEAK_HOUSE']
Start a server instance with BleakHouse integration:
<shell>
-RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server
+$ RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server
</shell>
Make sure to run a couple hundred requests to get better data samples, then press +CTRL-C+. The server will stop and Bleak House will produce a dumpfile in +/tmp+:
@@ -666,7 +668,7 @@ To analyze it, just run the listed command. The top 20 leakiest lines will be li
This way you can find where your application is leaking memory and fix it.
-If "BleakHouse":http://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
+If "BleakHouse":https://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
h4. Valgrind
@@ -680,12 +682,12 @@ h3. 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":http://github.com/josevalim/rails-footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate.
-* "Query Trace":http://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs.
-* "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
+* "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 Stats":https://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
* "Query Reviewer":http://code.google.com/p/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":http://github.com/rails/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.
-* "Exception Logger":http://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
+* "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.
+* "Exception Logger":https://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
h3. References
@@ -702,8 +704,6 @@ h3. References
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5
-
* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by "Emilio Tagua":credits.html#miloops
* October 19, 2008: Copy editing pass by "Mike Gunderloy":credits.html#mgunderloy
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index 146b75da3f..1f21c27ae6 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -9,6 +9,7 @@ In this guide you will:
* Generate select boxes from multiple types of data
* Understand the date and time helpers Rails provides
* Learn what makes a file upload form different
+* Learn some cases of building forms to external resources
* Find out where to look for complex forms
endprologue.
@@ -31,17 +32,18 @@ When called without arguments like this, it creates a form element that has the
Sample output from +form_tag+:
<html>
-<form action="/home/index" method="post">
+<form accept-charset="UTF-8" action="/home/index" method="post">
<div style="margin:0;padding:0">
+ <input name="utf8" type="hidden" value="&#x2713;" />
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
</div>
Form contents
</form>
</html>
-If you carefully observe this output, you can see that the helper generated something you didn't specify: a +div+ element with a hidden input inside. This is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled). You can read more about this in the "Ruby On Rails Security Guide":./security.html#_cross_site_reference_forgery_csrf.
+If you carefully observe this output, you can see that the helper generated something you didn't specify: a +div+ element with two hidden input elements inside. The first input element with name +utf8+ enforces browsers to properly respect your form's character encoding and is generated for all forms whether action is "get" or "post". Second input element with name +authenticity_token+ is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled). You can read more about this in the "Ruby On Rails Security Guide":./security.html#_cross_site_reference_forgery_csrf.
-NOTE: Throughout this guide, this +div+ with the hidden input will be stripped away to have clearer code samples.
+NOTE: Throughout this guide, this +div+ with the hidden input elements will be stripped away to have clearer code samples.
h4. A Generic Search Form
@@ -58,20 +60,20 @@ To create this form you will use +form_tag+, +label_tag+, +text_field_tag+, and
A basic search form
-<html>
+<erb>
<%= form_tag(search_path, :method => "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
-</html>
+</erb>
-TIP: +search_path+ can be a named route specified in "routes.rb": <br /><tt>map.search "search", :controller => "search"</tt>
+TIP: +search_path+ can be a named route specified in "routes.rb" as: <br /><code>match "search" => "search"</code> This declares that path "/search" will be handled by action "search" belonging to controller "search".
The above view code will result in the following markup:
<html>
-<form action="/search" method="get">
+<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" />
@@ -90,14 +92,14 @@ As with the +link_to+ helper, the path argument doesn't have to be given a strin
<ruby>
form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form")
-# => <form action="/people/search?method=get&class=nifty_form" method="post">
+# => <form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">
</ruby>
Here you wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL with extraneous parameters. The correct way of passing multiple hashes as arguments is to delimit the first hash (or both hashes) with curly brackets:
<ruby>
form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form")
-# => <form action="/people/search" method="get" class="nifty_form">
+# => <form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">
</ruby>
This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.
@@ -106,7 +108,7 @@ WARNING: Do not delimit the second hash without doing so with the first hash, ot
h4. Helpers for Generating Form Elements
-Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons, and so on. These basic helpers, with names ending in <notextile>_tag</notextile> such as +text_field_tag+, +check_box_tag+, etc., generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains
+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 <notextile>_tag</notextile> such as +text_field_tag+ and +check_box_tag+ generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains
<erb>
<%= text_field_tag(:query) %>
@@ -126,17 +128,19 @@ Checkboxes are form controls that give the user a set of options they can enable
<erb>
<%= check_box_tag(:pet_dog) %>
- <%= label_tag(:pet_dog, "I own a dog") %>
+<%= label_tag(:pet_dog, "I own a dog") %>
<%= check_box_tag(:pet_cat) %>
- <%= label_tag(:pet_cat, "I own a cat") %>
+<%= label_tag(:pet_cat, "I own a cat") %>
+</erb>
output:
+<html>
<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
- <label for="pet_dog">I own a dog</label>
+<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>
-</erb>
+<label for="pet_cat">I own a cat</label>
+</html>
The second parameter to +check_box_tag+ is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the +params+ hash). With the above form you would check the value of +params[:pet_dog]+ and +params[:pet_cat]+ to see which pets the user owns.
@@ -146,17 +150,19 @@ Radio buttons, while similar to checkboxes, are controls that specify a set of o
<erb>
<%= radio_button_tag(:age, "child") %>
- <%= label_tag(:age_child, "I am younger than 21") %>
+<%= label_tag(:age_child, "I am younger than 21") %>
<%= radio_button_tag(:age, "adult") %>
- <%= label_tag(:age_adult, "I'm over 21") %>
+<%= label_tag(:age_adult, "I'm over 21") %>
+</erb>
output:
+<html>
<input id="age_child" name="age" type="radio" value="child" />
- <label for="age_child">I am younger than 21</label>
+<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>
-</erb>
+<label for="age_adult">I'm over 21</label>
+</html>
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".
@@ -170,17 +176,19 @@ Other form controls worth mentioning are the text area, password input and hidde
<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
<%= password_field_tag(:password) %>
<%= hidden_field_tag(:parent_id, "5") %>
+</erb>
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" />
-</erb>
+</html>
Hidden inputs are not shown to the user, but they hold data like any textual input. Values inside them can be changed with JavaScript.
-TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating +filter_parameter_logging(:password)+ in your ApplicationController.
+TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged.
h3. Dealing with Model Objects
@@ -222,16 +230,16 @@ end
The corresponding view +app/views/articles/new.html.erb+ using +form_for+ looks like this:
<erb>
-<%= form_for :article, @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
+<%= form_for @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body, :size => "60x12" %>
- <%= submit_tag "Create" %>
+ <%= f.submit "Create" %>
<% end %>
</erb>
There are a few things to note here:
-# +:article+ is the name of the model and +@article+ is the actual object being edited.
+# +@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.
# 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+
@@ -239,7 +247,7 @@ There are a few things to note here:
The resulting HTML is:
<html>
-<form action="/articles/create" method="post" class="nifty_form">
+<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form">
<input id="article_title" name="article[title]" size="30" type="text" />
<textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
<input name="commit" type="submit" value="Create" />
@@ -253,7 +261,7 @@ The helper methods called on the form builder are identical to the model object
You can create a similar binding without actually creating +&lt;form&gt;+ 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, @person, :url => { :action => "create" } do |person_form| %>
+<%= 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 %>
@@ -264,7 +272,7 @@ You can create a similar binding without actually creating +&lt;form&gt;+ tags
which produces the following output:
<html>
-<form action="/people/create" class="new_person" id="new_person" method="post">
+<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" />
</form>
@@ -277,7 +285,7 @@ h4. 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>
-map.resources :articles
+resources :articles
</ruby>
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.
@@ -287,13 +295,13 @@ When dealing with RESTful resources, calls to +form_for+ can get significantly e
<ruby>
## Creating a new article
# long-style:
-form_for(:article, @article, :url => articles_path)
+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, @article, :url => article_path(@article), :html => { :method => "put" })
+form_for(@article, :url => article_path(@article), :html => { :method => "put" })
# short-style:
form_for(@article)
</ruby>
@@ -334,9 +342,10 @@ form_tag(search_path, :method => "put")
output:
<html>
-<form action="/search" method="post">
+<form accept-charset="UTF-8" action="/search" method="post">
<div style="margin:0;padding:0">
<input name="_method" type="hidden" value="put" />
+ <input name="utf8" type="hidden" value="&#x2713;" />
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
</div>
...
@@ -466,7 +475,7 @@ To leverage time zone support in Rails, you have to ask your users what time zon
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":http://github.com/rails/country_select/tree/master. 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).
+Rails _used_ to have a +country_select+ helper for choosing countries, but this has been extracted to the "country_select plugin":https://github.com/chrislerum/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).
h3. Using Date and Time Form Helpers
@@ -549,7 +558,7 @@ will produce the same output if the current year is 2009 and the value chosen by
h3. 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 form's encoding *MUST* be set to "multipart/form-data". If you forget to do this the file will not be uploaded. This can be done by passing +:multi_part => true+ as an HTML option. This means that in the case of +form_tag+ it must be passed in the second options hash and in the case of +form_for+ inside the +:html+ hash.
+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.
@@ -558,11 +567,13 @@ The following two forms both upload a file.
<%= file_field_tag 'picture' %>
<% end %>
-<%= form_for @person, :html => {:multipart => true} do |f| %>
+<%= form_for @person do |f| %>
<%= f.file_field :picture %>
<% end %>
</erb>
+NOTE: Since Rails 3.1, forms rendered using +form_for+ have their encoding set to <tt>multipart/form-data</tt> automatically once a +file_field+ is used inside the block. Previous versions required you to set this explicitly.
+
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]+.
h4. What Gets Uploaded
@@ -578,13 +589,13 @@ def upload
end
</ruby>
-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 plugins designed to assist with these. Two of the better known ones are "Attachment-Fu":http://github.com/technoweenie/attachment_fu and "Paperclip":http://www.thoughtbot.com/projects/paperclip.
+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 plugins designed to assist with these. Two of the better known ones are "Attachment-Fu":https://github.com/technoweenie/attachment_fu 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.
h4. Dealing with Ajax
-Unlike other forms making an asynchronous file upload form is not as simple as replacing +form_for+ with +remote_form_for+. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
+Unlike other forms making an asynchronous file upload form is not as simple as providing +form_for+ with <tt>:remote => true</tt>. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
h3. Customizing Form Builders
@@ -631,7 +642,12 @@ action for a Person model, +params[:model]+ would usually be a hash of all the a
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 Rails' parameter parser. For example <tt> ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789" # => {"name"=>"fred", "phone"=>"0123456789"} </tt>
+TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example,
+
+<ruby>
+ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
+# => {"name"=>"fred", "phone"=>"0123456789"}
+</ruby>
h4. Basic Structures
@@ -707,7 +723,7 @@ You might want to render a form with a set of edit fields for each of a person's
Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:
<html>
-<form action="/people/1" class="edit_person" id="edit_person_1" method="post">
+<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
<input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
<input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
@@ -748,6 +764,40 @@ As a shortcut you can append [] to the name and omit the +:index+ option. This i
produces exactly the same output as the previous example.
+h3. Forms to external resources
+
+If you need to post some data to an external resource it is still great to build your from using rails form helpers. But sometimes you need to set an +authenticity_token+ for this resource. You can do it by passing an +:authenticity_token => 'your_external_token'+ parameter to the +form_tag+ options:
+
+<erb>
+<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
+ Form contents
+<% end %>
+</erb>
+
+Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an +authenticity_token+ hidden field at all. For doing this just pass +false+ to the +:authenticity_token+ option:
+
+<erb>
+<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
+ Form contents
+<% end %>
+</erb>
+
+The same technique is available for the +form_for+ too:
+
+<erb>
+<%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
+ Form contents
+<% end %>
+</erb>
+
+Or if you don't want to render an +authenticity_token+ field:
+
+<erb>
+<%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
+ Form contents
+<% end %>
+</erb>
+
h3. Building Complex Forms
Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:
@@ -755,14 +805,13 @@ Many apps grow beyond simple forms editing a single object. For example when cre
* As of Rails 2.3, Rails includes "Nested Attributes":./2_3_release_notes.html#nested-attributes and "Nested Object Forms":./2_3_release_notes.html#nested-object-forms
* Ryan Bates' series of Railscasts on "complex forms":http://railscasts.com/episodes/75
* Handle Multiple Models in One Form from "Advanced Rails Recipes":http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf
-* Eloy Duran's "complex-forms-examples":http://github.com/alloy/complex-form-examples/ application
-* Lance Ivy's "nested_assignment":http://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":http://github.com/cainlevy/complex-form-examples/tree/cainlevy
-* James Golick's "attribute_fu":http://github.com/jamesgolick/attribute_fu plugin
+* Eloy Duran's "complex-forms-examples":https://github.com/alloy/complex-form-examples/ application
+* Lance Ivy's "nested_assignment":https://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":https://github.com/cainlevy/complex-form-examples/tree/cainlevy
+* James Golick's "attribute_fu":https://github.com/jamesgolick/attribute_fu plugin
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/1
-
+* February 5, 2011: Added 'Forms to external resources' section. Timothy N. Tsvetkov <timothy.tsvetkov@gmail.com>
* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
h3. Authors
diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile
index c5b41673e1..d32ba48003 100644
--- a/railties/guides/source/generators.textile
+++ b/railties/guides/source/generators.textile
@@ -1,6 +1,6 @@
-h2. Creating and Customizing Rails Generators
+h2. Creating and Customizing Rails Generators & Templates
-Rails generators are an essential tool if you plan to improve your workflow and in this guide you will learn how to create and customize already existing generators.
+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.
In this guide you will:
@@ -10,10 +10,11 @@ In this guide you will:
* Customize your scaffold by creating new generators
* Customize your scaffold by changing generator templates
* Learn how to use fallbacks to avoid overwriting a huge set of generators
+* Learn how to create an application template
endprologue.
-NOTE: This guide is about Rails generators for versions >= 3.0. Rails generators from previous versions are not supported.
+NOTE: This guide is about generators in Rails 3, previous versions are not covered.
h3. First Contact
@@ -33,9 +34,9 @@ $ rails generate helper --help
h3. Creating Your First Generator
-Since Rails 3.0, generators are built on top of "Thor":http://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+.
+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 +RAILS_APP/lib/generators/initializer_generator.rb+ with the following content:
+The first step is to create a file at +lib/generators/initializer_generator.rb+ with the following content:
<ruby>
class InitializerGenerator < Rails::Generators::Base
@@ -45,6 +46,8 @@ class InitializerGenerator < Rails::Generators::Base
end
</ruby>
+NOTE: +create_file+ is a method provided by +Thor::Actions+ and the documentation for it and its brethren can be found at "rdoc.info":http://rdoc.info/github/wycats/thor/master/Thor/Actions.
+
Our new generator is quite simple: it inherits from +Rails::Generators::Base+ and has one method definition. Each public method in the generator is executed when a generator is invoked. 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:
@@ -74,7 +77,7 @@ Now we can see the new description by invoking +--help+ on the new generator. Th
h3. Creating Generators with Generators
-A faster way to create a generator is using the generator's generator:
+Generators themselves have a generator:
<shell>
$ rails generate generator initializer
@@ -84,7 +87,7 @@ $ rails generate generator initializer
create lib/generators/initializer/templates
</shell>
-And it will create a new generator as follows:
+This is the generator just created:
<ruby>
class InitializerGenerator < Rails::Generators::NamedBase
@@ -92,7 +95,7 @@ class InitializerGenerator < Rails::Generators::NamedBase
end
</ruby>
-First, notice that we are inheriting from +Rails::Generators::NamedBase+ instead of +Rails::Generators::Base+. This means that our generator expects as least one argument, which will be the name of the initializer.
+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):
@@ -102,7 +105,9 @@ Usage:
rails generate initializer NAME [options]
</shell>
-We can also see in our new generator that it has a class method called +source_root+. This method points to where our generator templates will be placed and by default it points to the created directory under +RAILS_APP/lib/generators/initializer/templates+. In order to understand what a generator template means, let's create a file at +RAILS_APP/lib/generators/initializer/templates/initializer.rb+ with the following content:
+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
@@ -124,16 +129,16 @@ end
And let's execute our generator:
<shell>
-$ rails generate initializer foo
+$ rails generate initializer core_extensions
</shell>
-We can see that now a initializer named foo was created at +config/initializers/foo.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+.
+We can see that now a 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+.
-h3. Generators Lookup
+The methods that are available for generators are covered in the "final section":#generator-methods of this guide.
-Now that we've created our first generator, we need to briefly discuss generator lookup. The way Rails finds generators is exactly the same way Ruby find files, i.e. using +$LOAD_PATHS+.
+h3. Generators Lookup
-For instance, when you say +rails generate initializer foo+, Rails knows you want to invoke the initializer generator and then search for the following generators in the $LOAD_PATHS:
+When you run +rails generate initializer core_extensions+ Rails requires these files in turn until one is found:
<shell>
rails/generators/initializer/initializer_generator.rb
@@ -142,11 +147,13 @@ rails/generators/initializer_generator.rb
generators/initializer_generator.rb
</shell>
-If none of them is found, it raises an error message.
+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+.
h3. Customizing Your Workflow
-Rails generators are flexible enough to let you customize your scaffold the way you want. In your +config/application.rb+ there is a section just for generators:
+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|
@@ -166,7 +173,7 @@ $ rails generate scaffold User name:string
invoke test_unit
create test/unit/user_test.rb
create test/fixtures/users.yml
- route map.resources :users
+ route resources :users
invoke scaffold_controller
create app/controllers/users_controller.rb
invoke erb
@@ -186,9 +193,9 @@ $ rails generate scaffold User name:string
create public/stylesheets/scaffold.css
</shell>
-Looking at this output, it's easy to understand how generators work on 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.
+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 on scaffold. We can achieve that by changing our application to the following:
+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|
@@ -199,18 +206,18 @@ config.generators do |g|
end
</ruby>
-If we generate another resource on scaffold, we can notice that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use +Datamapper+ and +RSpec+ instead of +ActiveRecord+ and +TestUnit+, it's just a matter of adding their gems to your application and configuring your generators.
+If we generate another resource with the scaffold generator, we can see that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it's just a matter of adding their gems to your application and configuring your generators.
-To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator:
+To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks:
<shell>
-$ rails generate generator my_helper
+$ rails generate generator rails/my_helper
</shell>
After that, we can delete both the +templates+ directory and the +source_root+ class method from our new generators, because we are not going to need them. So our new generator looks like the following:
<ruby>
-class MyHelperGenerator < Rails::Generators::NamedBase
+class Rails::MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
@@ -224,18 +231,18 @@ end
We can try out our new generator by creating a helper for users:
<shell>
-$ rails generate my_helper users
+$ rails generate my_helper products
</shell>
And it will generate the following helper file in +app/helpers+:
<ruby>
-module UsersHelper
- attr_reader :users, :user
+module ProductsHelper
+ attr_reader :products, :product
end
</ruby>
-Which is what we expected. We can now tell scaffold to use our new helper generator by configuring +config/application.rb+ once again:
+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|
@@ -247,7 +254,7 @@ config.generators do |g|
end
</ruby>
-And see it in action when invoking generator once again:
+and see it in action when invoking the generator:
<shell>
$ rails generate scaffold Post body:text
@@ -260,10 +267,10 @@ We can notice on the output that our new helper was invoked instead of the Rails
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 your generator to the following:
+To do that, we can change the generator this way:
<ruby>
-class MyHelperGenerator < Rails::Generators::NamedBase
+class Rails::MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
@@ -276,7 +283,7 @@ end
end
</ruby>
-Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +MyHelper::Generators::TestUnitGenerator+ and +TestUnit::Generators::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add:
+Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +Rails::TestUnitGenerator+ and +TestUnit::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add:
<ruby>
# Search for :helper instead of :my_helper
@@ -287,9 +294,9 @@ And now you can re-run scaffold for another resource and see it generating tests
h3. 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 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 inside +RAILS_APP/lib/templates+. Since we want to customize +Rails::Generators::HelperGenerator+, we can do that by simply making a template copy inside +RAILS_APP/lib/templates/rails/helper+ with the name +helper.rb+. So let's create that file with the following content:
+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
@@ -297,7 +304,7 @@ module <%= class_name %>Helper
end
</erb>
-So now we can revert the changes in +config/application.rb+:
+and revert the last change in +config/application.rb+:
<ruby>
config.generators do |g|
@@ -308,11 +315,11 @@ config.generators do |g|
end
</ruby>
-If you generate another resource, you can see that we got 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 +RAILS_APP/lib/templates/erb/scaffold+.
+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+.
h3. 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 test framework, like "shoulda":http://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 +Shoulda+ namespace.
+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 +Shoulda+ namespace.
We can easily simulate this behavior by changing our +config/application.rb+ once again:
@@ -328,7 +335,7 @@ config.generators do |g|
end
</ruby>
-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 test unit generators:
+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:
<shell>
$ rails generate scaffold Comment body:text
@@ -338,7 +345,7 @@ $ rails generate scaffold Comment body:text
invoke shoulda
create test/unit/comment_test.rb
create test/fixtures/comments.yml
- route map.resources :comments
+ route resources :comments
invoke scaffold_controller
create app/controllers/comments_controller.rb
invoke erb
@@ -359,9 +366,258 @@ $ rails generate scaffold Comment body:text
Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication.
+h3. Application templates
+
+Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred as a "template".
+
+<ruby>
+gem("rspec-rails", :group => "test")
+gem("cucumber-rails", :group => "test")
+
+if yes?("Would you like to install Devise?")
+ gem("devise")
+ generate("devise:install")
+ model_name = ask("What would you like the user model to be called? [user]")
+ model_name = "user" if model_name.blank?
+ generate("devise", model_name)
+end
+</ruby>
+
+In the above template we specify that the application relies on the +rspec-rails+ and +cucumber-rails+ gem so these two will be added to the +test+ group in the +Gemfile+. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the +Gemfile+ outside of any group and then runs the +devise:install+ generator. This template then takes the users input and runs the +devise+ generator, with the user's answer from the last question being passed to this generator.
+
+Imagine that this template was in a file called +template.rb+. We can use it to modify the outcome of the +rails new+ command by using the +-m+ option and passing in the filename:
+
+<shell>
+$ rails new thud -m template.rb
+</shell>
+
+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:
+
+<shell>
+$ rails new thud -m https://gist.github.com/722911.txt
+</shell>
+
+Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.
+
+h3. Generator methods
+
+The following are methods available for both generators and templates for Rails.
+
+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
+
+h4. +plugin+
+
++plugin+ will install a plugin into the current application.
+
+<ruby>
+ plugin("dynamic-form", :git => "git://github.com/rails/dynamic-form.git")
+</ruby>
+
+Available options are:
+
+* +:git+ - Takes the path to the git repository where this plugin can be found.
+* +:branch+ - The name of the branch of the git repository where the plugin is found.
+* +:submodule+ - Set to +true+ for the plugin to be installed as a submodule. Defaults to +false+.
+* +:svn+ - Takes the path to the svn repository where this plugin can be found.
+* +:revision+ - The revision of the plugin in an SVN repository.
+
+h4. +gem+
+
+Specifies a gem dependency of the application.
+
+<ruby>
+gem("rspec", :group => "test", :version => "2.1.0")
+gem("devise", "1.1.5")
+</ruby>
+
+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")
+</ruby>
+
+The above code will put the following line into +Gemfile+:
+
+<ruby>
+ gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master"
+</ruby>
+
+
+h4. +add_source+
+
+Adds a specified source to +Gemfile+:
+
+<ruby>
+ add_source "http://gems.github.com"
+</ruby>
+
+h4. +application+
+
+Adds a line to +config/application.rb+ directly after the application class definition.
+
+<ruby>
+ application "config.asset_host = 'http://example.com'"
+</ruby>
+
+This method can also take a block:
+
+<ruby>
+application do
+ "config.asset_host = 'http://example.com'"
+end
+</ruby>
+
+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
+</ruby>
+
+h4. +git+
+
+Runs the specified git command:
+
+<ruby>
+ git :init
+ git :add => "."
+ git :commit => "-m First commit!"
+ git :add => "onefile.rb", :rm => "badfile.cxx"
+</ruby>
+
+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.
+
+h4. +vendor+
+
+Places a file into +vendor+ which contains the specified code.
+
+<ruby>
+ vendor("sekrit.rb", '#top secret stuff')
+</ruby>
+
+This method also takes a block:
+
+<ruby>
+ vendor("seeds.rb") do
+ "puts 'in ur app, seeding ur database'"
+ end
+</ruby>
+
+h4. +lib+
+
+Places a file into +lib+ which contains the specified code.
+
+<ruby>
+ lib("special.rb", 'p Rails.root')
+</ruby>
+
+This method also takes a block:
+
+<ruby>
+lib("super_special.rb") do
+ puts "Super special!"
+end
+</ruby>
+
+h4. +rakefile+
+
+Creates a Rake file in the +lib/tasks+ directory of the application.
+
+<ruby>
+ rakefile("test.rake", 'hello there')
+</ruby>
+
+This method also takes a block:
+
+<ruby>
+rakefile("test.rake") do
+ %Q{
+ task :rock => :environment do
+ puts "Rockin'"
+ end
+ }
+end
+</ruby>
+
+h4. +initializer+
+
+Creates an initializer in the +config/initializers+ directory of the application:
+
+<ruby>
+ initializer("begin.rb", "puts 'this is the beginning'")
+</ruby>
+
+This method also takes a block:
+
+<ruby>
+initializer("begin.rb") do
+ puts "Almost done!"
+end
+</ruby>
+
+h4. +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")
+</ruby>
+
+
+h4. +rake+
+
+Runs the specified Rake task.
+
+<ruby>
+ rake("db:migrate")
+</ruby>
+
+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+.
+
+h4. +capify!+
+
+Runs the +capify+ command from Capistrano at the root of the application which generates Capistrano configuration.
+
+<ruby>
+ capify!
+</ruby>
+
+h4. +route+
+
+Adds text to the +config/routes.rb+ file:
+
+<ruby>
+ route("resources :people")
+</ruby>
+
+h4. +readme+
+
+Output the contents of a file in the template's +source_path+, usually a README.
+
+<ruby>
+ readme("README")
+</ruby>
+
h3. Changelog
-"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/102
+* December 1, 2010: Documenting the available methods and options for generators and templates by "Ryan Bigg":http://ryanbigg.com
+* December 1, 2010: Addition of Rails application templates by "Ryan Bigg":http://ryanbigg.com
+
+* August 23, 2010: Edit pass by "Xavier Noria":credits.html#fxn
* April 30, 2010: Reviewed by José Valim
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index ffb0310816..0661549644 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -110,7 +110,7 @@ Active Resource provides a framework for managing the connection between busines
h5. Active Support
-Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications.
+Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in Rails, both by the core code and by your applications.
h5. Railties
@@ -149,13 +149,11 @@ Usually run this as the root user:
# gem install rails
</shell>
-NOTE. In the Rails 3.0.0-beta, you will need to manually install the dependencies for Rails itself as a bug in rubygems will cause these to not be installed, see the "3.0 Release Notes":3_0_release_notes.html for the commands to run.
-
-TIP. If you're working on Windows, you may find it easier to install "Instant Rails":http://instantrails.rubyforge.org/wiki/wiki.pl. Be aware, though, that Instant Rails releases tend to lag seriously behind the actual Rails version. Also, you will find that Rails development on Windows is overall less pleasant than on other operating systems. If at all possible, we suggest that you install a Linux virtual machine and use that for Rails development, instead of using Windows.
+TIP. If you're working on Windows, you can quickly install Ruby and Rails with "Rails Installer":http://railsinstaller.org.
h4. Creating the Blog Application
-The best way to use this guide is to follow each step as it happens, no code or step needed to make this example application has been left out, so you can literally follow along step by step. If you need to see the completed code, you can download it from "Getting Started Code":http://github.com/mikel/getting-started-code.
+The best way to use this guide is to follow each step as it happens, no code or step needed to make this example application has been left out, so you can literally follow along step by step. If you need to see the completed code, you can download it from "Getting Started Code":https://github.com/mikel/getting-started-code.
To begin, open a terminal, navigate to a folder where you have rights to create files, and type:
@@ -165,7 +163,7 @@ $ rails new blog
This will create a Rails application called Blog in a directory called blog.
-TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails -h</tt>.
+TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails new -h</tt>.
After you create the blog application, switch to its folder to continue work directly in that application:
@@ -177,7 +175,7 @@ In any case, Rails will create a folder in your working directory called <tt>blo
|_.File/Folder|_.Purpose|
|Gemfile|This file allows you to specify what gem dependencies are needed for your Rails application.|
-|README.rdoc|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.|
+|README|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.|
|Rakefile|This file contains batch jobs that can be run from the terminal.|
|app/|Contains the controllers, models, and views for your application. You'll focus on this folder for the remainder of this guide.|
|config/|Configure your application's runtime rules, routes, database, and more.|
@@ -186,7 +184,7 @@ In any case, Rails will create a folder in your working directory called <tt>blo
|doc/|In-depth documentation for your application.|
|lib/|Extended modules for your application (not covered in this guide).|
|log/|Application log files.|
-|public/|The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.|
+|public/|The only folder seen to the world as-is. This is where your images, JavaScript files, stylesheets (CSS), and other static files go.|
|script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
|test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html|
|tmp/|Temporary files|
@@ -194,15 +192,13 @@ In any case, Rails will create a folder in your working directory called <tt>blo
h4. Installing the Required Gems
-Rails uses the "Bundler":http://www.github.com/carlhuda/bundler gem to populate the +vendor+ directory with all the gems your application depends on. As we don't need any special gems beyond the default, we just need to do the following:
+Rails applications manage gem dependencies with "Bundler":http://gembundler.com/v1.0/index.html by default. As we don't need any other gems beyond the ones in the generated +Gemfile+ we can directly run
<shell>
-As the root user:
-# gem install bundler
-# bundle install
+$ bundle install
</shell>
-This will copy down the versions of all the gems you need to start a rails application.
+to have them ready.
h4. Configuring a Database
@@ -231,11 +227,11 @@ NOTE: In this guide we are using an SQLite3 database for data storage, because i
h5. Configuring a MySQL Database
-If you choose to use MySQL instead of the shipped Sqlite3 database, your +config/database.yml+ will look a little different. Here's the development section:
+If you choose to use MySQL instead of the shipped SQLite3 database, your +config/database.yml+ will look a little different. Here's the development section:
<yaml>
development:
- adapter: mysql
+ adapter: mysql2
encoding: utf8
database: blog_development
pool: 5
@@ -262,6 +258,8 @@ development:
Change the username and password in the +development+ section as appropriate.
+TIP: You don't have to update the database configurations manually. If you had a look at the options of application generator, you have seen that one of them is named <tt>--database</tt>. It lets you choose an adapter for couple of most used relational databases. You can even run the generator repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite.
+
h4. Creating the Database
Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command:
@@ -276,7 +274,7 @@ TIP: Rake is a general-purpose command-runner that Rails uses for many things. Y
h3. Hello, Rails!
-One of the traditional places to start with a new language is by getting some text up on screen quickly, to do this, you need to get your Rails application server running.
+One of the traditional places to start with a new language is by getting some text up on screen quickly. To do this, you need to get your Rails application server running.
h4. Starting up the Web Server
@@ -286,7 +284,7 @@ You actually have a functional Rails application already. To see it, you need to
$ rails server
</shell>
-This will fire up an instance of the Mongrel web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. You should see Rails' default information page:
+This will fire up an instance of the WEBrick web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. You should see Rails' default information page:
!images/rails_welcome.png(Welcome Aboard screenshot)!
@@ -302,7 +300,7 @@ To get Rails saying "Hello", you need to create at minimum a controller and a vi
$ rails generate controller home index
</shell>
-TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: +ruby \path\to\rails controller home index+.
+TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: <tt>ruby \path\to\your\application\script\rails generate controller home index</tt>.
Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code:
@@ -320,9 +318,9 @@ The first step to doing this is to delete the default page from your application
$ rm public/index.html
</shell>
-We need to do this as Rails will deliver any static file in the +public+ directory in preference to any dynamic contact we generate from the controllers.
+We need to do this as Rails will deliver any static file in the +public+ directory in preference to any dynamic content we generate from the controllers.
-Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. 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+, uncomment it and change it like the following:
+Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. 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+, uncomment it and change it like the following:
<ruby>
Blog::Application.routes.draw do
@@ -351,12 +349,12 @@ In the case of the blog application, you can start by generating a scaffolded Po
$ rails generate scaffold Post name:string title:string content:text
</shell>
-NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch.
+NOTE. While scaffolding will get you up and running quickly, the code it generates is unlikely to be a perfect fit for your application. You'll most probably want to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. Rails, however, makes it really simple to customize templates for generated models, controllers, views and other source files. You'll find more information in the "Creating and Customizing Rails Generators & Templates":generators.html guide.
The scaffold generator will build 15 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates:
|_.File |_.Purpose|
-|db/migrate/20100207214725_create_posts.rb.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
+|db/migrate/20100207214725_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
|app/models/post.rb |The Post model|
|test/fixtures/posts.yml |Dummy posts for use in testing|
|app/controllers/posts_controller.rb |The Posts controller|
@@ -413,7 +411,7 @@ Rails will execute this migration command and tell you it created the Posts tabl
== CreatePosts: migrated (0.0020s) ===========================================
</shell>
-NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file.
+NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitly pass it when invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.
h4. Adding a Link
@@ -471,28 +469,32 @@ To see your validations in action, you can use the console. The console is a com
$ rails console
</shell>
+TIP: The default console will make changes to your database. You can instead open a console that will roll back any changes you make by using +rails console --sandbox+.
+
After the console loads, you can use it to work with your application's models:
<shell>
>> p = Post.new(:content => "A new post")
-=> #<Post id: nil, name: nil, title: nil,
+=> #<Post id: nil, name: nil, title: nil,
content: "A new post", created_at: nil,
updated_at: nil>
>> p.save
=> false
>> p.errors
-=> #<OrderedHash { :title=>["can't be blank",
+=> #<OrderedHash { :title=>["can't be blank",
"is too short (minimum is 5 characters)"],
:name=>["can't be blank"] }>
</shell>
This code shows creating a new +Post+ instance, attempting to save it and getting +false+ for a return value (indicating that the save failed), and inspecting the +errors+ of the post.
+When you're finished, type +exit+ and hit +return+ to exit the console.
+
TIP: Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes to your models while the console is open, type +reload!+ at the console prompt to load them.
h4. Listing All Posts
-The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb + and look at the +index+ action:
+The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb+ and look at the +index+ action:
<ruby>
def index
@@ -505,7 +507,7 @@ def index
end
</ruby>
-+Post.all+ calls the +Post+ model to return all of the posts currently in the database. The result of this call is an array containing the posts which has been saved in an instance variable called +@posts+.
++Post.all+ calls the +Post+ model to return all of the posts currently in the database. The result of this call is an array of posts that we store in a instance variable called +@posts+.
TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html.
@@ -552,7 +554,7 @@ TIP: For more details on the rendering process, see "Layouts and Rendering in Ra
h4. Customizing the Layout
-The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. In previous versions of Rails, the +rails generate scaffold+ command would automatically create a controller specific layout, like +app/views/layouts/posts.html.erb+, for the posts controller. However this has been changed in Rails 3.0. A application specific +layout+ is used for all the controllers and can be found in +app/views/layouts/application.html.erb+. Open this layout in your editor and modify the +body+ tag:
+The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. In previous versions of Rails, the +rails generate scaffold+ command would automatically create a controller specific layout, like +app/views/layouts/posts.html.erb+, for the posts controller. However this has been changed in Rails 3.0. An application specific +layout+ is used for all the controllers and can be found in +app/views/layouts/application.html.erb+. Open this layout in your editor and modify the +body+ tag:
<erb>
<!DOCTYPE html>
@@ -561,7 +563,7 @@ The view is only part of the story of how HTML is displayed in your web browser.
<title>Blog</title>
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag :defaults %>
- <%= csrf_meta_tag %>
+ <%= csrf_meta_tags %>
</head>
<body style="background: #EEEEEE;">
@@ -668,7 +670,7 @@ The +create+ action instantiates a new Post object from the data supplied by the
If the post was not successfully saved, due to a validation error, then the controller returns the user back to the +new+ action with any error messages so that the user has the chance to fix the error and try again.
-The "Post was successfully created" message is stored inside of the Rails +flash+ hash, (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created."
+The "Post was successfully created." message is stored inside of the Rails +flash+ hash, (usually just called _the flash_) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created."
h4. Showing an Individual Post
@@ -729,7 +731,6 @@ After finding the requested post, Rails uses the +edit.html.erb+ view to display
<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>
-<% end %>
</erb>
Again, as with the +new+ action, the +edit+ action is using the +form+ partial, this time however, the form will do a PUT action to the PostsController and the submit button will display "Update Post"
@@ -742,7 +743,7 @@ def update
respond_to do |format|
if @post.update_attributes(params[:post])
- format.html { redirect_to(@post,
+ format.html { redirect_to(@post,
:notice => 'Post was successfully updated.') }
format.xml { head :ok }
else
@@ -814,6 +815,8 @@ class CreateComments < ActiveRecord::Migration
t.timestamps
end
+
+ add_index :comments, :post_id
end
def self.down
@@ -822,7 +825,7 @@ class CreateComments < ActiveRecord::Migration
end
</ruby>
-The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration:
+The +t.references+ line sets up a foreign key column for the association between the two models. And the +add_index+ line sets up an index for this association column. Go ahead and run the migration:
<shell>
$ rake db:migrate
@@ -922,8 +925,6 @@ So first, we'll wire up the Post show template (+/app/views/posts/show.html.erb+
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
@@ -992,8 +993,6 @@ Once we have made the new comment, we send the user back to the original post us
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
@@ -1015,7 +1014,7 @@ Once we have made the new comment, we send the user back to the original post us
Now you can add posts and comments to your blog and have them show up in the right places.
-h3. Refactorization
+h3. Refactoring
Now that we have Posts and Comments working, if we take a look at the +app/views/posts/show.html.erb+ template, it's getting long and awkward. We can use partials to clean this up.
@@ -1056,13 +1055,10 @@ Then in the +app/views/posts/show.html.erb+ you can change it to look like the f
</p>
<h2>Comments</h2>
-<%= render :partial => "comments/comment",
- :collection => @post.comments %>
+<%= render @post.comments %>
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
@@ -1090,8 +1086,6 @@ Lets also move that new comment section out to it's own partial, again, you crea
<erb>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
@@ -1127,8 +1121,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following:
</p>
<h2>Comments</h2>
-<%= render :partial => "comments/comment",
- :collection => @post.comments %>
+<%= render @post.comments %>
<h2>Add a comment:</h2>
<%= render "comments/form" %>
@@ -1139,7 +1132,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following:
<%= link_to 'Back to Posts', posts_path %> |
</erb>
-The second render just defines the partial template we want to render, <tt>comments/form</tt>, Rails is smart enough to spot the forward slash in that string and realise that you want to render the <tt>_form.html.erb</tt> file in the <tt>app/views/comments</tt> directory.
+The second render just defines the partial template we want to render, <tt>comments/form</tt>, Rails is smart enough to spot the forward slash in that string and realize that you want to render the <tt>_form.html.erb</tt> file in the <tt>app/views/comments</tt> directory.
The +@post+ object is available to any partials rendered in the view because we defined it as an instance variable.
@@ -1213,15 +1206,15 @@ Rails provides a very simple HTTP authentication system that will work nicely in
<ruby>
class ApplicationController < ActionController::Base
protect_from_forgery
-
+
private
-
+
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == 'admin' && password == 'password'
end
end
-
+
end
</ruby>
@@ -1277,7 +1270,7 @@ Again, run the migration to create the database table:
$ rake db:migrate
</shell>
-Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails (via the +accepts_nested_attributes+ macro) that you intend to edit tags via posts:
+Next, edit the +post.rb+ file to create the other side of the association, and to tell Rails (via the +accepts_nested_attributes_for+ macro) that you intend to edit tags via posts:
<ruby>
class Post < ActiveRecord::Base
@@ -1381,8 +1374,7 @@ Finally, we will edit the <tt>app/views/posts/show.html.erb</tt> template to sho
</p>
<h2>Comments</h2>
-<%= render :partial => "comments/comment",
- :collection => @post.comments %>
+<%= render @post.comments %>
<h2>Add a comment:</h2>
<%= render "comments/form" %>
@@ -1405,7 +1397,7 @@ Open up <tt>app/helpers/posts_helper.rb</tt> and add the following:
<erb>
module PostsHelper
def join_tags(post)
- post.tags.map { |t| t.name }.join(", ")
+ post.tags.map { |t| t.name }.join(", ")
end
end
</erb>
@@ -1436,8 +1428,7 @@ Now you can edit the view in <tt>app/views/posts/show.html.erb</tt> to look like
</p>
<h2>Comments</h2>
-<%= render :partial => "comments/comment",
- :collection => @post.comments %>
+<%= render @post.comments %>
<h2>Add a comment:</h2>
<%= render "comments/form" %>
@@ -1451,7 +1442,8 @@ h3. 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 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
* The "Rails Wiki":http://wiki.rubyonrails.org/
@@ -1483,8 +1475,7 @@ Two very common sources of data that are not UTF-8:
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2
-
+* August 30, 2010: Minor editing after Rails 3 release by "Joost Baaij":http://www.spacebabies.nl
* July 12, 2010: Fixes, editing and updating of code samples by "Jaime Iniesta":http://jaimeiniesta.com
* May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have by "Yehuda Katz":http://www.yehudakatz.com
* April 30, 2010: Fixes, editing and updating of code samples by "Rohit Arondekar":http://rohitarondekar.com
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 63d22db485..3e7e396e8d 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -1,4 +1,4 @@
-h2. Rails Internationalization (I18n) API
+lh2. Rails Internationalization (I18n) API
The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for *translating your application to a single custom language* other than English or for *providing multi-language support* in your application.
@@ -10,7 +10,7 @@ So, in the process of _internationalizing_ your Rails application you have to:
* Tell Rails where to find locale dictionaries
* Tell Rails how to set, preserve and switch locale
-In the process of _localizing_ your application you'll probably want to do following three things:
+In the process of _localizing_ your application you'll probably want to do the following three things:
* Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc
* Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc.
@@ -87,11 +87,11 @@ en:
hello: "Hello world"
</ruby>
-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+":http://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+":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.
+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/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.
The I18n library will use *English* as a *default locale*, i.e. if you don't set a different locale, +:en+ will be used for looking up translations.
-NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cz+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-UK+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":http://github.com/joshmh/globalize2/tree/master may help you implement it.
+NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cz+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-UK+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":https://github.com/joshmh/globalize2/tree/master may help you implement it.
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.
@@ -127,7 +127,7 @@ If you want to translate your Rails application to a *single language other than
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 _cookie_. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being "_RESTful_":http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in "Stefan Tilkov's articles":http://www.infoq.com/articles/rest-introduction. There may be some exceptions to this rule, which are discussed below.
+WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. 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 approach in "Stefan Tilkov's articles":http://www.infoq.com/articles/rest-introduction. There may be some exceptions to this rule, which are discussed below.
The _setting part_ is easy. You can set the locale in a +before_filter+ in the +ApplicationController+ like this:
@@ -231,6 +231,17 @@ end
Now, when you call the +books_path+ method you should get +"/en/books"+ (for the default locale). An URL like +http://localhost:3001/nl/books+ should load the Netherlands locale, then, and following calls to +books_path+ should return +"/nl/books"+ (because the locale changed).
+If you don't want to force the use of a locale in your routes you can use an optional path scope (donated by the use brackets) like so:
+
+<ruby>
+# config/routes.rb
+scope "(:locale)", :locale => /en|nl/ do
+ resources :books
+end
+</ruby>
+
+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:
@@ -242,7 +253,7 @@ 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.)
-IMPORTANT: This solution has currently one rather big *downside*. Due to the _default_url_options_ implementation, you have to pass the +:id+ option explicitly, like this: +link_to 'Show', book_url(:id => book)+ and not depend on Rails' magic in code like +link_to 'Show', book+. If this should be a problem, have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":http://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":http://github.com/raul/translate_routes/tree/master. See also the page "How to encode the current locale in the URL":http://rails-i18n.org/wiki/wikipages/how-to-encode-the-current-locale-in-the-url in the Rails i18n Wiki.
+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.
h4. Setting the Locale from the Client Supplied Information
@@ -267,7 +278,7 @@ def extract_locale_from_accept_language_header
end
</ruby>
-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":http://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's "locale":http://github.com/rtomayko/rack-contrib/blob/master/lib/rack/locale.rb.
+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.
h5. Using GeoIP (or Similar) Database
@@ -294,12 +305,12 @@ end
# app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
- flash[:notice] = "Hello flash!"
+ flash[:notice] = "Hello Flash"
end
end
# app/views/home/index.html.erb
-<h1>Hello world!</h1>
+<h1>Hello World</h1>
<p><%= flash[:notice] %></p>
</ruby>
@@ -333,8 +344,8 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo
<ruby>
# config/locales/en.yml
en:
- hello_world: Hello World
- hello_flash: Hello Flash
+ hello_world: Hello world!
+ hello_flash: Hello flash!
# config/locales/pirate.yml
pirate:
@@ -379,7 +390,7 @@ So that would give you:
!images/i18n/demo_localized_pirate.png(rails i18n demo localized time to pirate)!
-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":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locales/+ directory, they will automatically be ready for use.
+TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the "rails-i18n repository at Github":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locales/+ directory, they will automatically be ready for use.
h4. Localized Views
@@ -453,24 +464,24 @@ 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 :invalid, :scope => [:activerecord, :errors, :messages]
+I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages]
</ruby>
-This looks up the +:invalid+ message in the Active Record error 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.invalid"
+I18n.translate "activerecord.errors.messages.record_invalid"
</ruby>
Thus the following calls are equivalent:
<ruby>
-I18n.t 'activerecord.errors.messages.invalid'
-I18n.t 'errors.messages.invalid', :scope => :active_record
-I18n.t :invalid, :scope => 'activerecord.errors.messages'
-I18n.t :invalid, :scope => [:activerecord, :errors, :messages]
+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]
</ruby>
h5. Defaults
@@ -518,7 +529,7 @@ es:
title: "Título"
</yaml>
-you can look up the +books.index.title+ value *inside* +app/views/books/index.html.erb+ template like this (note the dot):
+you can look up the +books.index.title+ value *inside* +app/views/books/index.html.erb+ template like this (note the dot):
<ruby>
<%= t '.title' %>
@@ -575,7 +586,7 @@ I18n.t :foo
I18n.l Time.now
</ruby>
-Explicitely passing a locale:
+Explicitly passing a locale:
<ruby>
I18n.t :foo, :locale => :de
@@ -612,7 +623,7 @@ pt:
bar: baz
</ruby>
-As you see, in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
+As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
Here is a "real" example from the Active Support +en.yml+ translations YAML file:
@@ -638,7 +649,7 @@ Generally we recommend using YAML as a format for storing translations. There ar
h4. Translations for Active Record Models
-You can use the methods +Model.human_name+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names.
+You can use the methods +Model.model_name.human+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names.
For example when you add the following translations:
@@ -653,7 +664,7 @@ en:
# will translate User attribute "login" as "Handle"
</ruby>
-Then +User.human_name+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle".
+Then +User.model_name.human+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle".
h5. Error Message Scopes
@@ -661,11 +672,11 @@ Active Record validation error messages can also be translated easily. Active Re
This gives you quite powerful means to flexibly adjust your messages to your application's needs.
-Consider a User model with a +validates_presence_of+ validation for the name attribute like this:
+Consider a User model with a validation for the name attribute like this:
<ruby>
class User < ActiveRecord::Base
- validates_presence_of :name
+ validates :name, :presence => true
end
</ruby>
@@ -675,6 +686,8 @@ The key for the error message in this case is +:blank+. Active Record will look
activerecord.errors.models.[model_name].attributes.[attribute_name]
activerecord.errors.models.[model_name]
activerecord.errors.messages
+errors.attributes.[attribute_name]
+errors.messages
</ruby>
Thus, in our example it will try the following keys in this order and return the first result:
@@ -683,6 +696,8 @@ Thus, in our example it will try the following keys in this order and return the
activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
+errors.attributes.name.blank
+errors.messages.blank
</ruby>
When your models are additionally using inheritance then the messages are looked up in the inheritance chain.
@@ -691,18 +706,20 @@ For example, you might have an Admin model inheriting from User:
<ruby>
class Admin < User
- validates_presence_of :name
+ validates :name, :presence => true
end
</ruby>
Then Active Record will look for messages in this order:
<ruby>
-activerecord.errors.models.admin.attributes.title.blank
+activerecord.errors.models.admin.attributes.name.blank
activerecord.errors.models.admin.blank
-activerecord.errors.models.user.attributes.title.blank
+activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
+errors.attributes.name.blank
+errors.messages.blank
</ruby>
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.
@@ -716,27 +733,27 @@ So, for example, instead of the default error message +"can not be blank"+ you c
* +count+, where available, can be used for pluralization if present:
|_. validation |_.with option |_.message |_.interpolation|
-| validates_confirmation_of | - | :confirmation | -|
-| validates_acceptance_of | - | :accepted | -|
-| validates_presence_of | - | :blank | -|
-| validates_length_of | :within, :in | :too_short | count|
-| validates_length_of | :within, :in | :too_long | count|
-| validates_length_of | :is | :wrong_length | count|
-| validates_length_of | :minimum | :too_short | count|
-| validates_length_of | :maximum | :too_long | count|
-| validates_uniqueness_of | - | :taken | -|
-| validates_format_of | - | :invalid | -|
-| validates_inclusion_of | - | :inclusion | -|
-| validates_exclusion_of | - | :exclusion | -|
-| validates_associated | - | :invalid | -|
-| validates_numericality_of | - | :not_a_number | -|
-| validates_numericality_of | :greater_than | :greater_than | count|
-| validates_numericality_of | :greater_than_or_equal_to | :greater_than_or_equal_to | count|
-| validates_numericality_of | :equal_to | :equal_to | count|
-| validates_numericality_of | :less_than | :less_than | count|
-| validates_numericality_of | :less_than_or_equal_to | :less_than_or_equal_to | count|
-| validates_numericality_of | :odd | :odd | -|
-| validates_numericality_of | :even | :even | -|
+| 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 | -|
h5. Translations for the Active Record +error_messages_for+ Helper
@@ -761,23 +778,23 @@ Rails uses fixed strings and other localizations, such as format strings and oth
h5. Action View Helper Methods
-* +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations.
+* +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":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitely). All date selection helpers translate the prompt using the translations in the "datetime.prompts":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable.
+* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":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 prompt using the translations in the "datetime.prompts":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable.
-* The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+, and +number_to_human_size+ helpers use the number format settings located in the "number":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope.
+* 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.
h5. Active Record Methods
-* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
+* +model_name.human+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":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".
-* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +human_name+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
+* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +model_name.human+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
-*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +'&nbsp;'+).
+*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +'&nbsp;'+).
h5. Active Support Methods
-* +Array#to_sentence+ uses format settings as given in the "support.array":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope.
+* +Array#to_sentence+ uses format settings as given in the "support.array":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope.
h3. Customize your I18n Setup
@@ -792,6 +809,12 @@ That does not mean you're stuck with these limitations, though. The Ruby I18n ge
I18n.backend = Globalize::Backend::Static.new
</ruby>
+You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the ActiveRecord backend and fall back to the (default) Simple backend:
+
+<ruby>
+I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
+</ruby>
+
h4. Using Different Exception Handlers
The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
@@ -813,7 +836,7 @@ In other contexts you might want to change this behaviour, though. E.g. the defa
<ruby>
module I18n
- def just_raise_that_exception(*args)
+ def self.just_raise_that_exception(*args)
raise args.first
end
end
@@ -835,7 +858,7 @@ h3. Conclusion
At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
-If you find anything missing or wrong in this guide please file a ticket on "our issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions please sign up to our "mailinglist":http://groups.google.com/group/rails-i18n.
+If you find anything missing or wrong in this guide, please file a ticket on our "issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions, please sign up to our "mailing list":http://groups.google.com/group/rails-i18n.
h3. Contributing to Rails I18n
@@ -844,16 +867,16 @@ I18n support in Ruby on Rails was introduced in the release 2.2 and is still evo
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":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale repository for Ruby on Rails, please "_fork_":http://github.com/guides/fork-a-project-and-submit-your-modifications the repository, add your data and send a "pull request":http://github.com/guides/pull-requests.
+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.
h3. Resources
* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki.
-* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list.
-* "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases.
+* "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.
-* "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem.
* "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem.
@@ -862,7 +885,7 @@ h3. Authors
* "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author)
* "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k
-If you found this guide useful please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
+If you found this guide useful, please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
h3. Footnotes
@@ -872,8 +895,3 @@ fn1. Or, to quote "Wikipedia":http://en.wikipedia.org/wiki/Internationalization_
fn2. Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
fn3. 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 experiment with custom features and extensions.
-
-
-h3. Changelog
-
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/23
diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb
index a0db87c188..af46beee56 100644
--- a/railties/guides/source/index.html.erb
+++ b/railties/guides/source/index.html.erb
@@ -3,19 +3,23 @@ Ruby on Rails Guides
<% end %>
<% content_for :header_section do %>
-<h2>Ruby on Rails Guides</h2>
+<h2>Ruby on Rails Guides (<%= ENV['RAILS_VERSION'] || 'edge' %>)</h2>
<% if @edge %>
<p>
These are <b>Edge Guides</b>, based on the current
- <a href="http://github.com/rails/rails/tree/master">master branch</a>.
+ <a href="https://github.com/rails/rails/tree/master">master branch</a>.
</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. The guides for Rails 2.3 are still available
+ at <a href="http://guides.rubyonrails.org/v2.3.8/">http://guides.rubyonrails.org/v2.3.8/</a>.
+</p>
<% end %>
-
<p>
These guides are designed to make you immediately productive with Rails,
and to help you understand how all of the pieces fit together.
@@ -27,7 +31,7 @@ Ruby on Rails Guides
<div id="subCol">
<dl>
<dd class="warning">Rails Guides are a result of the ongoing <a href="http://hackfest.rubyonrails.org">Guides hackfest</a>, and a work in progress.</dd>
- <dd class="ticket">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections at the respective Lighthouse ticket.</dd>
+ <dd class="work-in-progress">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections to the author.</dd>
</dl>
</div>
<% end %>
@@ -67,7 +71,7 @@ Ruby on Rails Guides
<p>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.</p>
<% end %>
-<%= guide("Action View Form Helpers", 'form_helpers.html', :ticket => 1) do %>
+<%= guide("Action View Form Helpers", 'form_helpers.html', :work_in_progress => true) do %>
<p>Guide to using built-in Form helpers.</p>
<% end %>
</dl>
@@ -96,11 +100,11 @@ Ruby on Rails Guides
<p>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.</p>
<% end %>
-<%= guide("Action Mailer Basics", 'action_mailer_basics.html', :ticket => 25) do %>
+<%= guide("Action Mailer Basics", 'action_mailer_basics.html', :work_in_progress => true) do %>
<p>This guide describes how to use Action Mailer to send and receive emails.</p>
<% end %>
-<%= guide("Testing Rails Applications", 'testing.html', :ticket => 8) do %>
+<%= guide("Testing Rails Applications", 'testing.html', :work_in_progress => true) do %>
<p>This is a rather comprehensive guide to doing both unit and functional tests in Rails. It covers everything from &quot;What is a test?&quot; to the testing APIs. Enjoy.</p>
<% end %>
@@ -120,11 +124,11 @@ Ruby on Rails Guides
<p>This guide covers the basic configuration settings for a Rails application.</p>
<% end %>
-<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html', :ticket => 29) do %>
+<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html', :work_in_progress => true) do %>
<p>This guide covers the command line tools and rake tasks provided by Rails.</p>
<% end %>
-<%= guide("Caching with Rails", 'caching_with_rails.html', :ticket => 10) do %>
+<%= guide("Caching with Rails", 'caching_with_rails.html', :work_in_progress => true) do %>
<p>Various caching techniques provided by Rails.</p>
<% end %>
</dl>
@@ -132,7 +136,7 @@ Ruby on Rails Guides
<h3>Extending Rails</h3>
<dl>
- <%= guide("The Basics of Creating Rails Plugins", 'plugins.html', :ticket => 32) do %>
+ <%= guide("The Basics of Creating Rails Plugins", 'plugins.html', :work_in_progress => true) do %>
<p>This guide covers how to build a plugin to extend the functionality of Rails.</p>
<% end %>
@@ -140,23 +144,27 @@ Ruby on Rails Guides
<p>This guide covers Rails integration with Rack and interfacing with other Rack components.</p>
<% end %>
- <%= guide("Adding Generators", 'generators.html') do %>
+ <%= guide("Creating and Customizing Rails Generators", 'generators.html') do %>
<p>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).</p>
<% end %>
</dl>
-<h3>Contributing to Rails</h3>
+<h3>Contributing to Ruby on Rails</h3>
<dl>
- <%= guide("Contributing to Rails", 'contributing_to_rails.html') do %>
+ <%= guide("Contributing to Ruby on Rails", 'contributing_to_ruby_on_rails.html') do %>
<p>Rails is not &quot;somebody else's framework.&quot; This guide covers a variety of ways that you can get involved in the ongoing development of Rails.</p>
<% end %>
<%= guide('API Documentation Guidelines', 'api_documentation_guidelines.html') do %>
<p>This guide documents the Ruby on Rails API documentation guidelines.</p>
<% end %>
+
+ <%= guide('Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html') do %>
+ <p>This guide documents the Ruby on Rails guides guidelines.</p>
+ <% end %>
</dl>
<h3>Release Notes</h3>
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
index f80c00b280..0cbbe1f389 100644
--- a/railties/guides/source/initialization.textile
+++ b/railties/guides/source/initialization.textile
@@ -1,2012 +1,425 @@
h2. The Rails Initialization Process
-This guide explains how the initialization process in Rails works as of Rails 3.
+This guide explains the internals of the initialization process in Rails works as of Rails 3.1. It is an extremely in-depth guide and recommended for advanced Rails developers.
* Using +rails server+
* Using Passenger
endprologue.
-This guide first describes the process of +rails server+ then explains the Passenger + Rack method, before delving into the common initialize pattern these two go through.
+This guide goes through every single file, class and method call that is required to boot up the Ruby on Rails stack for a default Rails 3.1 application, explaining each part in detail a long the way. For this guide, we will be focusing on how the two most common methods (+rails server+ and Passenger) boot a Rails application.
+
+NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified.
h3. Launch!
As of Rails 3, +script/server+ has become +rails server+. This was done to centralize all rails related commands to one common file.
-The actual +rails+ command is kept in _railties/bin/rails_ and goes like this:
-
-<ruby>
- require 'rbconfig'
-
- module Rails
- module ScriptRailsLoader
- RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"]
- SCRIPT_RAILS = File.join('script', 'rails')
-
- def self.exec_script_rails!
- cwd = Dir.pwd
- exec RUBY, SCRIPT_RAILS, *ARGV if File.exists?(SCRIPT_RAILS)
- Dir.chdir("..") do
- # Recurse in a chdir block: if the search fails we want to be sure
- # the application is generated in the original working directory.
- exec_script_rails! unless cwd == Dir.pwd
- end
- rescue SystemCallError
- # could not chdir, no problem just return
- end
- end
- end
-
- Rails::ScriptRailsLoader.exec_script_rails!
-
- railties_path = File.expand_path('../../lib', __FILE__)
- $:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path)
+h4. +bin/rails+
- require 'rails/ruby_version_check'
- Signal.trap("INT") { puts; exit }
-
- require 'rails/commands/application'
-</ruby>
-
-The +Rails::ScriptRailsLoader+ module here defines two constants: +RUBY+ and +SCRIPT_RAILS+. +RUBY+ is the full path to your ruby executable, on a Snow Leopard system it's _/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby_. +SCRIPT_RAILS+ is simply _script/rails_. When +exec_script_rails+ is invoked, this will attempt to +exec+ the _rails_ file in the _script_ directory using the path to your Ruby executable, +RUBY+. If +exec+ is invoked, the program will stop at this point. If the _script/rails_ file doesn't exist in the current directory, Rails will recurse upwards until it finds it by calling +exec_script_rails+ from inside the +Dir.chdir("..")+. This is handy if you're currently in one of the sub-directories of the rails application and wish to launch a server or a console.
-
-If Rails cannot execute _script/rails_ then it will fall back to the standard +rails+ command task of generating an application.
-
-In +script/rails+ we see the following:
+The actual +rails+ command is kept in _bin/rails_ at the and goes like this:
<ruby>
#!/usr/bin/env ruby
- # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
-
- APP_PATH = File.expand_path('../../config/application', __FILE__)
- require File.expand_path('../../config/boot', __FILE__)
- require 'rails/commands'
-</ruby>
-This obviously defines a couple of constants to some pretty important files, _config/environment.rb_, _config/boot.rb_ and _config/application.rb_ all within the context of +__FILE__+ which is of course +script/rails+ in the root of your application. Then it goes on to +require BOOT_PATH+ which leads us onto _config/boot.rb_.
-
-h3. Passenger
-
-Before we dive into what _config/boot.rb_ encompasses, we'll just glimpse at what Passenger does enough to get an understanding of how it requires a Rails application.
-
-Passenger will require _config/environment.rb_ by way of its +PhusionPassenger::Railz::ApplicationSpawner#preload_application+ method. _config/environment.rb_ requires _config/application.rb_ which requires _config/boot.rb_. That's how the Rails boot process begins with Passenger in a nutshell.
-
-h3. _config/boot.rb_
-
-_config/boot.rb_ is the first stop for everything for initializing your application. This boot process does quite a bit of work for you and so this section attempts to go in-depth enough to explain what each of the pieces does.
-
-<ruby>
- require 'rubygems'
-
- # Set up gems listed in the Gemfile.
- gemfile = File.expand_path('../../Gemfile', __FILE__)
begin
- ENV['BUNDLE_GEMFILE'] = gemfile
- require 'bundler'
- Bundler.setup
- rescue Bundler::GemNotFound => e
- STDERR.puts e.message
- STDERR.puts "Try running `bundle install`."
- exit!
- end if File.exist?(gemfile)
-</ruby>
-
-h3. Bundled Rails (3.x)
-
-
-Rails 3 now uses Bundler and the README for the project explains it better than I could:
-
-> "Bundler is a tool that manages gem dependencies for your ruby application. It takes a gem manifest file and is able to fetch, download, and install the gems and all child dependencies specified in this manifest. It can manage any update to the gem manifest file and update the bundle's gems accordingly. It also lets you run any ruby code in context of the bundle's gem environment."
-
-Now with Rails 3 we have a Gemfile which defines the basics our application needs to get going:
-
-<ruby>
- source 'http://rubygems.org'
-
- gem 'rails', '3.0.0.beta4'
-
- # Bundle edge Rails instead:
- # gem 'rails', :git => 'git://github.com/rails/rails.git'
-
- gem 'sqlite3-ruby', :require => 'sqlite3'
-
- # Use unicorn as the web server
- # gem 'unicorn'
-
- # Deploy with Capistrano
- # gem 'capistrano'
-
- # Bundle the extra gems:
- # gem 'bj'
- # gem 'nokogiri'
- # gem 'sqlite3-ruby', :require => 'sqlite3'
- # gem 'aws-s3', :require => 'aws/s3'
-
- # Bundle gems for certain environments:
- # gem 'rspec', :group => :test
- # group :test do
- # gem 'webrat'
- # end
-
-</ruby>
-
-Here the only two gems we need are +rails+ and +sqlite3-ruby+, so it seems. This is until you run +bundle pack+. This command freezes all the gems required by your application into _vendor/cache_. The gems installed by default are:
-
-* abstract-1.0.0.gem
-* actionmailer-3.0.0.beta4.gem
-* actionpack-3.0.0.beta4.gem
-* activemodel-3.0.0.beta4.gem
-* activerecord-3.0.0.beta4.gem
-* activeresource-3.0.0.beta4.gem
-* activesupport-3.0.0.beta4.gem
-* arel-0.4.0.gem
-* builder-2.1.2.gem
-* bundler-1.0.0.rc.2.gem
-* erubis-2.6.6.gem
-* i18n-0.4.1.gem
-* mail-2.2.5.gem
-* memcache-client-1.8.5.gem
-* mime-types-1.16.gem
-* nokogiri-1.4.3.1.gem
-* polyglot-0.3.1.gem
-* rack-1.2.1.gem
-* rack-mount-0.6.9.gem
-* rack-test-0.5.4.gem
-* rails-3.0.0.beta4.gem
-* railties-3.0.0.beta4.gem
-* rake-0.8.7.gem
-* sqlite3-ruby-1.3.1.gem
-* text-format-1.0.0.gem
-* text-hyphen-1.0.0.gem
-* thor-0.13.7.gem
-* treetop-1.4.8.gem
-* tzinfo-0.3.22.gem
-
-TODO: Prettify when it becomes more stable.
-
-I won't go into what each of these gems are, as that is really something that needs covering on a case-by-case basis. We will however just dig a little under the surface of Bundler.
-
-Back in _config/boot.rb_, we call +Bundler.setup+ which will load and parse the +Gemfile+ and add the _lib_ directory of the gems mentioned **and** their dependencies (**and** their dependencies' dependencies, and so on) to the +$LOAD_PATH+.
-
-h3. Requiring Rails
-
-After _config/boot.rb_ is loaded, there's this +require+:
-
-<ruby>
- require 'rails/commands'
-</ruby>
-
-In this file, _railties/lib/rails/commands.rb_, there is a case statement for +ARGV.shift+:
-
-<ruby>
- case ARGV.shift
- ...
- when 's', 'server'
- require 'rails/commands/server'
- # Initialize the server first, so environment options are set
- server = Rails::Server.new
- require APP_PATH
- ...
- end
-</ruby>
-
-We're running +rails server+ and this means it will make a require out to _rails/commands/server_ (_railties/lib/rails/commands/server.rb_). Firstly, this file makes a couple of requires of its own:
-
-<ruby>
- require 'fileutils'
- require 'optparse'
- require 'action_dispatch'
-</ruby>
-
-The first two are Ruby core and this guide does not cover what they do, but _action_dispatch_ (_actionpack/lib/action_dispatch.rb_) is important. This file firstly make a require to _active_support_ (_activesupport/lib/active_support.rb_) which defines the +ActiveSupport+ module.
-
-h4. +require 'active_support'+
-
-_activesupport/lib/active_support.rb_ sets up +module ActiveSupport+:
-
-<ruby>
- module ActiveSupport
- class << self
- attr_accessor :load_all_hooks
- def on_load_all(&hook) load_all_hooks << hook end
- def load_all!; load_all_hooks.each { |hook| hook.call } end
- end
- self.load_all_hooks = []
-
- on_load_all do
- [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom]
- end
- end
-</ruby>
-
-This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this).
-
-The +on_load_all+ method is called later with the +Dependencies+, +Deprecation+, +Gzip+, +MessageVerifier+, +Multibyte+ and +SecureRandom+. What each of these modules do will be covered later.
-
-This file goes on to define some classes that will be automatically loaded using Ruby's +autoload+ method, but not before including Rails's own variant of the +autoload+ method from _active_support/dependencies/autoload.rb_:
-
-
-<ruby>
- require "active_support/inflector/methods"
- require "active_support/lazy_load_hooks"
-
- module ActiveSupport
- module Autoload
- def self.extended(base)
- base.extend(LazyLoadHooks)
- end
-
- @@autoloads = {}
- @@under_path = nil
- @@at_path = nil
- @@eager_autoload = false
-
- def autoload(const_name, path = @@at_path)
- full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
- location = path || Inflector.underscore(full)
-
- if @@eager_autoload
- @@autoloads[const_name] = location
- end
- super const_name, location
- end
-
- ...
- end
- end
-</ruby>
-
-h4. Lazy Hooks
-
-+ActiveSupport::LazyLoadHooks+ is responsible for defining methods used for running hooks that are defined during the initialization process, such as the one defined inside the +active_record.initialize_timezone+ initializer:
-
-<ruby>
- initializer "active_record.initialize_timezone" do
- ActiveSupport.on_load(:active_record) do
- self.time_zone_aware_attributes = true
- self.default_timezone = :utc
- end
- end
-</ruby>
-
-When the initializer runs it invokes method +on_load+ for +ActiveRecord+ and the block passed to it would be called only when +run_load_hooks+ is called.
-When the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated then +run_load_hooks+ is invoked. The very last line of +activerecord/lib/active_record/base.rb+ is:
-
-<ruby>
-ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-</ruby>
-
-h4. +require 'active_support'+ cont'd.
-
-This file also uses the method +eager_autoload+ also defined in _active_support/dependencies/autoload.rb_:
-
-<ruby>
- def eager_autoload
- old_eager, @@eager_autoload = @@eager_autoload, true
- yield
- ensure
- @@eager_autoload = old_eager
- end
-</ruby>
-
-As you can see for the duration of the +eager_autoload+ block the class variable +@@eager_autoload+ is set to +true+, which has the consequence of when +autoload+ is called that the location of the file for that specific +autoload+'d constant is added to the +@@autoloads+ hash initialized at the beginning of this module declaration. So now that you have part of the context, here's the other, the code from _activesupport/lib/active_support.rb_:
-
-<ruby>
- require "active_support/dependencies/autoload"
-
- module ActiveSupport
- extend ActiveSupport::Autoload
-
- autoload :DescendantsTracker
- autoload :FileUpdateChecker
- autoload :LogSubscriber
- autoload :Notifications
-
- # TODO: Narrow this list down
- eager_autoload do
- autoload :BacktraceCleaner
- autoload :Base64
- autoload :BasicObject
- autoload :Benchmarkable
- autoload :BufferedLogger
- autoload :Cache
- autoload :Callbacks
- autoload :Concern
- autoload :Configurable
- autoload :Deprecation
- autoload :Gzip
- autoload :Inflector
- autoload :JSON
- autoload :Memoizable
- autoload :MessageEncryptor
- autoload :MessageVerifier
- autoload :Multibyte
- autoload :OptionMerger
- autoload :OrderedHash
- autoload :OrderedOptions
- autoload :Rescuable
- autoload :SecureRandom
- autoload :StringInquirer
- autoload :XmlMini
- end
-
- autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
- autoload :TestCase
- end
-
- autoload :I18n, "active_support/i18n"
-</ruby>
-
-So we know the ones in +eager_autoload+ are eagerly loaded and it does this by storing them in an +@@autoloads+ hash object and then loading them via +eager_autoload!+ which is called via the +preload_frameworks+ initializer defined in _railties/lib/rails/application/bootstrap.rb_.
-
-The classes and modules that are not +eager_autoload+'d are automatically loaded as they are references
-
-Note: What does it means to be autoloaded? An example of this would be calling the +ActiveSupport::TestCase+ class which hasn't yet been initialized. Because it's been specified as an +autoload+ Ruby will require the file that it's told to. The file it requires is not defined in the +autoload+ call here but, as you may have seen, in the +ActiveSupport::Autoload.autoload+ definition. So once that file has been required Ruby will try again and then if it still can't find it it will throw the all-too-familiar +uninitialized constant+ error.
-
-h4. +require 'action_dispatch'+
-
-Back in _actionpack/lib/action_dispatch.rb_, the next require after _active_support_ is to _active_support/dependencies/autoload_ but this file has already been loaded by _activesupport/lib/active_support.rb_ and so will not be loaded again. The next require is to Rack itself:
-
-<ruby>
- require 'rack'
-</ruby>
-
-As mentioned previously, Bundler has added the gems' _lib_ directories to the load path so this _rack_ file that is referenced lives in the Rack gem: _lib/rack.rb_. This loads Rack so we can use it later on when we define +Rails::Server+ to descend from +Rack::Server+.
-
-This file then goes on to define the +ActionDispatch+ module and it's related autoloads:
-
-<ruby>
- module Rack
- autoload :Test, 'rack/test'
- end
-
- module ActionDispatch
- extend ActiveSupport::Autoload
-
- autoload_under 'http' do
- autoload :Request
- autoload :Response
- end
-
- autoload_under 'middleware' do
- autoload :Callbacks
- autoload :Cascade
- autoload :Cookies
- autoload :Flash
- autoload :Head
- autoload :ParamsParser
- autoload :RemoteIp
- autoload :Rescue
- autoload :ShowExceptions
- autoload :Static
- end
-
- autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
- autoload :Routing
-
- module Http
- extend ActiveSupport::Autoload
-
- autoload :Cache
- autoload :Headers
- autoload :MimeNegotiation
- autoload :Parameters
- autoload :FilterParameters
- autoload :Upload
- autoload :UploadedFile, 'action_dispatch/http/upload'
- autoload :URL
- end
-
- module Session
- autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
- autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
- autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
- end
-
- autoload_under 'testing' do
- autoload :Assertions
- autoload :Integration
- autoload :PerformanceTest
- autoload :TestProcess
- autoload :TestRequest
- autoload :TestResponse
- end
- end
-
- autoload :Mime, 'action_dispatch/http/mime_type'
-</ruby>
-
-h4. +require "rails/commands/server"+
-
-Now that Rails has required Action Dispatch and it has required Rack, Rails can now go about defining the +Rails::Server+ class:
-
-<ruby>
- module Rails
- class Server < ::Rack::Server
-
- ...
-
- def initialize(*)
- super
- set_environment
- end
-
- ...
-
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
- end
- ...
- end
- end
-</ruby>
-
-h4. +require "rails/commands"+
-
-Back in _rails/commands_ Rails calls +Rails::Server.new+ which calls the +initialize+ method on the +Rails::Server+ class, which calls +super+, meaning it's actually calling +Rack::Server#initialize+, with it being defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
- end
-</ruby>
-
-The +options+ method like this:
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
-
-The +parse_options+ method like this:
-
-<ruby>
- def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options
- end
-</ruby>
-
-And +default_options+ like this:
-
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
-
-Here it is important to note that the default environment is _development_. After +Rack::Server#initialize+ has done its thing it returns to +Rails::Server#initialize+ which calls +set_environment+:
-
-<ruby>
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
+ require "rails/cli"
+ rescue LoadError
+ railties_path = File.expand_path('../../railties/lib', __FILE__)
+ $:.unshift(railties_path)
+ require "rails/cli"
end
</ruby>
-From the information given we can determine that +ENV["RAILS_ENV"]+ will be set to _development_ if no other environment is specified.
-
-Finally, after +Rails::Server.new+ has executed, there is one more require:
-
-<ruby>
- require APP_PATH
-</ruby>
-
-+APP_PATH+ was previously defined as _config/application.rb_ in the application's root, and so that is where Rails will go next.
-
-h4. +require APP_PATH+
-
-This file is _config/application.rb_ in your application and makes two requires to begin with:
-
-<ruby>
- require File.expand_path('../boot', __FILE__)
- require 'rails/all'
-</ruby>
-
-The +../boot+ file it references is +config/boot.rb+, which was loaded earlier in the initialization process and so will not be loaded again.
-
-If you generate the application with the +-O+ option this will put a couple of pick-and-choose requirements at the top of your _config/application.rb_ instead:
-
-<ruby>
- # Pick the frameworks you want:
- # require "active_record/railtie"
- require "action_controller/railtie"
- require "action_mailer/railtie"
- require "active_resource/railtie"
- require "rails/test_unit/railtie"
-</ruby>
-
-For the purposes of this guide, will will assume only:
+This file will attempt to load +rails/cli+ and if it cannot find it then add the +railties/lib+ path to the load path (+$:+) and will then try to require it again.
-<ruby>
- require 'rails/all'
-</ruby>
-
-h4. +require "rails/all"+
-
-Now we'll dive into the internals of the pre-initialization stage of Rails. The file that is being required is _railties/lib/rails/all.rb_. The first line in this file is:
-
-<ruby>
- require 'rails'
-</ruby>
-
-h4. +require 'rails'+
+h4. +railites/lib/rails/cli.rb+
-This file (_railties/lib/rails.rb_) requires the very, very basics that Rails needs to get going. I'm not going to delve into these areas yet, just cover them briefly for now. Later on we will go through the ones that are important to the boot procedure.
+This file looks like this:
<ruby>
- require 'pathname'
+ require 'rbconfig'
+ require 'rails/script_rails_loader'
- require 'active_support'
- require 'active_support/core_ext/kernel/reporting'
- require 'active_support/core_ext/logger'
+ # If we are inside a Rails application this method performs an exec and thus
+ # the rest of this script is not run.
+ Rails::ScriptRailsLoader.exec_script_rails!
- require 'rails/application'
- require 'rails/version'
- require 'rails/deprecation'
- require 'rails/log_subscriber'
require 'rails/ruby_version_check'
+ Signal.trap("INT") { puts; exit }
- require 'active_support/railtie'
- require 'action_dispatch/railtie'
-</ruby>
-
-+require 'pathname'+ requires the Pathname class which is used for returning a Pathname object for +Rails.root+. Although is coming to use this path name to generate paths as below:
-
-<ruby>
- Rails.root.join("app/controllers")
-</ruby>
-
-Pathname can also be converted to string, so the following syntax is preferred:
-
-<ruby>
- "#{Rails.root}/app/controllers"
-</ruby>
-
-
-This works because Ruby automatically handles file path conversions. Although this is not new to Rails 3 (it was available in 2.3.5), it is something worthwhile pointing out.
-
-Inside this file there are other helpful helper methods defined, such as +Rails.root+, +Rails.env+, +Rails.logger+ and +Rails.application+.
-
-The first require:
-
-<ruby>
- require 'active_support'
-</ruby>
-
-Is not ran as this was already required by _actionpack/lib/action_dispatch.rb_.
-
-
-h4. +require 'active_support/core_ext/kernel/reporting'+
-
-This file extends the +Kernel+ module, providing the methods +silence_warnings+, +enable_warnings+, +with_warnings+, +silence_stderr+, +silence_stream+ and +suppress+. The API documentation on these overridden methods is fairly good and if you wish to know more "have a read.":http://api.rubyonrails.org/classes/Kernel.html
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'active_support/core_ext/logger'+
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'rails/application'+
-
-Here's where +Rails::Application+ is defined. This is the superclass of +YourApp::Application+ from _config/application.rb_ and the subclass of +Rails::Engine+ This is the main entry-point into the Rails initialization process as when your application is initialized, your class is the basis of its configuration.
-
-This file requires three important files before +Rails::Application+ is defined: _rails/railties_path.rb_, _rails/plugin.rb_ and _rails/engine.rb_.
-
-
-h4. +require 'rails/railties_path'+
-
-This file serves one purpose:
-
-<ruby>
- RAILTIES_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
-</ruby>
-
-Helpful, hey? One must wonder why they just didn't define it outright.
-
-
-h4. +require 'rails/plugin'+
-
-Firstly this file requires _rails/engine.rb_, which defines our +Rails::Engine+ class, explained in the very next section.
-
-This file defines a class called +Rails::Plugin+ which descends from +Rails::Engine+.
-
-This defines the first few initializers for the Rails stack:
-
-* load_init_rb
-* sanity_check_railties_collisons
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-TODO: Expand.
-
-h4. +require 'rails/engine'+
-
-This file requires _rails/railtie.rb_ which defines +Rails::Railtie+.
-
-+Rails::Engine+ defines a couple of further initializers for your application:
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-* add_routing_namespaces
-* add_locales
-* add_view_paths
-* add_generator_templates
-* load_application_initializers
-* load_application_classes
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-
-Also in here we see that a couple of methods are +delegate+'d:
-
-<ruby>
- delegate :middleware, :paths, :root, :to => :config
-</ruby>
-
-This means when you call either the +middleware+, +paths+ or +root+ methods you are in reality calling +config.middleware+, +config.paths+ and +config.root+ respectively.
-
-+Rails::Engine+ descends from +Rails::Railtie+.
-
-h4. +require 'rails/railtie'+
-
-+Rails::Railtie+ (_pronounced Rail-tie, as in a bowtie_), provides a method of classes to hook into Rails, providing them with methods to add generators, rake tasks and subscribers. All of the facets of Rails are their own Railtie. and as you've probably already figured out, the engines that you use are railties too. Plugins also can be railties, but they do not have to be.
-
-Here there's requires to _rails/initializable.rb_ and and _rails/configurable.rb_.
-
-h4. +require 'rails/initializable'+
-
-The +Rails::Initializable+ module includes methods helpful for the initialization process in rails, such as the method to define initializers: +initializer+. This is included into +Rails::Railtie+ so it's available there as well as +Rails::Engine+, +Rails::Application+ and +YourApp::Application+. In here we also see the class definition for +Rails::Initializer+, the class for all initializer objects.
-
-h4. +require 'rails/configuration'+
-
-The +Rails::Configuration+ module sets up shared configuration for applications, engines and plugins alike.
-
-At the top of this file there are three +require+s:
-
-<ruby>
- require 'active_support/ordered_options'
- require 'rails/paths'
- require 'rails/rack'
-</ruby>
-
-h4. +require 'active_support/ordered_options'+
-
-+ActiveSupport::OrderedOptions+ is a special-purpose +OrderedHash+, used for keeping track of the options specified in the configuration of your application.
-
-TODO: expand.
-
-h4. +require 'rails/paths'+
-
-This file is used to set up the +Rails::Paths+ module which is used to set up helpers for referencing paths to the folders of your Rails application, such as in _railties/lib/rails/engine/configuration.rb_ where it is used to firstly define them:
-
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.mailers "app/mailers", :eager_load => true
- paths.app.views "app/views", :eager_load => true
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths.public "public"
- paths.public.javascripts "public/javascripts"
- paths.public.stylesheets "public/stylesheets"
- paths
- end
- end
-</ruby>
-
-You can then get to these helper methods by calling +YourApp::Application.config.paths+.
-
-h4. +require 'rails/rack'+
-
-This file sets up some +autoload+'d constants for +Rails::Rack+:
-
-<ruby>
- module Rails
- module Rack
- autoload :Debugger, "rails/rack/debugger"
- autoload :Logger, "rails/rack/logger"
- autoload :LogTailer, "rails/rack/log_tailer"
- autoload :Static, "rails/rack/static"
- end
+ if ARGV.first == 'plugin'
+ ARGV.shift
+ require 'rails/commands/plugin_new'
+ else
+ require 'rails/commands/application'
end
</ruby>
-h4. +require 'rails/version'+
-
-Now we're back to _rails.rb_. The line after +require 'rails/application'+ in _rails.rb_ is:
+The +rbconfig+ file here is out of Ruby's standard library and provides us with the +RbConfig+ class which contains useful information dependent on how Ruby was compiled. We'll see this in use in +railties/lib/rails/script_rails_loader+.
<ruby>
- require 'rails/version'
-</ruby>
-
-The code in this file declares +Rails::VERSION+ so that the version number can easily be accessed. It stores it in constants, with the final version number being attainable by calling +Rails::VERSION::STRING+.
-
-h4. +require 'rails/deprecation'+
-
-This sets up a couple of familiar constants: +RAILS_ENV+, +RAILS_ROOT+ and +RAILS_DEFAULT_LOGGER+ to still be usable, but raise a deprecation warning when they are. Their alternatives are now +Rails.env+, +Rails.root+ and +Rails.logger+ respectively.
-
-If you wish to know more about how they're deprecated see the +require 'active_support/deprecation/proxy_wrappers'+ section. TODO: link to section.
-
-h4. +require 'rails/log_subscriber'+
-
-The +Rails::LogSubscriber+ provides a central location for logging in Rails 3 so as to not slow down the main thread. When you call one of the logging methods (+info+, +debug+, +warn+, +error+, +fatal+ or +unknown+) from the +Rails::LogSubscriber+ class or one of its subclasses this will notify the Rails logger to log this call in the fashion you specify, but will not write it to the file. The file writing is done at the end of the request, courtesy of the +Rails::Rack::Logger+ middleware.
-
-Each Railtie defines its own class that descends from +Rails::LogSubscriber+ with each defining its own methods for logging individual tasks.
-
-h4. +require 'rails/ruby_version_check'+
-
-This file ensures that you're running a minimum of 1.8.7. If you're running an older version, it will tell you:
-
-<pre>
- Rails requires Ruby version 1.8.7 or later.
- You're running [your Ruby version here]; please upgrade to continue.
-</pre>
-
-h4. +require 'activesupport/railtie'+
-
-This file declares two Railties, one for ActiveSupport and the other for I18n. In these Railties there's the following initializers defined:
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-* i18n.initialize
-
-This Railtie also defines an an +after_initialize+ block, which will (as the name implies) be ran after the initialization process. More on this later. TODO: When you write the section you can link to it.
-
-h4. +require 'action_dispatch/railtie'+
-
-This file is explained in the ActionDispatch Railtie Section. TODO: link
-
-h4. Return to _rails/all.rb_
-
-Now that we've covered the extensive process of what the first line does in this file, lets cover the remainder:
-
-<ruby>
- %w(
- active_record
- action_controller
- action_mailer
- active_resource
- rails/test_unit
- ).each do |framework|
- begin
- require "#{framework}/railtie"
- rescue LoadError
- end
- end
-</ruby>
-
-As you may be able to tell from the code, this is going through and loading all the Railties for Active Record, Action Controller, Action Mailer, Active Resource. Two other Railties, one for Active Support and one for Action Dispatch were required earlier, but are still covered in this section for continuity reasons. TODO: link.
-
-h4. ActiveSupport Railtie
-
-From Active Support's README:
-
-Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails.
-
-TODO: Quotify.
-
-h5. +require 'active_support/railtie'+
-
+require 'pathname'
-h4. Active Record Railtie
-
-The Active Record Railtie takes care of hooking Active Record into Rails. This depends on Active Support, Active Model and Arel. From Active Record's readme:
-
-TODO: Quotify.
-
-<plain>
- Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It's an implementation of the object-relational mapping (ORM) pattern by the same name as described by Martin Fowler:
-
- "An object that wraps a row in a database table or view, encapsulates
- the database access, and adds domain logic on that data."
-
- Active Record's main contribution to the pattern is to relieve the original of two stunting problems:
- lack of associations and inheritance. By adding a simple domain language-like set of macros to describe
- the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the
- gap of functionality between the data mapper and active record approach.
-</plain>
-
-h5. +require "active_record/railtie"+
-
-The _activerecord/lib/active_record/railtie.rb_ file defines the Railtie for Active Record.
-
-This file first requires Active Record, the _railties/lib/rails.rb_ file which has already been required and so will be ignored, and the Active Model Railtie:
-
-<ruby>
- require "active_record"
- require "rails"
- require "active_model/railtie"
-</ruby>
-
-Active Model's Railtie is covered in the next section. TODO: Section.
-
-h5. +require "active_record"+
-
-TODO: Why are +activesupport_path+ and +activemodel_path+ defined here?
-
-The first three requires require ActiveSupport, Active Model and ARel in that order:
-
-<ruby>
- require 'active_support'
- require 'active_model'
- require 'arel'
-</ruby>
-
-
-h5. +require "active_support"+
-
-This was loaded earlier by _railties/lib/rails.rb_. This line is here as a safeguard for when Active Record is loaded outside the scope of Rails.
-
-h5. +require "active_model"+
-
-TODO: Again with the +activesupport_path+!
-
-Here we see another +require "active_support"+ this is again, a safeguard for when Active Model is loaded outside the scope of Rails.
-
-This file defines a few +autoload+'d modules for Active Model, requires +active_support/i18n+ and adds the default translation file for Active Model to +I18n.load_path+.
-
-The +require 'active_support/i18n'+ just loads I18n and adds Active Support's default translations file to +I18n.load_path+ too:
-
-<ruby>
- require 'i18n'
- I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml
-</ruby>
-
-
-h5. +require "arel"+
-
-This file in _arel/lib/arel.rb_ loads a couple of Active Support things first:
-
-<ruby>
- require 'active_support/inflector'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-These files are explained in the "Common Includes" section.
-
-h5. +require 'arel'+
-
-Back in _arel/lib/arel.rb_, the next two lines require Active Record parts:
-
-<ruby>
- require 'active_record'
- require 'active_record/connection_adapters/abstract/quoting'
-</ruby>
-
-Because we're currently loading _active_record.rb_, it skips right over it.
-
-h5. +require 'active_record/connection_adapters/abstract/quoting'+
-
-_activerecord/lib/active_record/connection_adapters/abstract/quoting.rb_ defines methods used for quoting fields and table names in Active Record.
-
-TODO: Explain why this is loaded especially.
-
-h5. +require 'active_record'+
-
-Back the initial require from the _railtie.rb_.
-
-The _active_support_ and _active_model_ requires are again just an insurance for if we're loading Active Record outside of the scope of Rails. In _active_record.rb_ the ActiveRecord +Module+ is initialized and in it there is defined a couple of +autoloads+ and +eager_autoloads+.
-
-There's a new method here called +autoload_under+ which is defined in +ActiveSupport::Autoload+. This sets the autoload path to temporarily be the specified path, in this case +relation+ for the +autoload+'d classes inside the block.
-
-Inside this file the +AttributeMethods+, +Locking+ and +ConnectionAdapter+ modules are defined inside the +ActiveRecord+ module. The second to last line tells Arel what SQL engine we want to use. In this case it's +ActiveRecord::Base+. The final line adds in the translations for Active Record which are only for if a record is invalid or non-unique.
-
-h5. +require 'rails'+
-
-As mentioned previously this is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-h5. +require 'active_model/railtie'+
-
-This is covered in the Active Model Railtie section. TODO: link there.
-
-h5. +require 'action_controller/railtie'+
-
-This is covered in the Action Controller Railtie section. TODO: link there.
-
-h5. The Active Record Railtie
-
-Inside the Active Record Railtie the +ActiveRecord::Railtie+ class is defined:
-
-<ruby>
- module ActiveRecord
- class Railtie < Rails::Railtie
-
+module Rails
+ module ScriptRailsLoader
+ RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"]
+ SCRIPT_RAILS = File.join('script', 'rails')
...
- end
- end
-</ruby>
-
-TODO: Explain the logger.
-
-By doing this the +ActiveRecord::Railtie+ class gains access to the methods contained within +Rails::Railtie+ such as +rake_tasks+, +log_subscriber+ and +initiailizer+, all of which the Railtie is using in this case. The initializers defined here are:
-
-* active_record.initialize_timezone
-* active_record.logger
-* active_record.set_configs
-* active_record.initialize_database
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-As with the engine initializers, these are explained later.
-
-
-h4. Active Model Railtie
-
-This Railtie is +require+'d by Active Record's Railtie.
-
-From the Active Model readme:
-
-<plain>
- Prior to Rails 3.0, if a plugin or gem developer wanted to be able to have an object interact with Action Pack helpers, it was required to either copy chunks of code from Rails, or monkey patch entire helpers to make them handle objects that did not look like Active Record. This generated code duplication and fragile applications that broke on upgrades.
-
- Active Model is a solution for this problem.
-
- Active Model provides a known set of interfaces that your objects can implement to then present a common interface to the Action Pack helpers.
-</plain>
-
-
-h5. +require "active_model/railtie"+
-
-This Railtie file, _activemodel/lib/active_model/railtie.rb_ is quite small and only requires in +active_model+. As mentioned previously, the require to _rails_ is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-<ruby>
- require "active_model"
- require "rails"
-</ruby>
-
-h5. +require "active_model"+
-
-Active Model depends on Active Support and ensures it is required by making a +require 'active_support'+ call. It has already been loaded from _railties/lib/rails.rb_ so will not be reloaded for us here. The file goes on to define the +ActiveModel+ module and all of its autoloaded classes. This file also defines the english translations for some of the validation messages provided by Active Model, such as "is not included in the list" and "is reserved".
-
-h4. Action Controller Railtie
-
-The Action Controller Railtie takes care of all the behind-the-scenes code for your controllers; it puts the C into MVC; and does so by implementing the +ActionController::Base+ class which you may recall is where your +ApplicationController+ class descends from.
-
-h5. +require 'action_controller/railtie'+
-
-This first makes a couple of requires:
-
-<ruby>
- require "action_controller"
- require "rails"
- require "action_view/railtie"
-</ruby>
-
-The _action_controller_ file is explained in the very next section. The require to _rails_ is requiring the already-required _railties/lib/rails.rb_. If you wish to know about the require to _action_view/railtie_ this is explained in the Action View Railtie section.
-
-h5. +require 'action_controller+
-
-This file, _actionpack/lib/action_controller.rb_, defines the Action Controller module and its relative autoloads. Before it does any of that it makes two requires: one to _abstract_controller_, explored next, and the other to _action_dispatch_, explored directly after that.
-
-h5. +require 'abstract_controller'+
-
-+AbstractController+ provides the functionality of TODO.
-
-This file is in _actionpack/lib/abstract_controller.rb_ and begins by attempting to add the path to Active Support to the load path, which it would succeed in if it wasn't already set by anything loaded before it. In this case, it's not going to be set due to Arel already loading it in (TODO: right?).
-
-The next thing in this file four +require+ calls:
-
-<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/dependencies/autoload'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
-</ruby>
-
-After these require calls the +AbstractController+ module is defined with some standard +autoload+'d classes.
-
-
-h5. +require 'active_support/ruby/shim'+
-
-This file is explained in the "Common Includes" section beneath.
-
-h5. +require 'active_support/dependencies/autoload+
-
-This file was loaded upon the first require of +active_support+ and is not included. If you wish to be refreshed on what this file performs visit TODO: link to section.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Common Includes" section as it is required again later on. See the TODO: section. I also think this may be explained in the Active Support Core Extensions guide.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section as it has already been required by Arel at this point in the initialization process (see: section TODO: LINK!).
-
-h5. +require 'action_controller'+
-
-Back to _actionpack/lib/action_controller.rb_.
-
-After the initial call to +require 'abstract_controller'+, this calls +require 'action_dispatch'+ which was required earlier by _railties/lib/rails.rb_. The purpose of this file is explained in the ActionDispatch Railtie section.
-
-This file defines the +ActionController+ module and its autoloaded classes.
-
-Here we have a new method called +autoload_under+. This was covered in the Active Record Railtie but it is covered here also just in case you missed or skimmed over it. The +autoload_under+ method is defined in +ActiveSupport::Autoload+ and it sets the autoload path to temporarily be the specified path, in this case by specifying _metal_ it will load the specified +autoload+'d classes from _lib/action_controller/metal_ inside the block.
-
-Another new method we have here is called +autoload_at+:
-
-<ruby>
- autoload_at "action_controller/metal/exceptions" do
- autoload :ActionControllerError
- autoload :RenderError
- autoload :RoutingError
- autoload :MethodNotAllowed
- autoload :NotImplemented
- autoload :UnknownController
- autoload :MissingFile
- autoload :RenderError
- autoload :SessionOverflowError
- autoload :UnknownHttpMethod
- end
-</ruby>
-
-This defines the path of which to find these classes defined at and is most useful for if you have multiple classes defined in a single file, as is the case for this block; all of those classes are defined inside _action_controller/metal/exceptions.rb_ and when Active Support goes looking for them it will look in that file.
-
-At the end of this file there are a couple more requires:
-
-<ruby>
- # All of these simply register additional autoloads
- require 'action_view'
- require 'action_controller/vendor/html-scanner'
-
- # Common Active Support usage in ActionController
- require 'active_support/concern'
- require 'active_support/core_ext/class/attribute_accessors'
- require 'active_support/core_ext/load_error'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/name_error'
- require 'active_support/inflector'
-</ruby>
-
-h5. +require 'action_view'+
-
-This is best covered in the Action View Railtie section, so skip there by TODO: Link / page?
-
-h5. +require 'action_controller/vendor/html-scanner'+
-
-TODO: What is the purpose of this? Find out.
-
-h5. +require 'active_support/concern'+
-
-TODO: I can kind of understand the purpose of this.. need to see where @_dependencies is used however.
-
-h5. +require 'active_support/core_ext/class/attribute_accessors'+
-
-This file defines, as the path implies, attribute accessors for class. These are +cattr_reader+, +cattr_writer+, +cattr_accessor+.
-
-h5. +require 'active_support/core_ext/load_error'+
-
-The Active Support Core Extensions (TODO: LINK!) guide has a great coverage of what this file precisely provides.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Core Extension" guide.
-
-This file was required through the earlier _abstract_controller.rb_ require.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section.
-
-This file was required earlier by Arel and so is not required again.
-
-h5. +require 'active_support/core_ext/name_error'+
-
-This file includes extensions to the +NameError+ class, providing the +missing_name+ and +missing_name?+ methods. For more information see the Active Support Core Extensions guide.
-
-h5. +require 'active_support/inflector'+
-
-This file is explained in the "Common Includes" section.
-
-This file was earlier required by Arel and so is not required again.
-
-h5. Action Controller Railtie
-
-So now we come back to the Action Controller Railtie with a couple more requires to go before +ActionController::Railtie+ is defined:
-
-<ruby>
- require "action_view/railtie"
- require "active_support/core_ext/class/subclasses"
- require "active_support/deprecation/proxy_wrappers"
- require "active_support/deprecation"
-</ruby>
-
-As explained previously the +action_view/railtie+ file will be explained in the Action View Railtie section. TODO: link to it.
-
-h5. +require 'active_support/core_ext/class/subclasses'+
-
-For an explanation of this file _activesupport/lib/active_support/core_ext/class/subclasses_, see the Active Support Core Extension guide.
-
-h5. +require 'active_support/deprecation/proxy_wrappers'+
-
-This file, _activesupport/lib/active_support/deprecation/proxy_wrappers.rb_, defines a couple of deprecation classes, which are +DeprecationProxy+, +DeprecationObjectProxy+, +DeprecationInstanceVariableProxy+, +DeprecationConstantProxy+ which are all namespaced into +ActiveSupport::Deprecation+. These last three are all subclasses of +DeprecationProxy+.
-
-Why do we mention them here? Beside the obvious-by-now fact that we're covering just about everything about the initialization process in this guide, if you're deprecating something in your library and you use Active Support, you too can use the +DeprecationProxy+ class (and it's subclasses) too.
-
-
-h6. +DeprecationProxy+
-
-This class is used only in _railties/lib/rails/deprecation.rb_, loaded further on in the initialization process. It's used in this way:
-
-<ruby>
- RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
- cattr_accessor :warned
- self.warned = false
-
- def target
- Rails.root
- end
-
- def replace(*args)
- warn(caller, :replace, *args)
- end
-
- def warn(callstack, called, args)
- unless warned
- ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack)
- self.warned = true
- end
- end
- end).new
-</ruby>
-
-There is similar definitions for the other constants of +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+. All three of these constants are in the midst of being deprecated (most likely in Rails 3.1) so Rails will tell you if you reference them that they're deprecated using the +DeprecationProxy+ class. Whenever you call +RAILS_ROOT+ this will raise a warning, telling you: "RAILS_ROOT is deprecated! Use Rails.root instead".... TODO: investigate if simply calling it does raise this warning. This same rule applies to +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+, their new alternatives are +Rails.env+ and +Rails.logger+ respectively.
-
-h6. +DeprecatedObjectProxy+
-
-This is used in one place _actionpack/lib/action_controller/railtie.rb_, which you may remember is how we got to the +DeprecationProxy+ section:
-
-<ruby>
- ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
-</ruby>
-
-This makes more sense in the wider scope of the initializer:
-
-<ruby>
- initializer "action_controller.url_helpers" do |app|
- ActionController.base_hook do
- extend ::ActionController::Railtie::UrlHelpers.with(app.routes)
- end
- message = "ActionController::Routing::Routes is deprecated. " \
- "Instead, use Rails.application.routes"
-
- proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
- ActionController::Routing::Routes = proxy
end
+end
</ruby>
-+ActionController::Routing::Routes+ was the previous constant used in defining routes in Rails 2 applications, now it's simply a method on +Rails.application+ rather than it's own individual class: +Rails.application.routes+. Both of these still call the +draw+ method on the returned object to end up defining the routes.
-
-
-h6. +DeprecatedInstanceVariableProxy+
-
-This isn't actually used anywhere in Rails anymore. It was used previously for when +@request+ and +@params+ were deprecated in Rails 2. It has been kept around as it could be useful for the same purposes in libraries that use Active Support.
-
-h6. +DeprecatedConstantProxy+
-
-This method is used in a couple of places, _activesupport/lib/active_support/json/encoding.rb_ and _railties/lib/rails/rack.rb_.
-
-In _encoding.rb_ it's used to define a constant that's now been deprecated:
-
-<ruby>
- CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError)
-</ruby>
-
+The +rails/script_rails_loader+ file uses +RbConfig::Config+ to gather up the +bin_dir+ and +ruby_install_name+ values for the configuration which will result in a path such as +/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby+, which is the default path on Mac OS X. If you're running Windows the path may be something such as +C:/Ruby192/bin/ruby+. Anyway, the path on your system may be different, but the point of this is that it will point at the known ruby executable location for your install. The +RbConfig::CONFIG["EXEEXT"]+ will suffix this path with ".exe" if the script is running on Windows. This constant is used later on in +exec_script_rails!+. As for the +SCRIPT_RAILS+ console, we'll see that when we get to the +in_rails_application?+ method.
-Now when you reference +ActiveSupport::JSON::CircularReferenceError+ you'll receive a warning:
-
-<plain>
- ActiveSupport::JSON::CircularReferenceError is deprecated! Use Encoding::CircularReferenceError instead.
-</plain>
-
-h5. +require "active_support/deprecation"+
-
-This re-opens the +ActiveSupport::Deprecation+ module which was already defined by our deprecation proxies. Before this happens however we have 4 requires:
+Back in +rails/cli+, the next line is this:
<ruby>
- require 'active_support/deprecation/behaviors'
- require 'active_support/deprecation/reporting'
- require 'active_support/deprecation/method_wrappers'
- require 'active_support/deprecation/proxy_wrappers'
+ Rails::ScriptRailsLoader.exec_script_rails!
</ruby>
-The remainder of this file goes about setting up the +silenced+ and +debug+ accessors:
+This method is defined in +rails/script_rails_loader+ like this:
<ruby>
- module ActiveSupport
- module Deprecation #:nodoc:
- class << self
- # The version the deprecated behavior will be removed, by default.
- attr_accessor :deprecation_horizon
- end
- self.deprecation_horizon = '3.0'
-
- # By default, warnings are not silenced and debugging is off.
- self.silenced = false
- self.debug = false
+ def self.exec_script_rails!
+ cwd = Dir.pwd
+ return unless in_rails_application? || in_rails_application_subdirectory?
+ exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application?
+ Dir.chdir("..") do
+ # Recurse in a chdir block: if the search fails we want to be sure
+ # the application is generated in the original working directory.
+ exec_script_rails! unless cwd == Dir.pwd
end
+ rescue SystemCallError
+ # could not chdir, no problem just return
end
</ruby>
-h5. +require "active_support/deprecation/behaviors"+
-
-This sets up some default behavior for the warnings raised by +ActiveSupport::Deprecation+, defining different ones for _development_ and _test_ and nothing for production, as we never want deprecation warnings in production:
-
-<ruby>
- # Default warning behaviors per Rails.env. Ignored in production.
- DEFAULT_BEHAVIORS = {
- 'test' => Proc.new { |message, callstack|
- $stderr.puts(message)
- $stderr.puts callstack.join("\n ") if debug
- },
- 'development' => Proc.new { |message, callstack|
- logger =
- if defined?(Rails) && Rails.logger
- Rails.logger
- else
- require 'logger'
- Logger.new($stderr)
- end
- logger.warn message
- logger.debug callstack.join("\n ") if debug
- }
- }
-</ruby>
-
-In the _test_ environment, we will see the deprecation errors displayed in +$stderr+ and in _development_ mode, these are sent to +Rails.logger+ if it exists, otherwise it is output to +$stderr+ in a very similar fashion to the _test_ environment. These are both defined as procs, so Active Support can pass arguments to the +call+ method we call on it when Active Support +warn+.
-
-h5. +require 'active_support/deprecation/reporting'+
-
-This file defines further extensions to the +ActiveSupport::Deprecation+ module, including the +warn+ method which is used from Active Support's +DeprecationProxy+ class and an +attr_accessor+ on the class called +silenced+. This checks that we have a behavior defined, which we do in the _test_ and _development_ environments, and that we're not +silenced+ before warning about deprecations by +call+'ing the +Proc+ time.
-
-This file also defines a +silence+ method on the module also which you can pass a block to temporarily silence errors:
+This method will first check if the current working directory (+cwd+) is a Rails application or is a subdirectory of one. The way to determine this is defined in the +in_rails_application?+ method like this:
<ruby>
- ActiveSupport::Deprecation.silence do
- puts "YOU CAN FIND ME HERE: #{RAILS_ROOT}"
+ def self.in_rails_application?
+ File.exists?(SCRIPT_RAILS)
end
</ruby>
-TODO: may have to correct this example.
-
-h5. +require 'active_support/deprecation/method_wrappers'+
-
-This file defines a class method on +ActiveSupport::Deprecation+ called +deprecate_methods+. This method is used in _activesupport/lib/active_support/core_ext/module/deprecation.rb_ to allow you to declare deprecated methods on modules:
+The +SCRIPT_RAILS+ constant defined earlier is used here, with +File.exists?+ checking for its presence in the current directory. If this method returns +false+, then +in_rails_application_subdirectory?+ will be used:
<ruby>
- class Module
- # Declare that a method has been deprecated.
- # deprecate :foo
- # deprecate :bar => 'message'
- # deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!'
- def deprecate(*method_names)
- ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
- end
+ def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
+ File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent)
end
</ruby>
-h5. +require 'action_controller/railtie'+
-
-Inside +ActionController::Railtie+ there are another two requires:
+This climbs the directory tree until it reaches a path which contains a +script/rails+ file. If a directory is reached which contains this file then this line will run:
<ruby>
- require "action_controller/railties/log_subscriber"
- require "action_controller/railties/url_helpers"
+ exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application?
</ruby>
+This is effectively the same as doing +ruby script/rails [arguments]+. Where +[arguments]+ at this point in time is simply "server".
-h5. +require 'action_controller/railties/log_subscriber'+
-
-+ActionController::Railties::LogSubscriber+ inherits from +Rails::LogSubscriber+ and defines methods for logging such things as action processing and file sending.
-
-h5. +require 'action_controller/railties/url_helpers'+
-
-This file defines a +with+ method on +ActionController::Railtie::UrlHelpers+ which is later used in the +action_controller.url_helpers+ initializer. For more information see the +action_controller.url_helpers+ initializer section.
-
-h5. Action Controller Railtie
-
-After these requires it deprecates a couple of ex-Action Controller methods and points whomever references them to their ActionDispatch equivalents. These methods are +session+, +session=+, +session_store+ and +session_store=+.
-
-After the deprecations, Rails defines the +log_subscriber+ to be a new instance of +ActionController::Railties::LogSubscriber+ and then go about defining the following initializers, keeping in mind that these are added to the list of initializers defined before hand:
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-* action_controller.url_helpers
-
-h4. Action View Railtie
+h4. +script/rails+
-The Action View Railtie provides the backend code for your views and it puts the C into MVC. This implements the +ActionView::Base+ of which all views and partials are objects of.
-
-h5. +require 'action_view/railtie'+
-
-The Railtie is defined in a file called _actionpack/lib/action_view/railtie.rb_ and initially makes a call to +require 'action_view'+.
-
-h5. +require 'action_view'+
-
-Here again we have the addition of the path to Active Support to the load path attempted, but because it's already in the load path it will not be added. Similarly, we have two requires:
-
-<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-And these have already been required. If you wish to know what these files do go to the explanation of each in the "Common Includes" section. TODO: link to them!
-
-This file goes on to +require 'action_pack'+ which consists of all this code (comments stripped):
+This file looks like this:
<ruby>
- require 'action_pack/version'
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
+ require File.expand_path('../../config/boot', __FILE__)
+ require 'rails/commands'
</ruby>
-the _version_ file contains this code (comments stripped):
+The +APP_PATH+ constant here will be used later in +rails/commands+. The +config/boot+ file that +script/rails+ references is the +config/boot.rb+ file in our application which is responsible for loading Bundler and setting it up.
-<ruby>
- module ActionPack #:nodoc:
- module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 0
- TINY = "0.beta1"
-
- STRING = [MAJOR, MINOR, TINY].join('.')
- end
- end
-</ruby>
-
-TODO: Why?!
+h4. +config/boot.rb+
-This file goes on to define the +ActionView+ module and its +autoload+'d modules and then goes on to make two more requires:
++config/boot.rb+ contains this:
<ruby>
- require 'active_support/core_ext/string/output_safety'
- require 'action_view/base'
-</ruby>
-
-h5. +require 'active_support/core_ext/string/output_safety'+
-
-The _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ file is responsible for the code used in escaping HTML and JSON, namely the +html_escape+ and +json_escape+ methods. It does this by overriding these methods in +Erb::Util+ which is later included into +ActionView::Base+. This also defines +ActiveSupport::SafeBuffer+ which descends from +String+ and is used for concatenating safe output from your views to ERB templates.
-
-h5. +require 'action_view/base'+
-
-This file initially makes requires to the following files:
+ require 'rubygems'
-<ruby>
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute'
+ # Set up gems listed in the Gemfile.
+ gemfile = File.expand_path('../../Gemfile', __FILE__)
+ begin
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+ rescue Bundler::GemNotFound => e
+ STDERR.puts e.message
+ STDERR.puts "Try running `bundle install`."
+ exit!
+ end if File.exist?(gemfile)
</ruby>
-These are explained in their relevant areas inside the "Common Includes" section.
-
-The remainder of this file sets up the +ActionView+ module and the +ActionView::Base+ class which is the class of all view templates. Inside of +ActionView::Base+ it makes an include to several helper modules:
+In a standard Rails application, there's a +Gemfile+ which declares all dependencies of the application. +config/boot.rb+ sets +ENV["BUNDLE_GEMFILE"]+ to the location of this file, then requires Bundler and calls +Bundler.setup+ which adds the dependencies of the application (including all the Rails parts) to the load path, making them available for the application to load. The gems that a Rails 3.1 application depends on are as follows:
+
+* abstract (1.0.0)
+* actionmailer (3.1.0.beta)
+* actionpack (3.1.0.beta)
+* activemodel (3.1.0.beta)
+* activerecord (3.1.0.beta)
+* activeresource (3.1.0.beta)
+* activesupport (3.1.0.beta)
+* arel (2.0.7)
+* builder (3.0.0)
+* bundler (1.0.6)
+* erubis (2.6.6)
+* i18n (0.5.0)
+* mail (2.2.12)
+* mime-types (1.16)
+* polyglot (0.3.1)
+* rack (1.2.1)
+* rack-cache (0.5.3)
+* rack-mount (0.6.13)
+* rack-test (0.5.6)
+* rails (3.1.0.beta)
+* railties (3.1.0.beta)
+* rake (0.8.7)
+* sqlite3-ruby (1.3.2)
+* thor (0.14.6)
+* treetop (1.4.9)
+* tzinfo (0.3.23)
+
+h4. +rails/commands.rb+
+
+Once +config/boot.rb+ has finished, the next file that is required is +rails/commands+ which will execute a command based on the arguments passed in. In this case, the +ARGV+ array simply contains +server+ which is extracted into the +command+ variable using these lines:
+
+<ruby>
+ aliases = {
+ "g" => "generate",
+ "c" => "console",
+ "s" => "server",
+ "db" => "dbconsole"
+ }
-<ruby>
- include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context
+ command = ARGV.shift
+ command = aliases[command] || command
</ruby>
-h5. +ActionView::Helpers+
-
-This module, from _actionpack/lib/action_view/helpers.rb_, initially sets up the +autoload+'s for the various +ActionView::Helpers+ modules (TODO: mysteriously not using +autoload_under+). This also sets up a +ClassMethods+ module which is included automatically into wherever +ActionView::Helpers+ is included by defining a +self.included+ method:
+If we used <tt>s</tt> rather than +server+, Rails will use the +aliases+ defined in the file and match them to their respective commands. With the +server+ command, Rails will run this code:
<ruby>
- def self.included(base)
- base.extend(ClassMethods)
- end
-
- module ClassMethods
- include SanitizeHelper::ClassMethods
- end
-</ruby>
-
-Inside of +SanitizeHelper::ClassMethods+ it defines, of course, methods for assisting with sanitizing in Rails such as +link_sanitizer+ which is used by the +strip_links+ method.
+ when 'server'
+ # Change to the application's path if there is no config.ru file in current dir.
+ # This allows us to run script/rails server from other directories, but still get
+ # the main config.ru and properly set the tmp directory.
+ Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
-Afterwards this includes the +ActiveSupport::Benchmarkable+ which is used for benchmarking how long a specific thing takes in a view. The method is simply +benchmark+ and can be used like this:
-
-<ruby>
- benchmark("potentially long running thing") do
- Post.count
- end
+ require 'rails/commands/server'
+ Rails::Server.new.tap { |server|
+ # We need to require application after the server sets environment,
+ # otherwise the --environment option given to the server won't propagate.
+ require APP_PATH
+ Dir.chdir(Rails.application.root)
+ server.start
+ }
</ruby>
-The "documentation":http://api.rails.info/classes/ActiveSupport/Benchmarkable.html#M000607 is great about explaining what precisely this does. (TODO: replace link with real documentation link when it becomes available.)
-
-This module is also included into Active Record and +AbstractController+, meaning you can also use the +benchmark+ method in these methods.
+This file will change into the root of the directory (a path two directories back from +APP_PATH+ which points at +config/application.rb+), but only if the +config.ru+ file isn't found. This then requires +rails/commands/server+ which requires +action_dispatch+ and sets up the +Rails::Server+ class.
-After including +ActiveSupport::Benchmarkable+, the helpers which we have declared to be +autoload+'d are included. I will not go through and cover what each of these helpers do, as their names should be fairly explicit about it, and it's not really within the scope of this guide.
+h4. +actionpack/lib/action_dispatch.rb+
-h5. +ActionView::Rendering+
+Action Dispatch is the routing component of the Rails framework. It depends on Active Support, +actionpack/lib/action_pack.rb+ and +Rack+ being available. The first thing required here is +active_support+.
-This module, from _actionpack/lib/action_view/render/rendering.rb_ defines a method you may be a little too familiar with: +render+. This is the +render+ use for rendering all kinds of things, such as partials, templates and text.
+h4. +activesupport/lib/active_support.rb+
-h5. +ActionView::Partials+
+This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. The required file also requires another file: +active_support/lazy_load_hooks+
-This module, from _actionpack/lib/action_view/render/partials.rb_, defines +ActionView::Partials::PartialRenderer+ which you can probably guess is used for rendering partials.
+h4. +activesupport/lib/active_support/lazy_load_hooks.rb+
-h5. +ActionView::Layouts+
+This file defines the +ActiveSupport.on_load+ hook which is used to execute code when specific parts are loaded. We'll see this in use a little later on.
-This module, from _actionpack/lib/action_view/render/layouts.rb_, defines +ActionView::Layouts+ which defines methods such as +find_layout+ for locating layouts.
+This file begins with requiring +active_support/inflector/methods+.
-h5. +ERB::Util+
+h4. +activesupport/lib/active_support/inflector/methods.rb+
-The +ERB::Util+ module from Ruby core, as the document describes it: "A utility module for conversion routines, often handy in HTML generation". It offers two methods +html_escape+ and +url_encode+, with a third called +json_escape+ being added in by the requirement of _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ earlier. As explained earlier, +html_escape+ is overridden to return a string marked as safe.
-
-h5. +ActionView::Context+
-
-TODO: Not entirely sure what this is all about. Something about the context of view rendering... can't work it out.
-
-h5. Action View Railtie
-
-Now that _actionpack/lib/action_view.rb_ has been required, the next step is to +require 'rails'+, but this will be skipped as the file was required by _railties/lib/rails/all.rb_ way back in the beginnings of the initialization process.
-
-Next, the Railtie itself is defined:
+The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently.
+In this file there are a lot of lines such as this inside the +ActiveSupport+ module:
<ruby>
- module ActionView
- class Railtie < Rails::Railtie
- railtie_name :action_view
-
- require "action_view/railties/log_subscriber"
- log_subscriber ActionView::Railties::LogSubscriber.new
-
- initializer "action_view.cache_asset_timestamps" do |app|
- unless app.config.cache_classes
- ActionView.base_hook do
- ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
- end
- end
- end
- end
- end
-</ruby>
-
-The +ActionView::LogSubscriber+ sets up a method called +render_template+ which is called when a template is rendered. TODO: Templates only or partials and layouts also? I would imagine these fall under the templates category, but there needs to research to ensure this is correct.
-
-The sole initializer defined here, _action_view.cache_asset_timestamps_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate.
-
-h4. Action Mailer Railtie
-
-The Action Mailer Railtie is responsible for including all the emailing functionality into Rails by way of the Action Mailer gem itself. Action Mailer is:
-
-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.
-
-TODO: Quotify.
-
-h5. +require 'action_mailer/railtie'+
-
-This file first makes two requires:
-
-<ruby>
- require "action_mailer"
- require "rails"
-</ruby>
-
-The requires in +action_mailer+ are already loaded or are core extensions:
-
-<ruby>
- require 'abstract_controller'
- require 'action_view'
-
- # Common Active Support usage in Action Mailer
- require 'active_support/core_ext/class'
- require 'active_support/core_ext/object/blank'
- require 'active_support/core_ext/array/uniq_by'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/string/inflections'
- require 'active_support/lazy_load_hooks'
+ autoload :Inflector
</ruby>
-_abstract_controller_ is covered in the "Action Controller Railtie" section. TODO: Cover AbstractController there and link to it.
-_action_view_ was required by the Action View Railtie and will not be required again.
-
-For the core extensions you may reference the "Core Extensions" guide. TODO: Link to guide.
-
-_active_support/lazy_load_hooks_ was covered earlier in the guide and since it has already been required at this point in the initialization process, it will not be required again.
-
-The +require "rails"+ is referencing the _railties/lib/rails.rb_ file which was included back in TODO: link to section.
-
-_actionmailer/lib/action_mailer.rb_ then goes on to define the +ActionMailer+ module:
-
-<ruby>
- module ActionMailer
- extend ::ActiveSupport::Autoload
-
- autoload :AdvAttrAccessor
- autoload :Collector
- autoload :Base
- autoload :DeliveryMethods
- autoload :DeprecatedApi
- autoload :MailHelper
- autoload :OldApi
- autoload :Quoting
- autoload :TestCase
- autoload :TestHelper
- end
-</ruby>
-
-And a +Text+ module too:
-
-<ruby>
- module Text
- extend ActiveSupport::Autoload
-
- autoload :Format, 'text/format'
- end
-</ruby>
-
-which is used by the +ActionMailer::MailerHelper+ method +block_format+:
-
-<ruby>
- def block_format(text)
- formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
- }.join("\n")
-
- # Make list points stand on their own line
- formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
- formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
- formatted
- end
-</ruby>
+Due to the overriding of the +autoload+ method, Ruby will know to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced.
-h5. Action Mailer Railtie
+The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport.
-The Railtie defines the +log_subscriber+ as +ActionMailer::Railties::LogSubscriber.new+, with this class having two logging methods: one for delivery called +deliver+ and one for receipt called +receive+.
+The +active_support/lib/active_support.rb+ file simply defines the +ActiveSupport+ module and some autoloads (eager and of the normal variety) for it.
-The initializers defined in this Railtie are:
+h4. +actionpack/lib/action_dispatch.rb+ cont'd.
-* action_mailer.url_for
-* action_mailer.logger
-* action_mailer.set_configs
+Now back to +action_pack/lib/action_dispatch.rb+. The next +require+ in this file is one for +action_pack+, which simply calls +action_pack/version.rb+ which defines +ActionPack::VERSION+ and the constants, much like +ActiveSpport+ does.
-These are covered later on the Initialization section. TODO: first write then link to Initialization section.
+After this line, there's a require to +active_model+ which simply defines autoloads for the +ActiveModel+ part of Rails and sets up the +ActiveModel+ module which is used later on.
-h4. Active Resource Railtie
+The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it.
-The Active Resource Railtie is responsible for creating an interface into remote sites that offer a REST API. The Active Resource Railtie depends on Active Support and Active Model.
+Finally in +action_dispatch.rb+ the +ActionDispatch+ module and *its* autoloads are declared.
-h5. +require 'active_resource/railtie'+
+h4. +rails/commands/server.rb+
-This file defines the Active Resource Railtie:
+The +Rails::Server+ class is defined in this file as inheriting from +Rack::Server+. When +Rails::Server.new+ is called, this calls the +initialize+ method in +rails/commands/server.rb+:
<ruby>
- require "active_resource"
- require "rails"
-
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
-
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
-
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
+ def initialize(*)
+ super
+ set_environment
end
</ruby>
-The +require 'rails'+ has already been done back in TODO: link to section.
-
-h5. +require 'active_resource'+
+Firstly, +super+ is called which calls the +initialize+ method on +Rack::Server+.
-This file, _activeresource/lib/active_resource.rb_, defines the +ActiveResource+ module, first off this will add the path to Active Support and Active Model to the load path if it's not already there, then require both +active_support+ (_activesupport/lib/active_support.rb_) and +active_model+ (_activemodel/lib/active_model.rb_)
+h4. Rack: +lib/rack/server.rb+
-<ruby>
- activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
- $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
- activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
- $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
-
- require 'active_support'
- require 'active_model'
-
- module ActiveResource
- extend ActiveSupport::Autoload
-
- autoload :Base
- autoload :Connection
- autoload :CustomMethods
- autoload :Formats
- autoload :HttpMock
- autoload :Observing
- autoload :Schema
- autoload :Validations
- end
-</ruby>
++Rack::Server+ is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of.
-h5. Active Resource Railtie
-
-The Railtie itself is fairly short as Active Resource is the smallest component of Rails.
+The +initialize+ method in +Rack::Server+ simply sets a couple of variables:
<ruby>
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
-
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
-
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
+ def initialize(options = nil)
+ @options = options
+ @app = options[:app] if options && options[:app]
end
</ruby>
-The Railtie defines the +log_subscriber+ as +ActiveResource::Railties::LogSubscriber.new+ which has one method defined: +request+. +request+ is used whenever a request is made to an external service.
-
-There is only one initializer defined here: +set_configs+. This is covered later in the Initialization section.
-
-
-h4. ActionDispatch Railtie
-
-ActionDispatch handles all dispatch work for Rails. It interfaces with Action Controller to determine what action to undertake when a request comes in. TODO: I would quote the README but it is strangely absent. Flyin' blind here!
-
-The ActionDispatch Railtie was previously required when we called +require 'rails'+, but we will cover the Railtie here too.
+In this case, +options+ will be +nil+ so nothing happens in this method.
-ActionDispatch depends on Active Support.
-
-h5. +require 'action_dispatch/railtie'+
-
-This file defines the ActionDispatch Railtie:
+After +super+ has finished in +Rack::Server+, we jump back to +rails/commands/server.rb+. At this point, +set_environment+ is called within the context of the +Rails::Server+ object and this method doesn't appear to do much at first glance:
<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
+ def set_environment
+ ENV["RAILS_ENV"] ||= options[:environment]
end
</ruby>
-The +require 'rails'+ has already been done back in TODO: link to section.
-
-
-
-
-h5. +require 'action_dispatch'+
-
-This file was already loaded earlier in the initialization process. TODO: link to it.
-
-h5. ActionDispatch Railtie
-
-The ActionDispatch Railtie is almost as short as the Active Resource Railtie:
+In fact, the +options+ method here does quite a lot. This method is defined in +Rack::Server+ like this:
<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
+ def options
+ @options ||= parse_options(ARGV)
end
</ruby>
-The +config+ method here is from +Rails::Railtie+ and pertains to your application's configuration. In this case, it is setting up some defaults which you can later override in _config/application.rb_.
-
-This Railtie does not define a +log_subscriber+ and only defines one initializer: +prepare_dispatcher+.
-
-h3. Return to _config/application.rb_
-
-Now that Rails has finished loading all the Railties by way of +require 'rails/all'+ Rails can now move on to the next line:
-
-<ruby>
- Bundler.require :default, Rails.env
-</ruby>
-
-NOTE: It is worth mentioning here that you are not tied to using Bundler with Rails 3, but it is (of course) advised that you do. To "turn off" Bundler, comment out or remove the corresponding lines in _config/application.rb_ and _config/boot.rb_.
-
-Bundler was +require+'d back in _config/boot.rb_, and so that is what makes it available here. This guide does not dive into the internals of Bundler; it's really it's own separate guide.
-
-The +Bundler.require+ method adds all the gems not specified inside a +group+ in the +Gemfile+ and the ones specified in groups for the +Rails.env+ (in this case, _development_), to the load path. This is how an application is able to find them.
-
-The rest of this file is spent defining your application's main class. This is it without the comments:
+Then +parse_options+ is defined like this:
<ruby>
- module YourApp
- class Application < Rails::Application
- config.encoding = "utf-8"
- config.filter_parameters += [:password]
- end
- end
-</ruby>
-
-h3. Return to Rails
+ def parse_options(args)
+ options = default_options
-On the surface, this looks like a simple class inheritance. There's more underneath though. back in +Rails::Application+, the +inherited+ method is defined:
+ # Don't evaluate CGI ISINDEX parameters.
+ # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
+ args.clear if ENV.include?("REQUEST_METHOD")
-<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
+ options.merge! opt_parser.parse! args
+ options[:config] = ::File.expand_path(options[:config])
+ ENV["RACK_ENV"] = options[:environment]
+ options
end
</ruby>
-We do not already have a +Rails.application+, so instead this resorts to calling +super+. +Rails::Application+ descends from +Rails::Engine+ and so will call the +inherited+ method in +Rails::Engine+ (in _railties/lib/rails/engine.rb_), but before that it's important to note that +called_from+ is defined an +attr_accessor+ on +Rails::Engine+ and that +YourApp::Application+ is not an +abstract_railtie+:
+With the +default_options+ set to this:
<ruby>
- def inherited(base)
- unless base.abstract_railtie?
- base.called_from = begin
- # Remove the line number from backtraces making sure we don't leave anything behind
- call_stack = caller.map { |p| p.split(':')[0..-2].join(':') }
- File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] })
- end
- end
-
- super
+ def default_options
+ {
+ :environment => ENV['RACK_ENV'] || "development",
+ :pid => nil,
+ :Port => 9292,
+ :Host => "0.0.0.0",
+ :AccessLog => [],
+ :config => "config.ru"
+ }
end
</ruby>
-This +called_from+ setting looks a little overwhelming to begin with, but the short end of it is that it returns your application's root, something like: _/home/you/yourapp_. After +called_from+ has been set, +super+ is again called and this means the +Rails::Railtie#inherited+ method (in _railties/lib/rails/railtie.rb_):
-
-<ruby>
- def inherited(base)
- unless base.abstract_railtie?
- base.send(:include, self::Configurable)
- subclasses << base
- end
- end
-</ruby>
-
-Again, +YourApp::Application+ will return false for +abstract_railtie+ and so the code inside the +unless+ will be ran. The first line:
+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>
- base.send(:include, self::Configurable)
-</ruby>
-
-includes the +self::Configurable+ module, with self being +Rails::Application+ in this context:
-
-<ruby>
- module Rails
- class Application
- module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
-
- module ClassMethods
- def inherited(base)
- raise "You cannot inherit from a Rails::Application child"
- end
- end
-
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
- end
- end
+ def opt_parser
+ Options.new
end
</ruby>
-The inclusion of the +Rails::Application::Configurable+ module triggers the +included+ method in here which extends +YourApp::Application+ with the +Rails::Application::Configurable::ClassMethods+.
-
-Now that the chain of +super+ calls is done, we'll go back to the original +inherited+ method in +Rails::Application+ and the final line in this method:
+The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+ to take different arguments. Its +parse!+ method begins like this:
<ruby>
- Rails.application = base.instance
-</ruby>
+ def parse!(args)
+ args, options = args.dup, {}
-+base+ in this case is +YourApp::Application+ and calling +instance+ on this will return an instance of +YourApp::Application+ through the +instance+ method defined here:
-
-<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
+ opt_parser = OptionParser.new do |opts|
+ opts.banner = "Usage: rails server [mongrel, thin, etc] [options]"
+ opts.on("-p", "--port=port", Integer,
+ "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
+ ...
</ruby>
-+self+ in this case is +YourApp::Application+, so it won't match to +Rails::Application+ so instead the +new+ method is called which calls the +initialize+ method.
-
-
-
+This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server.
-h3. Firing it up!
+h4. +Rails::Server#start+
-Now that we've covered the boot process of Rails the next line best to cover would be what happens after _script/rails_ has loaded _config/boot.rb_. That's quite simply that it then +require 'rails/commands'+ which is located at _railties/lib/rails/commands.rb_. Remember how +exec+ passed the arguments to +script/rails+? This is where they're used. _rails/commands.rb_ is quite a large file in Rails 3, as it contains all the Rails commands like console, about, generate and, of course, server. Because we've called +rails server+ the first argument in +ARGV+ is of course +"server"+. So assuming this we can determine that the +ARGV.shift+ in _commands.rb_ is going to return +"server"+, therefore it'll match this +when+:
-
-<ruby>
- when 's', 'server'
- require 'rails/commands/server'
- Dir.chdir(ROOT_PATH)
- Rails::Server.start
-</ruby>
-
-The keen-eyed observer will note that this +when+ also specifies the argument could also be simply +'s'+ thereby making the full command +rails s+. This is the same with the other commands with +generate+ becoming +g+, +console+ becoming +c+ and +dbconsole+ becoming +db+.
-
-This code here ensures we are at the +ROOT_PATH+ of our application (this constant was defined in _script/rails_) and then calls +Rails::Server.start+. +Rails::Server+ descends from +Rack::Server+ which is defined in the rack gem. The +Rails::Server.start+ method is defined like this:
+This method is defined like this:
<ruby>
def start
- ENV["RAILS_ENV"] = options[:environment]
-
puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}"
puts "=> Call with -d to detach" unless options[:daemonize]
trap(:INT) { exit }
puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
+ #Create required tmp directories if not found
+ %w(cache pids sessions sockets).each do |dir_to_make|
+ FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make))
+ end
+
super
ensure
- puts 'Exiting' unless options[:daemonize]
+ # The '-h' option calls exit before @options is set.
+ # If we call 'options' with it unset, we get double help banners.
+ puts 'Exiting' unless @options && options[:daemonize]
end
</ruby>
-We can see here that there is usual output indicating that the server is booting up.
-
-How the +options+ variable gets set and how Rack starts the server up is covered in the next section.
-
-h3. Racking it up!
-
-
-This +Rack::Server.start+ method is defined like this:
-
-<ruby>
- def self.start
- new.start
- end
-</ruby>
-
-+new+ as you know calls +initialize+ in a class, and that is defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
- end
-</ruby>
-
-And then +options+, which are the options referenced by the +start+ method in +Rails::Server+.
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
-
-And +parse_options+:
-
-<ruby>
- def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options
- end
-</ruby>
-
-And +default_options+:
-
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
-
-Finally! We've arrived at +default_options+ which leads into our next point quite nicely. After the object has been +initialize+'d, +start+ is called:
+This is where the first output of the Rails initialization happens. This method creates a trap for +INT+ signals, so if you +CTRL+C+ the server, it will exit the process. As we can see from the code here, it will create the +tmp/cache+, +tmp/pids+, +tmp/sessions+ and +tmp/sockets+ directories if they don't already exist prior to calling +super+. The +super+ method will call +Rack::Server.start+ which begins its definition like this:
<ruby>
def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
-
if options[:warn]
$-w = true
end
if includes = options[:include]
- $LOAD_PATH.unshift *includes
+ $LOAD_PATH.unshift(*includes)
end
if library = options[:require]
require library
end
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
+ if options[:debug]
+ $DEBUG = true
+ require 'pp'
+ p options[:server]
+ pp wrapped_app
+ pp app
+ end
</ruby>
-We're not debugging anything, so there goes the first 7 lines, we're not warning, nor are we including, requiring, daemonising or writing out a pid file. That's everything except the final line, which calls +run+ with the +wrapped_app+ which is then defined like this:
+In a Rails application, these options are not set at all and therefore aren't used at all. The first line of code that's executed in this method is a call to this method:
<ruby>
- def wrapped_app
- @wrapped_app ||= build_app app
- end
+ wrapped_app
</ruby>
-and +build_app+'s first and only argument is +app+ which is defined like this:
+This method calls another method:
+<ruby>
+ @wrapped_app ||= build_app app
+</ruby>
+
+Then the +app+ method here is defined like so:
<ruby>
def app
@@ -2022,1744 +435,678 @@ and +build_app+'s first and only argument is +app+ which is defined like this:
end
</ruby>
-+options+ is a method we talked about a short while ago, which is just the set of default options. +options[:config]+ in this context is therefore _config.ru_ which coincidentally we have in our application! To get an application instance from this method +Rack::Builder+ joins the fray with a call to +parse_file+ on our _config.ru_:
-
-<ruby>
- def self.parse_file(config, opts = Server::Options.new)
- options = {}
- if config =~ /\.ru$/
- cfgfile = ::File.read(config)
- if cfgfile[/^#\\(.*)/] && opts
- options = opts.parse! $1.split(/\s+/)
- end
- cfgfile.sub!(/^__END__\n.*/, '')
- app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
- TOPLEVEL_BINDING, config
- else
- require config
- app = Object.const_get(::File.basename(config, '.rb').capitalize)
- end
- return app, options
- end
-</ruby>
-
-First this reads your config file and checks it for +#\+ at the beginning. This is supported if you want to pass options into the +Rack::Server+ instance that you have and can be used like this:
+The +options[:config]+ value defaults to +config.ru+ which contains this:
<ruby>
- #\\ -E production
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
- run YourApp::Application.instance
-
+ run YourApp::Application
</ruby>
-TODO: Is the above correct? I am simply guessing!
-
-After that it removes all the content after any +__END__+ in your _config.ru_ (TODO: because? Is this so it doesn't get eval'd?) and then evals the content of this file which, as you've seen is quite simple. The code that's first evaluated would be the require to the _config/environment.rb_ file, which leads into the next section.
-h3. _config/environment.rb_
-
-Now that we've seen that _rails/server_ gets to _config/environment.rb_ via Rack's requiring of it and Passenger requires it straight off the line. We've covered the boot process of Rails and covered the beginnings of a Rack server starting up. We have reached a common path for both _rails/server_ and Passenger now, so let's investigate what _config/environment.rb_ does.
+The +Rack::Builder.parse_file+ method here takes the content from this +config.ru+ file and parses it using this code:
<ruby>
- # Load the rails application
- require File.expand_path('../application', __FILE__)
-
- # Initialize the rails application
- YourApp::Application.initialize!
-
+ app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
+ TOPLEVEL_BINDING, config
</ruby>
-As you can see, there's a require in here for _config/application.rb_, and this file looks like this:
-
+The <ruby>initialize</ruby> method will take the block here and execute it within an instance of +Rack::Builder+. This is where the majority of the initialization process of Rails happens. The chain of events that this simple line sets off will be the focus of a large majority of this guide. The +require+ line for +config/environment.rb+ in +config.ru+ is the first to run:
<ruby>
- module YourApp
- class Application < Rails::Application
- # Settings in config/environments/* take precedence over those specified here.
- # Application configuration should go into files in config/initializers
- # -- all .rb files in that directory are automatically loaded.
-
- # Add additional load paths for your own custom dirs
- # config.load_paths += %W( #{config.root}/extras )
-
- # Only load the plugins named here, in the order given (default is alphabetical).
- # :all can be used as a placeholder for all plugins not explicitly named
- # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
- # Activate observers that should always be running
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-
- # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
- # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
- # config.time_zone = 'Central Time (US & Canada)'
-
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
- # config.i18n.default_locale = :de
-
- # Configure generators values. Many other options are available, be sure to check the documentation.
- # config.generators do |g|
- # g.orm :active_record
- # g.template_engine :erb
- # g.test_framework :test_unit, :fixture => true
- # end
- end
- end
-</ruby>
-
-These options (and their siblings) are explained in a later section. What's important to note for this file currently is that this is where the +YourApp::Application+ class is initialized and that it's a subclass of +Rails::Application+. This is the first point where your application begins to initialize Rails and as you can see all of this is configuration stuff which your initializers and really, the rest of your application will depend on. These options and what they do will be covered later.
-
-
-h3. Rails Initialization Process
-
-Now begins the actual initialization of Rails. Previously we have covered how _rails server_ and Passenger get to this stage and the parts of Rails that they have both loaded.
-
-h3. +Rails::Application+
-
-The first steps for the initialization process of Rails begins when +YourApp::Application+ descends from +Rails::Application+. The +Rails::Application+ class descends from +Rails::Engine+ class which itself descends from +Rails::Railtie+ defined in _railties/lib/rails/railtie.rb_. Along this fantastical chain of superclasses, there's defined a couple of inherited class methods. These methods just so happen to be called when a class inherits from (aka: is made a subclass of) this class. This first one is for +Rails::Application+:
-
-<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
- end
-</ruby>
-
-This goes up the chain by using +super+ to calling +Rails::Engine.inherited+:
-
-<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
- end
- end
-
- super
- end
+ require ::File.expand_path('../config/environment', __FILE__)
</ruby>
-+called_from+ references where this code was called from. This is covered later on in the "Bootstrap Initializers" section.
+h4. +config/environment.rb+
-Which then calls +Rails::Railtie.inherited+:
+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.
-<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.send(:include, self::Configurable)
- subclasses << base
- end
- end
-</ruby>
+This file begins with requiring +config/application.rb+.
-This +inherited+ first includes the +Rails::Configurable+ module on +base+, which is +YourApp::Application+. This module defines the +config+ method on +YourApp::Application+, and now it's starting to come together. You may notice that in your +config/application.rb+ file there's a +config+ method called there. This is the method from +Rails::Configurable+.
+h4. +config/application.rb+
-Then this adds to +Rails::Railtie.subclasses+ your application's class because... TODO: explain.
+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.
-With +Rails::Railtie.inherited+ out of the way, and that being the last thing to do in +Rails::Engine.inherited+ we return to +Rails::Application.inherited+ which calls the following:
+Then the fun begins!
-<ruby>
- Rails.application = base.instance
-</ruby>
+h3. Loading Rails
-As you already know, +base+ is +YourApp::Application+ and now it's calling the +instance+ method on it. This method is defined in +Rails::Application+ like this:
+The next line in +config/application.rb+ is:
<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
+ require 'rails/all'
</ruby>
-The +new+ method here simply creates a new +Rails::Application+ and sets it to the +@@instance+ class variable. No magic.
+h4 +railties/lib/rails/all.rb+
-h3. Your Application's Configuration
-Now that +inherited+ has finished doing its job, next up in _config/application.rb_ is the call to the +config+ object's methods. As explained before, this +config+ object is an instance of +Rails::Railtie::Configuration+, put into place by the call of +include Rails::Configurable+ back in +Rails::Railtie.inherited+. This defined it as such:
+This file is responsible for requiring all the individual parts of Rails like so:
<ruby>
- def config
- @config ||= Railtie::Configuration.new
- end
-</ruby>
-
-All the methods for +Rails::Railtie::Configuration+ are defined like this in _railties/lib/rails/railtie/configuration.rb_:
-
-<ruby>
- require 'rails/configuration'
+ require "rails"
- module Rails
- class Railtie
- class Configuration
- include Rails::Configuration::Shared
- end
+ %w(
+ active_record
+ action_controller
+ action_mailer
+ active_resource
+ rails/test_unit
+ ).each do |framework|
+ begin
+ require "#{framework}/railtie"
+ rescue LoadError
end
end
</ruby>
-As you can probably guess here, the +Rails::Configuration+ module is defined by _rails/configuration_ (_railties/lib/rails/configuration.rb_).
-
-h3. +Rails::Configuration::Shared+
+First off the line is the +rails+ require itself.
-In a standard application, the +application.rb+ looks like this with all the comments stripped out:
+h4. +railties/lib/rails.rb+
-<ruby>
- require File.expand_path('../boot', __FILE__)
+This file is responsible for the initial definition of the +Rails+ module and, rather than defining the autoloads like +ActiveSupport+, +ActionDispatch+ and so on, it actually defines other functionality. Such as the +root+, +env+ and +application+ methods which are extremely useful in Rails 3 applications.
- module YourApp
- class Application < Rails::Application
- config.filter_parameters << :password
- end
- end
-</ruby>
-
-The +config+ method being the one defined on +Rails::Application::Configurable+:
-
-<ruby>
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
-</ruby>
+However, before all that takes place the +rails/ruby_version_check+ file is required first.
-The method +find_with_root_flag+ is defined on +Rails::Engine+ (the superclass of +Rails::Application+) and it will find the directory containing a certain flag. In this case it's the +config.ru+ file:
+h4. +railties/lib/rails/ruby_version_check.rb+
-<ruby>
- def find_root_with_flag(flag, default=nil)
- root_path = self.called_from
+This file simply checks if the Ruby version is less than 1.8.7 or is 1.9.1 and raises an error if that is the case. Rails 3 simply will not run on earlier versions of Ruby than 1.8.7 or 1.9.1.
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
+NOTE: You should always endeavour to run the latest version of Ruby with your Rails applications. The benefits are many, including security fixes and the like, and very often there is a speed increase associated with it. The caveat is that you could have code that potentially breaks on the latest version, which should be fixed to work on the latest version rather than kept around as an excuse not to upgrade.
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
+h4. +active_support/core_ext/kernel/reporting.rb+
- RUBY_PLATFORM =~ /(:?mswin|mingw)/ ?
- Pathname.new(root).expand_path : Pathname.new(root).realpath
- end
-</ruby>
-
-+called_from+ goes through the +caller+ which is the stacktrace of the current thread, in the case of your application it would go a little like this:
-
-<pre>
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails/application.rb:30:in `inherited'
- /home/you/yourapp/config/application.rb:4:in `<module:TestApp>'
- /home/you/yourapp/config/application.rb:3:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails/commands.rb:33:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
- /var/www/rboard/script/rails:10:in `<main>'
-</pre>
-
-+called_from+ is defined in the +inherited+ method for +Rails::Engine+ which looks like this:
+This is the first of the many Active Support core extensions that come with Rails. This one in particular defines methods in the +Kernel+ module which is mixed in to the +Object+ class so the methods are available on +main+ and can therefore be called like this:
<ruby>
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
+ silence_warnings do
+ # some code
end
</ruby>
-The +call_stack+ here is the +caller+ output shown previously, minus everything after the first +:+ on all the lines. The first path that matches this is _/usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails_. Yours may vary slightly, but should always end in _railties-x.x.x/lib/rails_.
+These methods can be used to silence STDERR responses and the +silence_stream+ allows you to also silence other streams. Additionally, this mixin allows you to suppress exceptions and capture streams. For more information see the "Silencing Warnings, Streams, and Exceptions":http://guides.rubyonrails.org/active_support_core_extensions.html#silencing-warnings-streams-and-exceptions section from the Active Support Core Extensions Guide.
-The code in +find_root_with_flag+ will go up this directory structure until it reaches the top, which in this case is +/+.
+h4. +active_support/core_ext/logger.rb+
-<ruby>
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
+The next file that is required is another Active Support core extension, this time to the +Logger+ class. This begins by defining the +around_[level]+ helpers for the +Logger+ class as well as other methods such as a +datetime_format+ getter and setter for the +formatter+ object tied to a +Logger+ object.
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
-</ruby>
+For more information see the "Extensions to Logger":http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide.
-TODO: What is all this for?
+h4. +railties/lib/rails/application.rb+
-At the root of the system it looks for +config.ru+. TODO: Why? Obviously it's not going to find it, so it uses the +default+ option we've specified which is +Dir.pwd+ which will default to the root folder of your Rails application. This path is then passed to +Rails::Application::Configuration.new+. +Rails::Application::Configuration+ descends from +Rails::Engine::Configuration+ and the +initialize+ method goes like this:
+The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first.
-<ruby>
- def initialize(*)
- super
- @allow_concurrency = false
- @colorize_logging = true
- @filter_parameters = []
- @dependency_loading = true
- @serve_static_assets = true
- @time_zone = "UTC"
- @consider_all_requests_local = true
- end
-</ruby>
+The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#merging under the "Merging" section.
-The +super+ method here is the +initialize+ method in +Rails::Engine::Configuration+:
+h4. +active_support/file_update_checker.rb+
-<ruby>
- def initialize(root=nil)
- @root = root
- end
-</ruby>
+The +ActiveSupport::FileUpdateChecker+ class defined within this file is responsible for checking if a file has been updated since it was last checked. This is used for monitoring the routes file for changes during development environment runs.
-Here, the +@root+ variable is assigned the path of your application and then the remainder of +Rails::Application::Configuration.initialize+ is ran, setting up a few instance variables for basic configuration, including one for +@filter_parameters+.
+h4. +railties/lib/rails/plugin.rb+
-Now with the +config+ option set up, we can go onwards and call +filter_parameters+ on it. This +filter_parameters+ method is not defined on +Rails::Configuration::Shared+ and actually falls to the +method_missing+ defined there instead:
+This file defines +Rails::Plugin+ which inherits from +Rails::Engine+. Unlike +Rails::Engine+ and +Rails::Railtie+ however, this class is not designed to be inherited from. Instead, this is used simply for loading plugins from within an application and an engine.
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
- end
- super
- end
-</ruby>
+This file begins by requiring +rails/engine.rb+
-We're not calling +filter_parameters=+, we're calling +filter_parameters+, therefore it'll be the second part of this ternary argument: +options[$1]+. The options method is defined like this:
+h4. +railties/lib/rails/engine.rb+
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
+The +rails/engine.rb+ file defines the +Rails::Engine+ class which inherits from +Rails::Railtie+. The +Rails::Engine+ class defines much of the functionality found within a standard application class such as the +routes+ and +config+ methods.
-OrderedOptions exists... TODO: explain.
+The "API documentation":http://api.rubyonrails.org/classes/Rails/Engine.html for +Rails::Engine+ explains the function of this class pretty well.
+This file's first line requires +rails/railtie.rb+.
-So from this we can determine that our +options+ hash now has a key for +filter_parameters+ which's value is an array consisting of a single symbol: +:password+. How this option manages to get into the +@filter_parameters+ variable defined on the +Rails::Application::Configuration.initialize+ method is explained later.
+h4. +railties/lib/rails/railtie.rb+
-h3. Application Configured!
+The +rails/railtie.rb+ file is responsible for defining +Rails::Railtie+, the underlying class for all ties to Rails now. Gems that want to have their own initializers or rake tasks and hook into Rails should have a +GemName::Railtie+ class that inherits from +Rails::Railtie+.
-Now your application has finished being configured (at least in the sense of _config/application.rb_, there's more to come!) in _config/environment.rb_ the final line calls +YourApp::Application.initalize!+.
+The "API documentation":http://api.rubyonrails.org/classes/Rails/Railtie.html for +Rails::Railtie+, much like +Rails::Engine+, explains this class exceptionally well.
-h3. Initialization begins
+The first require in this file is +rails/initializable.rb+.
-This is one of those magical uses of +method_missing+ which, for the purposes of debugging, is something that you don't expect to come across as often as you do and as a consequence you'll spend a good portion of an hour looking for method definitions that don't exist because +method_missing+ is taking care of it. There's some pretty crafty use of +method_missing+ all over Rails and it's encouraged to take note of its power.
+h4. +railties/lib/rails/initializable.rb+
-+Rails::Application+ has a +method_missing+ definition which does this:
+Now we reach the end of this particular rabbit hole as +rails/initializable.rb+ doesn't require any more Rails files, only +tsort+ from the Ruby standard library.
-<ruby>
- def method_missing(*args, &block)
- instance.send(*args, &block)
- end
-</ruby>
+This file defines the +Rails::Initializable+ module which contains the +Initializer+ class, the basis for all initializers in Rails. This module also contains a +ClassMethods+ class which will be included into the +Rails::Railtie+ class when these requires have finished.
-With our +instance+ being our already initialized by the +inherited+ method, this will just return the value of the +@@instance+ variable, a +Rails::Application+ object. Calling +initialize!+ on this method does this:
+Now that +rails/initializable.rb+ has finished being required from +rails/railtie.rb+, the next require is for +rails/configuration+.
-<ruby>
- def initialize!
- run_initializers(self)
- self
- end
-</ruby>
+h4. +railties/lib/rails/configuration.rb+
-The initializers it is talking about running here are the initializers for our application. The object passed in to +run_initializers+ is +YourApp::Application+.
+This file defines the +Rails::Configuration+ module, containing the +MiddlewareStackProxy+ class as well as the +Generators+ class. The +MiddlewareStackProxy+ class is used for managing the middleware stack for an application, which we'll see later on. The +Generators+ class provides the functionality used for configuring what generators an application uses through the "+config.generators+ option":http://guides.rubyonrails.org/configuring.html#configuring-generators.
+The first file required in this file is +activesupport/deprecation+.
-h3. +run_initializers+
+h4. +activesupport/lib/active_support/deprecation.rb+
-This method begins the running of all the defined initializers. In the section "The Boot Process" we covered the loading sequence of Rails before any initialization happens and during this time we saw that the +Rails::Railtie+ class includes the +Initializable+ module. As we've also seen +YourApp::Application+ is a descendant of this class, so it too has these methods.
+This file, and the files it requires, define the basic deprecation warning features found in Rails. This file is responsible for setting defaults in the +ActiveSupport::Deprecation+ module for the +deprecation_horizon+, +silenced+ and +debug+ values. The files that are required before this happens are:
-+run_initializers+ looks like this:
+* +active_support/deprecation/behaviors+
+* +active_support/deprecation/reporting+
+* +active_support/deprecation/method_wrappers+
+* +active_support/deprecation/proxy_wrappers+
-<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
- end
- @ran = true
- end
-</ruby>
+h4. +activesupport/lib/active_support/deprecation/behaviors.rb+
-Here the +initializers+ method is defined in _railties/lib/rails/application.rb_:
+This file defines the behavior of the +ActiveSupport::Deprecation+ module, setting up the +DEFAULT_BEHAVIORS+ hash constant which contains the three defaults to outputting deprecation warnings: +:stderr+, +:log+ and +:notify+. This file begins by requiring +activesupport/notifications+ and +activesupport/core_ext/array/wrap+.
-<ruby>
- def initializers
- initializers = Bootstrap.initializers_for(self)
- railties.all { |r| initializers += r.initializers }
- initializers += super
- initializers += Finisher.initializers_for(self)
- initializers
- end
-</ruby>
-
-h3. +Bootstrap+ initializers
+h4 +activesupport/lib/active_support/notifications.rb+
-The first line here references a +Bootstrap+ class we haven't seen before. Or have we? The keen-eyed observer would have spotted an +autoload+ for it at the top of +Rails::Application+:
-
-<ruby>
- autoload :Bootstrap, 'rails/application/bootstrap'
-</ruby>
+TODO: document +ActiveSupport::Notifications+.
-Now that we've referenced that class, it will be required for us. You'll notice inside this class that there's an +include Initializable+, providing the afore-mentioned methods from this module. Inside this class a number of initializers are defined.
+h4. +activesupport/core_ext/array/wrap+
-* load_environment_config
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
+As this file comprises of a core extension, it is covered exclusively in "the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#wrapping
-These are all defined using the +initializer+ method:
-
-<ruby>
- def initializer(name, opts = {}, &blk)
- raise ArgumentError, "A block must be passed when defining an initializer" unless blk
- opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
- initializers << Initializer.new(name, nil, opts, &blk)
- end
-</ruby>
+h4. +activesupport/lib/active_support/deprecation/reporting.rb+
-The +initializers+ method defined here just references an +@initializers+ variable:
+This file is responsible for defining the +warn+ and +silence+ methods for +ActiveSupport::Deprecation+ as well as additional private methods for this module.
-<ruby>
- def initializers
- @initializers ||= []
- end
-</ruby>
+h4. +activesupport/lib/active_support/deprecation/method_wrappers.rb+
-As you can see from this method it will set +opts[:after]+ if there are previously defined initializers. So we can determine from this that the order our initializers are defined in is the same order that they run in, but only by default. It is possible to change this by specifying an +:after+ or +:before+ option as we will see later on. Each initializer is its own instance of the +Initializer+ class:
+This file defines a +deprecate_methods+ which is primarily used by the +module/deprecation+ core extension required by the first line of this file. Other core extensions required by this file are the +module/aliasing+ and +array/extract_options+ files.
-<ruby>
- class Initializer
- attr_reader :name, :block
+h4. +activesupport/lib/active_support/deprecation/proxy_wrappers.rb+
- def initialize(name, context, options, &block)
- @name, @context, @options, @block = name, context, options, block
- end
++proxy_wrappers.rb+ defines deprecation wrappers for methods, instance variables and constants. Previously, this was used for the +RAILS_ENV+ and +RAILS_ROOT+ constants for 3.0 but since then these constants have been removed. The deprecation message that would be raised from these would be something like:
- def before
- @options[:before]
- end
+<plain>
+ BadConstant is deprecated! Use GoodConstant instead.
+</plain>
- def after
- @options[:after]
- end
+h4. +active_support/ordered_options+
- def run(*args)
- @context.instance_exec(*args, &block)
- end
+This file is the next file required from +rails/configuration.rb+ is the file that defines +ActiveSupport::OrderedOptions+ which is used for configuration options such as +config.active_support+ and the like.
- def bind(context)
- return self if @context
- Initializer.new(@name, context, @options, &block)
- end
- end
-</ruby>
+The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#deep_dup
-Now that +Rails::Application::Bootstrap+ has finished loading, we can continue on with our initialization. We saw that it called this:
+The file that is required next from is +rails/paths+
-<ruby>
- initializers = Bootstrap.initializers_for(self)
-</ruby>
+h4. +railties/lib/rails/paths.rb+
-Calling +initializers_for+, defined like this:
+This file defines the +Rails::Paths+ module which allows paths to be configured for a Rails application or engine. Later on in this guide when we cover Rails configuration during the initialization process we'll see this used to set up some default paths for Rails and some of them will be configured to be eager loaded.
-<ruby>
- def initializers_for(binding)
- Collection.new(initializers_chain.map { |i| i.bind(binding) })
- end
-</ruby>
+h4. +railties/lib/rails/rack.rb+
-The +binding+ argument here is +YourApp::Application+ and this will return a new +Initializer+ object for all the initializers in +initializers_chain+ for this particular context. +initializers_chain+ goes like this:
+The final file to be loaded by +railties/lib/rails/configuration.rb+ is +rails/rack+ which defines some simple autoloads:
<ruby>
- def initializers_chain
- initializers = Collection.new
- ancestors.reverse_each do |klass|
- next unless klass.respond_to?(:initializers)
- initializers = initializers + klass.initializers
+ module Rails
+ module Rack
+ autoload :Debugger, "rails/rack/debugger"
+ autoload :Logger, "rails/rack/logger"
+ autoload :LogTailer, "rails/rack/log_tailer"
+ autoload :Static, "rails/rack/static"
end
- initializers
end
</ruby>
-The ancestors list is relatively short for +Rails::Application::Bootstrap+, consisting of itself and +Rails::Initializable+. Rails will go through these ancestors in reverse and check them all if they +respond_to?(:initializers)+. +Rails::Initializable+ does not and so it's skipped. +Rails::Application::Bootstrap+ of course does, and this is the list of initializers we covered earlier.
+Once this file is finished loading, then the +Rails::Configuration+ class is initialized. This completes the loading of +railties/lib/rails/configuration.rb+ and now we jump back to the loading of +railties/lib/rails/railtie.rb+, where the next file loaded is +active_support/inflector+.
-After +initializers_chain+ is finished, then they are +map+'d like this, with the +binding+ of course being +YourApp::Application+ as explained previously.
+h4. +activesupport/lib/active_support/inflector.rb+
-<ruby>
- def initializers_for(binding)
- Collection.new(initializers_chain.map { |i| i.bind(binding) })
- end
-</ruby>
-
-Wow. All that to cover just the first line in the +initializers+ method for +Rails::Application+.
-
-h3. Railties Initializers
-
-This section covers the loading of the initializers and we will go into depth for each initializer in the next section, as they make more sense explained in their chain.
-
-The second line in +Rails::Application#initializers+:
++active_support/inflector.rb+ requires a series of file which are responsible for setting up the basics for knowing how to pluralize and singularize words. These files are:
<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
- end
-</ruby>
-
-calls +railties+, which is defined like this:
+ require 'active_support/inflector/inflections'
+ require 'active_support/inflector/transliterate'
+ require 'active_support/inflector/methods'
-<ruby>
- def railties
- @railties ||= Railties.new(config)
- end
+ require 'active_support/inflections'
+ require 'active_support/core_ext/string/inflections'
</ruby>
-This sets up a new +Rails::Application::Railties+ object like this:
+The +active_support/inflector/methods+ file has already been required by +active_support/autoload+ and so won't be loaded again here.
-<ruby>
- def initialize(config)
- @config = config
- end
-</ruby>
+h4. +activesupport/lib/active_support/inflector/inflections.rb+
-And calls +all+ on it:
+This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes".
-<ruby>
- def all(&block)
- @all ||= railties + engines + plugins
- @all.each(&block) if block
- @all
- end
-</ruby>
+h4. +activesupport/lib/active_support/inflector/transliterate.rb+
-This +all+ method executes code on all the +Rails::Railtie+ and +Rails::Engine+ subclasses, retreived by the +railties+ and +engines+ methods defined right after +all+:
+In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading.
-<ruby>
- def railties
- @railties ||= ::Rails::Railtie.subclasses.map(&:new)
- end
+h4. Back to +railties/lib/rails/railtie.rb+
- def engines
- @engines ||= ::Rails::Engine.subclasses.map(&:new)
- end
-</ruby>
+Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods.
-By default, the railties are:
+h4. +railties/lib/rails/initializable.rb+
-* +ActiveSupport::Railtie+
-* +I18n::Railtie+
-* +ActionDispatch::Railtie+
-* +ActionController::Railtie+
-* +ActiveRecord::Railtie+
-* +ActionView::Railtie+
-* +ActionMailer::Railtie+
-* +ActiveResource::Railtie+
-* +Rails::TestUnitRailtie+
+When the module from this file (+Rails::Initializable+) is included, it extends the class it's included into with the +ClassMethods+ module inside of it. This module defines the +initializer+ method which is used to define initializers throughout all of the railties. This file completes the loading of +railties/lib/rails/railtie.rb+. Now we go back to +rails/engine.rb+.
-And these all descend from +Rails::Railtie+.
+h4. +railties/lib/rails/engine.rb+
-The default +engines+ are +[]+.
+The next file required in +rails/engine.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation.
-The +plugins+ method it calls is a little more complex:
+The next two files after this are Ruby standard library files: +pathname+ and +rbconfig+. The file after these is +rails/engine/railties+.
-<ruby>
- def plugins
- @plugins ||= begin
- plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
- Plugin.all(plugin_names, @config.paths.vendor.plugins)
- end
- end
-</ruby>
+h4. +railties/lib/rails/engine/railties.rb+
-+@config.paths+ is defined in the +Rails::Application::Configuration+ like this:
+This file defines the +Rails::Engine::Railties+ class which provides the +engines+ and +railties+ methods which are used later on for defining rake tasks and other functionality for engines and railties.
-<ruby>
- def paths
- @paths ||= begin
- paths = super
- paths.app.controllers << builtin_controller if builtin_controller
- paths.config.database "config/database.yml"
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
- paths.log "log/#{Rails.env}.log"
- paths.tmp "tmp"
- paths.tmp.cache "tmp/cache"
- paths.vendor "vendor", :load_path => true
- paths.vendor.plugins "vendor/plugins"
-
- if File.exists?("#{root}/test/mocks/#{Rails.env}")
- ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " <<
- "automatically to load paths anymore in future releases"
- paths.mocks_path "test/mocks", :load_path => true, :glob => Rails.env
- end
+h4. Back to +railties/lib/rails/engine.rb+
- paths
- end
- end
-</ruby>
+Once +rails/engine/railties.rb+ has finished loading the +Rails::Engine+ class gets its basic functionality defined, such as the +inherited+ method which will be called when this class is inherited from.
-When we call +@config.paths.vendor.plugins+ it will return +"vendor/plugins"+.
-
+Once this file has finished loading we jump back to +railties/lib/rails/plugin.rb+
-If you've defined specific plugin requirements for your application in _config/application.rb_ by using this code:
+h4. Back to +railties/lib/rails/plugin.rb+
-<ruby>
- config.plugins = [:will_paginate, :by_star]
-</ruby>
+The next file required in this is a core extension from Active Support called +array/conversions+ which is covered in "this section":http://guides.rubyonrails.org/active_support_core_extensions.html#array-conversions of the Active Support Core Extensions Guide.
-or specific plugin loading using a similar statement such as this next one:
+Once that file has finished loading, the +Rails::Plugin+ class is defined.
-<ruby>
- config.plugins = [:will_paginate, :by_star, :all]
-</ruby>
+h4. Back to +railties/lib/rails/application.rb+
+Jumping back to +rails/application.rb+ now. This file defines the +Rails::Application+ class where the application's class inherits from. This class (and its superclasses) define the basic behaviour on the application's constant such as the +config+ method used for configuring the application.
-Then this is where the +@config.plugins+ comes from. If you wish to load only certain plugins for your application, use the first example. If you wish to load certain plugins before the rest then the second example is what you would use.
+Once this file's done then we go back to the +railties/lib/rails.rb+ file, which next requires +rails/version+.
-If +config.plugins+ is not defined then +:all+ is specified in its place. Whatever the +plugin_names+ is specified as, is passed to +Plugin.all+ along with the path to the plugins, +@config.path.vendor.plugins+ (which defaults to _vendor/plugins_):
+h4. +railties/lib/rails/version.rb+
-<ruby>
- def self.all(list, paths)
- plugins = []
- paths.each do |path|
- Dir["#{path}/*"].each do |plugin_path|
- plugin = new(plugin_path)
- next unless list.include?(plugin.name) || list.include?(:all)
- plugins << plugin
- end
- end
+Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails.
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
- end
-</ruby>
+Once this file has finished loading we go back to +railties/lib/rails.rb+ which then requires +active_support/railtie.rb+.
-As we can see here it will go through the paths and for every folder in _vendor/plugins_ and +initialize+ a new +Rails::Plugin+ object for each:
+h4. +activesupport/lib/active_support/railtie.rb+
-<ruby>
- def initialize(root)
- @name = File.basename(root).to_sym
- config.root = root
- end
-</ruby>
+This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+.
-This sets the plugin name to be the same name as the folder so the plugin located at _vendor/plugins/by\_star_'s name is +by_star+. After that, the +config+ object is initialized:
+h4. +activesupport/lib/active_support/i18n_railtie.rb+
-<ruby>
- def config
- @config ||= Engine::Configuration.new
- end
-</ruby>
-
-and the root of the plugin defined as that folder. The reasoning for defining a +root+ is so that the initializer called +load_init_rb+ has some place to look for this file:
+This file is the first file that sets up configuration with these lines inside the class:
<ruby>
- initializer :load_init_rb, :before => :load_application_initializers do |app|
- file = Dir["#{root}/{rails/init,init}.rb"].first
- config = app.config
- eval(File.read(file), binding, file) if file && File.file?(file)
- end
+ class Railtie < Rails::Railtie
+ config.i18n = ActiveSupport::OrderedOptions.new
+ config.i18n.railties_load_path = []
+ config.i18n.load_path = []
+ config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
</ruby>
-A little more on that later, however.
-
-If the plugin is not included in the list then it moves on to the next one. For all plugins included in the list (or if +:all+ is specified in the list) they are put into a +plugins+ local variable which is then sorted:
+By inheriting from +Rails::Railtie+ the +Rails::Railtie#inherited+ method is called:
<ruby>
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
-</ruby>
-
-The sort order is the same order as which they appear in the +config.plugins+ setting, or in alphabetical order if there is no setting specified.
-
-Now that we have our railties, engines, and plugins in a line we can finally get back to the +all+ code:
-
-<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
- end
-</ruby>
-
-This block will gather add the railties' initializers to it.
-
-h3. Engine Initializers
-
-The third line in this +initializers+ method:
-
-<ruby>
- initializers += super
-</ruby>
-
-The +super+ method it's referring to is of course +Rails::Engine.initializers+, which isn't defined on the class but, as we have seen before, is defined on the +Rails::Railtie+ class it inherits from through the +Rails::Initializable+ module. Therefore we can determine the initializers to be added are now the ones defined in +Rails::Engine+.
-
-h3. Finisher Initializers
-
-The final set of initializers in this chain are those in +Rails::Finisher+. This involves running any after initialize code, building the middleware stack and adding the route for _rails/info/properties_.
-
-h3. Running the Initializers
-
-Now that we have all the initializers we can go back to the +run_initializers+ in +Rails::Initializable+:
-
-<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
+ def inherited(base)
+ unless base.abstract_railtie?
+ base.send(:include, Railtie::Configurable)
+ subclasses << base
end
- @ran = true
- end
-</ruby>
-
-Now we finally have all the +initializers+ we can go through them and call +run+:
-
-<ruby>
- def run(*args)
- @context.instance_exec(*args, &block)
end
</ruby>
-You may remember that the +@context+ in this code is +YourApp::Application+ and calling +instance_exec+ on this class will make a new instance of it and execute the code within the +&block+ passed to it. This code within the block is the code from all the initializers.
-
-h3. Bootstrap Initializers
-
-These initializers are the very first initializers that will be used to get your application going.
-
-h4. +load_environment_config+
+This first checks if the Railtie that's inheriting it is a component of Rails itself:
<ruby>
- initializer :load_environment_config do
- require_environment!
- end
-</ruby>
+ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
-This quite simply makes a call to +require_environment!+ which is defined like this in +Rails::Application+:
+...
-<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
-</ruby>
-
-We've seen +config.paths+ before when loading the plugins and they're explained in more detail in the Bonus section at the end of this guide. +config.enviroment+ for +paths+ is defined like this:
-
-<ruby>
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
-</ruby>
-
-+Rails.env+ was defined way back in the boot process when +railties/lib/rails.rb+ was required:
-
-<ruby>
-module Rails
- class << self
-
- ...
-
- def env
- @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
- end
-
- ...
-
- end
+def abstract_railtie?
+ ABSTRACT_RAILTIES.include?(name)
end
</ruby>
-With +ENV["RAILS_ENV"]+ and +ENV["RACK_ENV"]+ not set to anything for our server booting process, this will default to +"development"+.
-
-Therefore the path to this config file line would look like this with a substitution made:
-
-<ruby>
- paths.config.environment "config/environments", :glob => "development.rb"
-</ruby>
-
-This method returns a +Path+ object (which acts as an +Enumerable+).
-
-Back to +require_environment+ now:
+Because +I18n::Railtie+ isn't in this list, +abstract_railtie?+ returns +false+. Therefore the +Railtie::Configurable+ module is included into this class and the +subclasses+ method is called and +I18n::Railtie+ is added to this new array.
<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
+def subclasses
+ @subclasses ||= []
+end
</ruby>
-And we've determined that +config.paths.config.environment+ is +Path+ object, and calling +to_a+ on that object calls +paths+ because it's +alias+'d at the bottom of the +Path+ class definition:
-<ruby>
- alias to_a paths
-</ruby>
+The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this:
<ruby>
- def paths
- raise "You need to set a path root" unless @root.path
- result = @paths.map do |p|
- path = File.expand_path(p, @root.path)
- @glob ? Dir[File.join(path, @glob)] : path
- end
- result.flatten!
- result.uniq!
- result
+ def config
+ @config ||= Railtie::Configuration.new
end
</ruby>
-This returns an array of files according to our +path+ and +@glob+ which are +config/environments+ and +development.rb+ respectively, therefore we can determine that:
+At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. The line for this is this particular line in +railties/lib/rails/railtie.rb+:
<ruby>
- Dir[File.join(path, @glob)]
+ autoload :Configuration, "rails/railtie/configuration"
</ruby>
-will return an +Array+ containing one element, +"config/enviroments/development.rb"+. Of course when we call +first+ on this Array we'll get the first element and because that exists, we now +require "config/environments/development.rb"+.
-
-This file contains the following by default:
-
-<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
+h4. +railties/lib/rails/railtie/configuration.rb+
- # Show full error reports and disable caching
- config.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
-
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
- end
-</ruby>
+This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again.
-This +configure+ method is an +alias+ of +class_eval+ on +Rails::Application+:
-
-<ruby>
- alias :configure :class_eval
-</ruby>
-
-therefore, the code inside of the +configure+ is evaluated within the context of +YourApp::Application+.
-
-The +config+ object here is the same one that was set up when _config/application.rb_ was loaded, therefore the methods called in this object will fall to the +method_missing+ defined in +Rails::Configuration::Shared+:
+This file defines the +Rails::Railtie::Configuration+ class which is responsible for providing a way to easily configure railties and it's the +initialize+ method here which is called by the +config+ method back in the +i18n_railtie.rb+ file. The methods on this object don't exist, and so are rescued by the +method_missing+ defined further down in +configuration.rb+:
<ruby>
def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
+ if name.to_s =~ /=$/
+ @@options[$`.to_sym] = args.first
+ elsif @@options.key?(name)
+ @@options[name]
+ else
+ super
end
- super
end
</ruby>
-This time we are using methods ending in +\=+, so it will set the key in the +options+ to be the value specified. The first couple of options, +cache_classes+, +whiny_nils+, +consider_all_requests_local+ are just simple keys on the +options+. If you recall how options were setup then you may be able to work out how the remaining +action_view+, +action_controller+ and +action_mailer+ methods work.
-
-Firstly, we'll cover how +config_key_regexp+ is defined:
-
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
-
-And also +config_keys+:
-
-<ruby>
- def config_keys
- (Railtie.railtie_names + Engine.engine_names).map { |n| n.to_s }.uniq
- end
-</ruby>
-
-+config_keys+ in here returns:
-
-<ruby>
- [:active_support, :i18n, :action_dispatch, :action_view, :action_controller, :active_record, :action_mailer, :active_resource, :test_unit]
-</ruby>
-
-With all of those keys coming from +Railtie::railtie_names+. If you've elected to not load some of the frameworks here they won't be available as configuration keys, so you'll need to remove them too.
+So therefore when an option is referred to it simply stores the value as the key if it's used in a setter context, or retrieves it if used in a getter context. Nothing fancy going on there.
-Now a reminder of how the +options+ key is defined:
+h4. Back to +activesupport/lib/active_support/i18n_railtie.rb+
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
-
-The values for these framework keys are +ActiveSupport::OrderedOptions+ objects, with the class defined like this:
+After the configuration method the +reloader+ method is defined, and then the first of of Railties' initializers is defined: +i18n.callbacks+.
<ruby>
- module ActiveSupport #:nodoc:
- class OrderedOptions < OrderedHash
- def []=(key, value)
- super(key.to_sym, value)
- end
-
- def [](key)
- super(key.to_sym)
- end
-
- def method_missing(name, *args)
- if name.to_s =~ /(.*)=$/
- self[$1.to_sym] = args.first
- else
- self[name]
- end
- end
+ initializer "i18n.callbacks" do
+ ActionDispatch::Reloader.to_prepare do
+ I18n::Railtie.reloader.execute_if_updated
end
end
</ruby>
-We can determine when we call +config.action_view.debug_rjs+ it's falling back to the +method_missing+ defined on +ActiveSupport::OrderedOptions+, which ends up either setting or retrieving a key. In this case because we're using a setter, it will set the key for this hash. This completes the loading of _config/environments/development.rb_.
-
-h4. +load_all_active_support+
-
-This initializer does exactly what it says:
+The +initializer+ method (from the +Rails::Initializable+ module) here doesn't run the block, but rather stores it to be run later on:
<ruby>
- initializer :load_all_active_support do
- require "active_support/all" unless config.active_support.bare
+ def initializer(name, opts = {}, &blk)
+ raise ArgumentError, "A block must be passed when defining an initializer" unless blk
+ opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
+ initializers << Initializer.new(name, nil, opts, &blk)
end
</ruby>
-If you don't want this to happen you can specify the +config.active_support.bare+ option to +true+ in either _config/application.rb_ or any of your environment files.
-
-h4. +preload_frameworks+
-
-Remember earlier how we had all that stuff +eager_autoload+'d for Active Support?
+An initializer can be configured to run before or after another initializer, which we'll see a couple of times throughout this initialization process. Anything that inherits from +Rails::Railtie+ may also make use of the +initializer+ method, something which is covered in the "Configuration guide":[http://ryanbigg.com/guides/configuring.html#rails-railtie-initializer].
-<ruby>
- initializer :preload_frameworks do
- require 'active_support/dependencies'
- ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
- end
-</ruby>
-
-This is where it gets loaded. The +eager_autoload!+ method is defined like this:
+The +Initializer+ class here is defined within the +Rails::Initializable+ module and its +initialize+ method is defined to just set up a couple of variables:
<ruby>
- def self.eager_autoload!
- @@autoloads.values.each { |file| require file }
+ def initialize(name, context, options, &block)
+ @name, @context, @options, @block = name, context, options, block
end
</ruby>
-With +@@autoloads+ being
-
-
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
-
-h4. Active Support Initializers
-
-Active Support
-
-**Active Support Initializers**
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-**I18n Initializers**
-
-* i18n.initialize
-
-The +I18n::Railtie+ also defines an +after_initialize+ which we will return to later when discussing the initializers in detail.
-
-**Action Dispatch Initializers**
-
-* action_dispatch.prepare_dispatcher
-
-**Action Controller Initializers**
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-
-**Active Record Initializers**
-
-* active_record.initialize_time_zone
-* active_record.logger
-* active_record.set_configs
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-**Action View Initializers **
-
-* action_view.cache_asset_timestamps
-
-**Action Mailer Initializers **
-
-* action_mailer.logger
-* action_mailer.set_configs
-* action_mailer.url_for
-
-**Active Resource Initializers**
-
-* active_resource.set_configs
-
-**Rails::Engine Initializers**
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-
-
-h4. +Rails::Engine.new+
-
-The +new+ method doesn't exist, but in Ruby classes calling +new+ on the class instantiates a new instance of that class and calls the instance method +initialize+ on it. This method for +Rails::Application+ goes like this:
-
-<ruby>
- def initialize
- require_environment
- Rails.application ||= self
- @route_configuration_files = []
- end
-</ruby>
-
-h4. +Rails::Application#require_environment+
-
-This is not a crafty method like the previous ones, it just does as it says on the box:
+Once this +initialize+ method is finished, the object is added to the object the +initializers+ method returns:
<ruby>
- def require_environment
- require config.environment_path
- rescue LoadError
+ def initializers
+ @initializers ||= self.class.initializers_for(self)
end
</ruby>
-The +config+ object here is actually another +delegate+'d method (along with +routes+), this time to +self.class+:
-
-<ruby>
- delegate :config, :routes, :to => :'self.class'
-</ruby>
-
-So the method call is actually +self.class.config+.
-
-
-h4. +Rails::Application.config+
-
-Defined back inside the +class << self+ for +Rails::Application+, +config+ makes a new +Rails::Application::Configuration+ object and caches it in a variable called +@config+:
+If +@initializers+ isn't set (which it won't be at this point), the +intializers_for+ method will be called for this class.
<ruby>
- def config
- @config ||= Configuration.new(Plugin::Configuration.default)
+ def initializers_for(binding)
+ Collection.new(initializers_chain.map { |i| i.bind(binding) })
end
</ruby>
-h4. +Rails::Plugin::Configuration.default+
+The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +Array+ and includes the +TSort+ module which is used to sort out the order of the initializers based on the order they are placed in.
-The +Rails::Plugin::Configuration+ class may be a bit difficult to find at first, but if you look for _plugin.rb_ in Rails, you'll find it in _railties/lib/rails/plugin.rb_. In this file, we see the following:
+The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this:
-<ruby>
- module Rails
- class Plugin < Railtie
- ...
+<rub>
+ def initializers_chain
+ initializers = Collection.new
+ ancestors.reverse_each do | klass |
+ next unless klass.respond_to?(:initializers)
+ initializers = initializers + klass.initializers
end
+ initializers
end
</ruby>
-So we note here that +Rails::Plugin+ descends from +Rails::Railtie+ and secondly we note that the class +Configuration+ is not actually included in the +Plugin+ class, but it **is** in the +Railtie+ class!
-
-h4. +Rails::Railtie::Configuration+
-
-We've now tracked down the +Plugin::Configuration.default+ method to being +Railtie::Configuration.default+, which is defined like this in _railties/lib/rails/configuration.rb_:
+This method collects the initializers from the ancestors of this class and adds them to a new +Collection+ object using the <tt>+</tt> method which is defined like this for the <tt>Collection</tt> class:
<ruby>
- class Railtie::Configuration
- def self.default
- @default ||= new
- end
- ...
+ def +(other)
+ Collection.new(to_a + other.to_a)
end
</ruby>
-In this case we have effectively seen that it's doing Configuration.new(Configuration.new). I'll explain why.
-
-h4. +Rails::Application::Configuration.new+
+So this <tt>+</tt> method is overriden to return a new collection comprising of the existing collection as an array and then using the <tt>Array#+</tt> method combines these two collections, returning a "super" +Collection+ object. In this case, the only initializer that's going to be in this new +Collection+ object is the +i18n.callbacks+ initializer.
-TODO: CLEAN THIS UP! This subclassing is only temporary and will probably not be separate in Rails 3. This is based solely off what the comment at the top of the Railtie::Configuration class says!
-
-The first thing to note here is that this class is subclassed from +Railtie::Configuration+ and therefore the method here is actually +Railtie::Configuration.new+. As mentioned previously, calling +new+ will make a new object of this class and then call +initialize+ on it, which is defined like this:
+The next method to be called after this +initializer+ method is the +after_initialize+ method on the +config+ object, which is defined like this:
<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
- else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
- end
+ def after_initialize(&block)
+ ActiveSupport.on_load(:after_initialize, :yield => true, &block)
end
</ruby>
-This method is not called with a +base+ argument for +Plugin::Configuration.default+ but it is for the +Configuration.new+ wrapped around it. We'll go for the internal one first, since that's the order Rails loads them in.
-
-h4. +default_middleware_stack+
-
-This method is defined like this:
+The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ file which was required earlier and is defined like this:
<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency })
- middleware.use('::Rack::Runtime')
- middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local })
- middleware.use('ActionDispatch::Notifications')
- middleware.use('ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes })
- middleware.use('ActionDispatch::Cookies')
- middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
- middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store })
- middleware.use('ActionDispatch::ParamsParser')
- middleware.use('::Rack::MethodOverride')
- middleware.use('::ActionDispatch::Head')
+ def self.on_load(name, options = {}, &block)
+ if base = @loaded[name]
+ execute_hook(base, options, block)
+ else
+ @load_hooks[name] << [block, options]
end
end
</ruby>
-To really understand this method we need to dig a little deeper, down into where +ActionDispatch::MiddlewareStack.new+ is defined and what in particular it does for us.
-
-h4. +ActionDispatch::MiddlewareStack.new+
-
-+ActionDispatch+ is our first foray outside of the +railties+ gem, as this is actually defined in the +actionpack+ part of Rails. The class definition is as important as the method:
+The +@loaded+ variable here is a hash containing elements representing the different components of Rails that have been loaded at this stage. Currently, this hash is empty. So the +else+ is executed here, using the +@load_hooks+ variable defined in +active_support/lazy_load_hooks+:
<ruby>
- module ActionDispatch
- class MiddlewareStack < Array
-
- ...
-
- def initialize(*args, &block)
- super(*args)
- block.call(self) if block_given?
- end
- end
- end
+ @load_hooks = Hash.new {|h,k| h[k] = [] }
</ruby>
-When it's calling +super+ here it's actually calling +initialize+ on the Array class and from this we can determine that an +ActionDispatch::MiddlewareStack+ object is just an +Array+ object with special powers. One of those special powers is the ability to take a block, and +call+ it with +self+, meaning the block's parameter is the object itself!
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Previously we saw a chunk of code that I'll re-show you stripped down:
+This defines a new hash which has keys that default to empty arrays. This saves Rails from having to do something like this instead:
<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- ...
- end
- end
+ @load_hooks[name] = []
+ @load_hooks[name] << [block, options]
</ruby>
-As explained in the previous section, we know that the +new+ on +ActionDispatch::MiddlewareStack+ takes a block and that block has one parameter which is the object itself. On this object we call the +use+ method to include middleware into our application. The use method simply does this:
+The value added to this array here consists of the block and options passed to +after_initialize+.
-<ruby>
- def use(*args, &block)
- middleware = Middleware.new(*args, &block)
- push(middleware)
- end
-</ruby>
+We'll see these +@load_hooks+ used later on in the initialization process.
-We'll come back to this method later on.
+This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+.
-h4. +ActionController::Middleware.new+
+h4. Back to +activesupport/lib/active_support/railtie.rb+
-This +initialize+ method also is in a class who's ancestry is important so once again I'll show the ancestry and we'll go up that particular chain:
+This file defines the +ActiveSupport::Railtie+ constant which like the +I18n::Railtie+ constant just defined, inherits from +Rails::Railtie+ meaning the +inherited+ method would be called again here, including +Rails::Configurable+ into this class. This class makes use of +Rails::Railtie+'s +config+ method again, setting up the configuration options for Active Support.
-<ruby>
- module ActionController
- class Middleware < Metal
-
- ...
-
- def initialize(app)
- super()
- @_app = app
- end
- end
- end
-</ruby>
+Then this Railtie sets up three more initializers:
-Here our method calls +super+ but with a difference: it's passing in no arguments intentionally by putting the two brackets at the end. The method called here is therefore +ActionController::Metal.initialize+.
+* +active_support.initialize_whiny_nils+
+* +active_support.deprecation_behavior+
+* +active_support.initialize_time_zone+
-h4. +ActionController::Metal.initialize+
+We will cover what each of these initializers do when they run.
-This is another subclassed class, this time from +ActionController::AbstractController+ and I'm sure you can guess what that means:
+Once the +active_support/railtie+ file has finished loading the next file required from +railties/lib/rails.rb+ is the +action_dispatch/railtie+.
-<ruby>
- class Metal < AbstractController::Base
-
- ...
-
- def initialize(*)
- @_headers = {}
- super
- end
- end
-</ruby>
+h4. +activesupport/lib/action_dispatch/railtie.rb+
-The single +*+ in the argument listing means we can accept any number of arguments, we just don't care what they are.
+This file defines the +ActionDispatch::Railtie+ class, but not before requiring +action_dispatch+.
-h4. +AbstractController::Base.initialize+
+h4. +activesupport/lib/action_dispatch.rb+
-This may be anti-climatic, but the initialize method here just returns an +AbstractController::Base+ object:
+This file attempts to locate the +active_support+ and +active_model+ libraries by looking a couple of directories back from the current file and then adds the +active_support+ and +active_model+ +lib+ directories to the load path, but only if they aren't already, which they are.
<ruby>
- # Initialize controller with nil formats.
- def initialize #:nodoc:
- @_formats = nil
- end
-</ruby>
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Now we're back to this method, from our foray into the depths of how +Middleware.new+ works, we've showed that it is an instance of +AbstractController::Base+. Therefore it does
-
-TODO: ELABORATE ON THIS SECTION, including explaining what all the pieces of middleware do. Then explain how the default_middleware_stack does what it does, whatever that is.
-
-h4. Back to +Rails::Application::Configuration.new+
-
-Now that the first call to this method is complete (+Plugin::Configuration.default+), we can move onto the second call. Here's a refresher of what this method does:
+ activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
+ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
- else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
- end
- end
+ activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
+ $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
</ruby>
-You'll note now that this method is being called now is +Configuration.new(Plugin::Configuration.default)+ and with the argument, it's going to perform differently than before, this time duplicating the +options+ and +middleware+ of the object it was passed.
-
-TODO: Find out what purpose the +@options+ and +@middleware+ variables serve.
+In effect, these lines only define the +activesupport_path+ and +activemodel_path+ variables and nothing more.
-Finally, a +Rails::Application::Configuration+ object will be returned. On this class there are a couple of +attr_accessor+s and +attr_writer+s defined:
+The next two requires in this file are already done, so they are not run:
<ruby>
- attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging,
- :consider_all_requests_local, :dependency_loading,
- :load_once_paths, :logger, :plugins,
- :preload_frameworks, :reload_plugins, :serve_static_assets,
- :time_zone, :whiny_nils
-
- attr_writer :cache_store, :controller_paths,
- :database_configuration_file, :eager_load_paths,
- :i18n, :load_paths, :log_level, :log_path, :paths,
- :routes_configuration_file, :view_path
-</ruby>
-
-Along with these are a lot of helper methods, and one of them is +environment_path+:
-
-<ruby>
- def environment_path
- "#{root}/config/environments/#{Rails.env}.rb"
- end
+ require 'active_support'
+ require 'active_support/dependencies/autoload'
</ruby>
-h4. Back to +Rails::Application#require_environment+
-
-Now that we have a +Rails::Application::Configuration+ object for the +config+ method, we call the +environment_path+ which, as we've seen above, just requires the current environment file which in this case is _config/environments/development.rb_. If this file cannot be found, the +LoadError+ +require+ throws will be +rescue+'d and Rails will continue on its merry way.
-
-h4. _config/environments/development.rb_
-
-In a standard Rails application we have this in our _config/environments/development.rb_ file:
+The following require is to +action_pack+ (+activesupport/lib/action_pack.rb+) which has a 22-line copyright notice at the top of it and ends in a simple require to +action_pack/version+. This file, like other +version.rb+ files before it, defines the +ActionPack::VERSION+ constant:
<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.action_controller.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
+ module ActionPack
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
+ end
end
</ruby>
-It's a little bit sneaky here, but +configure+ is +alias+'d to +class_eval+ on subclasses of +Rails::Application+ which of course includes +YourApp::Application+. This means that the code inside the +configure do+ block will be evaled within the context of +YourApp::Application+. The +config+ method here is the one mentioned before: the +Rails::Application::Configuration+ object. The methods on it should look familiar too: they're the ones that had +attr_accessor+ and +attr_writer+ definitions.
+Once +action_pack+ is finished, then +active_model+ is required.
-The ones down the bottom, +config.action_controller+, +config.action_view+ and +config.action_mailer+ aren't defined by +attr_accessor+ or +attr_writer+, rather they're undefined methods and therefore will trigger the +method_missing+ on the +Rails::Application::Configuration+ option.
+h4. +activemodel/lib/active_model.rb+
-h5. config.cache_classes=
-
-The first method call in this file, this tells Rails to not cache the classes for every request. This means for every single request Rails will reload the classes of your application. If you have a lot of classes, this will slow down the request cycle of your application. This is set to +false+ in the _development_ environment, and +true+ in the _test_ & _production_ environments.
-
-h5. config.whiny_nils=
-
-If this is set to +true+, like it is here in the _development_ environment, _activesupport/whiny_nil_ will be +require+'d. Have you ever seen this error:
-
-<ruby>
- Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
-</ruby>
-
-Or perhaps this one?
+This file makes a require to +active_model/version+ which defines the version for Active Model:
<ruby>
- You have a nil object when you didn't expect it!
- You might have expected an instance of Array.
- The error occurred while evaluating nil.flatten!
-</ruby>
-
-If you have, then this is _activesupport/whiny_nil_ at work.
-
-
-h5. The frameworks
-
-As mentioned before, the methods +action_controller+, +action_view+ and +action_mailer+ aren't defined on the +Rails::Application::Configuration+ object, rather they are caught by +method_missing+ which does this:
+ module ActiveModel
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? @options[$1] = args.first : @options[$1]
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
-
- super
end
</ruby>
-Whilst this code is not obvious at first, a little bit of further explanation will help you understand. +config_key_regexp+ is another method (a private one, like +method_missing+) defined here:
+Once the +version.rb+ file is loaded, the +ActiveModel+ module has its autoloaded constants defined as well as a sub-module called +ActiveModel::Serializers+ which has autoloads of its own. When the +ActiveModel+ module is closed the +active_support/i18n+ file is required.
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
+h4. +activesupport/lib/active_support/i18n.rb+
-As is +config_keys+:
+This is where the +i18n+ gem is required and first configured:
<ruby>
- def config_keys
- ([ :active_support, :action_view ] +
- Railtie.plugin_names).map { |n| n.to_s }.uniq
+ begin
+ require 'i18n'
+ require 'active_support/lazy_load_hooks'
+ rescue LoadError => e
+ $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
end
-</ruby>
-
-Aha! There we've got mention of +action_view+, but what is in +Railtie.plugin_names+? Most likely in this case the other frameworks.
-h5. +Railtie.plugin_names+
-
-I'm going to show you two methods since the third one, +self.plugin_name+, calls the second one, +self.plugins+ and they're right after each other:
-
-<ruby>
- module Rails
- class Railtie
- def self.inherited(klass)
- @plugins ||= []
- @plugins << klass unless klass == Plugin
- end
-
- def self.plugins
- @plugins
- end
-
- def self.plugin_names
- plugins.map { |p| p.plugin_name }
- end
- end
- end
+ I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
</ruby>
-In here we see that we get the +plugin_names+ from a variable called +@plugins+... which we haven't seen yet. Through the power of the wonderful +inherited+ the +@plugins+ variable is populated. +inherited+ is called when a class inherits, or subclasses, from this class. Therefore we can determine that the other classes are probably inheriting or subclassing from +Rails::Railtie+.
-
-h3. Serving a Request
-
-Now that your application is fully initialized, it's now ready to start serving requests.
-
-h4. _rails server_
-
-For servers running through _rails server_ you may recall that this uses +Rails::Server+ which is a subclass of +Rack::Server+. Previously we covered the initialization process of Rack but not completely up to the point where the server was running. Now that's what we'll do. Back when the +Rack::Server+ class was first covered there was a mention of the +start+ method which we only touched on. It goes a little like this:
-
-<ruby>
- def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
-
- if options[:warn]
- $-w = true
- end
+In effect, the +I18n+ module first defined by +i18n_railtie+ is extended by the +i18n+ gem, rather than the other way around. This has no ill effect. They both work on the same way.
- if includes = options[:include]
- $LOAD_PATH.unshift *includes
- end
+This is another spot where +active_support/lazy_load_hooks+ is required, but it has already been required so it's not loaded again.
- if library = options[:require]
- require library
- end
+If +i18n+ cannot be loaded, the user is presented with an error which says that it cannot be loaded and recommends that it's added to the +Gemfile+. However, in a normal Rails application this gem would be loaded.
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
-</ruby>
+Once it has finished loading, the +I18n.load_path+ method is used to add the +activesupport/lib/active_support/locale/en.yml+ file to I18n's load path. When the translations are loaded in the initialization process, this is one of the files where they will be sourced from.
-We were at the point of explaining what +wrapped_app+ was before we dived into the Rails initialization process.Now that we have a +wrapped_app+ we pass it as the first argument to +server.run+. +server+ in this instance is defined like this:
+The loading of this file finishes the loading of +active_model+ and so we go back to +action_dispatch+.
-<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
-</ruby>
+h4. Back to +activesupport/lib/action_dispatch.rb+
-Our +options+ Hash is still the default, and there is no +server+ key set in +default_options+, so it will default to +Rack::Handler.default+. This code works like this:
+The remainder of this file requires the +rack+ file from the Rack gem which defines the +Rack+ module. After +rack+, there's autoloads defined for the +Rack+, +ActionDispatch+, +ActionDispatch::Http+, +ActionDispatch::Session+. A new method called +autoload_under+ is used here, and this simply prefixes the files where the modules are autoloaded from with the path specified. For example here:
<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
+ autoload_under 'testing' do
+ autoload :Assertions
+ ...
</ruby>
+The +Assertions+ module is in the +action_dispatch/testing+ folder rather than simply +action_dispatch+.
-We don't have +PHP_FCGI_CHILDREN+ in our +ENV+, so it's not going to be +FastCGI+. We also don't have +REQUEST_METHOD+ in there, so it's not going to be +CGI+. If we have Mongrel installed it'll default to that and then finally it'll use WEBrick. For this, we'll assume a bare-bones installation and assume WEBrick. So from this we can determine our default handler is +Rack::Handler::WEBrick+.
+Finally, this file defines a top-level autoload, the +Mime+ constant.
-(side-note: Mongrel doesn't install on 1.9. TODO: How do we format these anyway?)
+h4. Back to +activesupport/lib/action_dispatch/railtie.rb+
-h5. +Rack::Handler::WEBrick+
+After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ class is defined and is yet another class that inherits from +Rails::Railtie+. This class defines some initial configuration option defaults for +config.action_dispatch+ before setting up a single initializer called +action_dispatch.configure+.
-This class is subclassed from +WEBrick::HTTPServlet::AbstractServlet+ which is a class that comes with the Ruby standard library. This is the magical class that serves the requests and deals with the comings (requests) and goings (responses) for your server.
+With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+.
+h4. Back to +railties/lib/rails.rb+
-+Rack::Server+ has handlers for the request and by default the handler for a _rails server_ server is
+With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+.
-h3. Cruft!
+h4. Back to +railties/lib/rails/all.rb+
-The final line of _config/environment.rb_:
+Now that +rails.rb+ is required, the remaining railties are loaded next, beginning with +active_record/railtie+.
-<ruby>
- YourApp::Application.initialize!
-</ruby>
+h4. +activerecord/lib/active_record/railtie.rb+
-gets down to actually initializing the application!
+Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there are a couple of files that are required first. The first one of these is +active_record+.
-TODO: Cover the other +config.*+ methods in perhaps a "Bonus" section near the end. If they aren't referenced in a config file they aren't that important, right?
+h4. +activerecord/lib/active_record.rb+
+This file begins by detecting if the +lib+ directories of +active_support+ and +active_model+ are not in the load path and if they aren't then adds them. As we saw back in +action_dispatch.rb+, these directories are already there.
-TODO: This belongs in the guide, I just don't know where yet. Maybe towards the end, since this is really the "final" thing to be done before being able to serve requests.
+The first three requires have already been done by other files and so aren't loaded here, but the 4th require, the one to +arel+ will require the file provided by the Arel gem, which defines the +Arel+ module.
<ruby>
- def build_app(app)
- middleware[options[:environment]].reverse_each do |middleware|
- middleware = middleware.call(self) if middleware.respond_to?(:call)
- next unless middleware
- klass = middleware.shift
- app = klass.new(app, *middleware)
- end
- app
- end
-</ruby>
-
-Because we don't have any middleware for our application, this returns the application itself( Guessing here!! TODO: Investigate if this is really the case.)
-
-Now that we have an app instance, the last line in +start+ calls +server.run wrapped_app, options+. We know what our app is, and that our options are just the default options, so what is +server+? +server+ is this:
-
-<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
+ require 'active_support'
+ require 'active_support/i18n'
+ require 'active_model'
+ require 'arel'
</ruby>
-Since we have default options, the server is obviously going to be +Rack::Handler.default+. The +default+ method goes like this:
+The 5th require in this file is one to +active_record/version+ which defines the +ActiveRecord::VERSION+ constant:
<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
-</ruby>
-
-h3. +Rails::Paths+
-
-
-The +super+ method it references comes from +Rails::Engine::Configuration+ which defines these paths:
+ module ActiveRecord
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.views "app/views"
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
</ruby>
-h3. Appendix A
-
-This file is _activesupport/lib/active_support/inflector/inflections.rb_ and defines the +ActiveSupport::Inflector::Inflections+ class which defines the +singularize+, +pluralize+, +humanize+, +tableize+, +titleize+ and +classify+ methods as well as the code to defining how to work out the irregular, singular, plural and human versions of words. These methods are called +irregular+, +singular+, +plural+ and +human+ respectively, as is the Rails way.
-
-This file is _activesupport/lib/active_support/inflector/transliterate.rb_ and defines two methods, +transliterate+ and +parameterize+.
+Once these requires are finished, the base for the +ActiveRecord+ module is defined along with its autoloads.
-This file first requires _activesupport/lib/active_support/core_ext/string/multibyte.rb_, which requires _activesupport/lib/active_support/multibyte.rb_, which subsequently requires _activesupport/core_ext/module/attribute_accessors.rb_. The _attribute_accessors.rb_ file is needed to gain access to the +mattr_accessor+ (module attribute accessor) method, which is called in _active_suport/multibyte.rb_. The file _active_support/multibyte.rb_ also autoloads three other classes:
+Near the end of the file, we see this line:
<ruby>
-module ActiveSupport #:nodoc:
- module Multibyte
- autoload :EncodingError, 'active_support/multibyte/exceptions'
- autoload :Chars, 'active_support/multibyte/chars'
- autoload :Unicode, 'active_support/multibyte/unicode'
- ...
+ ActiveSupport.on_load(:active_record) do
+ Arel::Table.engine = self
end
-end
</ruby>
-There are also these method definitions:
-
-<ruby>
- # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy
- # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for
- # an example how to do this.
- #
- # Example:
- # ActiveSupport::Multibyte.proxy_class = CharsForUTF32
- def self.proxy_class=(klass)
- @proxy_class = klass
- end
-
- # Returns the currect proxy class
- def self.proxy_class
- @proxy_class ||= ActiveSupport::Multibyte::Chars
- end
-</ruby>
+This will set the engine for +Arel::Table+ to be +ActiveRecord::Base+.
-These methods are used in _activesupport/lib/active_support/core_ext/string/multibyte.rb_.
-
-The file _activesupport/lib/active_support/core_ext/string/chars.rb_ defines the default proxy class that will be returned by +mb_chars+.
-
-Because Ruby 1.9's +String+ class has support for multibyte encodings, some methods are defined only for Ruby 1.8:
-
-* +self.wants?+
-* +++
-* +=~+
-* +=~+
-* +center+
-* +include?+
-* +index+
-* +insert+
-* +ljust+
-* +lstrip+, +lstrip!+
-* +ord+
-* +rindex+
-* +rjust+
-* +rstrip+, +rstrip!+
-* +size+
-* +strip+, +strip!+
-
-However, Ruby 1.9 lacks support for some needed operations, so the following methods are defined for both Ruby 1.8 and Ruby 1.9:
-
-* +<=>+
-* +[]=+
-* +capitalize+, +capitalize!+
-* +compose+
-* +decompose+
-* +downcase+, +downcase!+
-* +g_length+
-* +limit+
-* +normalize+
-* +reverse+, +reverse+!
-* +slice+, +slice!+
-* +split+
-* +tidy_bytes+, +tidy_bytes!+
-* +titleize+
-* +upcase+, +upcase!+
+The file then finishes with this line:
<ruby>
- class String
- if RUBY_VERSION >= "1.9"
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.consumes?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- def is_utf8? #:nodoc
- case encoding
- when Encoding::UTF_8
- valid_encoding?
- when Encoding::ASCII_8BIT, Encoding::US_ASCII
- dup.force_encoding(Encoding::UTF_8).valid_encoding?
- else
- false
- end
- end
- else
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.wants?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have
- # them), returns false otherwise.
- def is_utf8?
- ActiveSupport::Multibyte::Chars.consumes?(self)
- end
- end
+ I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
</ruby>
-As you can see, +mb_chars+ is where the +proxy_class+ property comes in handy. This method will create a new instance of the configured proxy class using the instance of +String+ as a constructor argument. By default, the new +String+-like object will be an instance of the proxy class +ActiveSupport::Multibyte::Chars+. You can use +ActiveSupport::Multibyte.proxy_class=+ to set a different proxy class if you wish.
-
-Here, +mb_chars+ invokes +is_utf8?+ to checks if the string can be treated as UTF-8. On 1.9, the string's +encoding+ property is checked. On 1.8, +wants?+ checks to see if +$KCODE+ is "UTF-8" and, and +consumes?+ checks whether the string can be unpacked as UTF-8 without raising an error.
-
-The keen eye will have seen +ActiveSupport::Multibyte::Chars+ was specified as an +autoload+ earlier: _activesupport/lib/active_support/multibyte/chars.rb_ will be loaded without an explicit +require+ when we call +is_utf8+ on 1.8, or +mb_chars+ on any Ruby version. This file includes _activesupport/lib/active_support/string/access.rb_ which defines methods such as +at+, +from+, +to+, +first+ and +last+. These methods will return parts of the string depending on what is passed to them.
+This will add the translations from +activerecord/lib/active_record/locale/en.yml+ to the load path for +I18n+, with this file being parsed when all the translations are loaded.
-The second file included is _activesupport/lib/active_support/string/behavior.rb_ which only defines +acts_like_string?+ on +String+, a method which always returns +true+. This method is used by +Object#acts_like?+, which accepts a single argument representing the downcased and symbolised version of a class, and returns true if the object's behavior is like that class. In this case the code would be +acts_like?(:string)+.
+h4. Back to +activerecord/lib/active_record/railtie.rb+
-The +Chars+ class also defines other important methods such as the "spaceship" method +<=>+, which is needed by the +Comparable+ module, in order to allow UTF-8-aware sorting.
-
-h3. Common Includes
-
-TODO: I feel this section would be better at the end of the guide as it breaks the flow.
-
-This section is for all the common includes in the Railties.
-
-h4. +require 'active_support/inflector'+
-
-This file is _activesupport/lib/active_support/inflector.rb_ and makes a couple of requires out different files tasked with putting inflections in place:
+The next two <tt>require</tt>s in this file aren't run because their files are already required, with +rails+ being required by +rails/all+ and +active_model/railtie+ being required from +action_dispatch+.
<ruby>
- require 'active_support/inflector/inflections'
- require 'active_support/inflector/transliterate'
- require 'active_support/inflector/methods'
-
- require 'active_support/inflections'
- require 'active_support/core_ext/string/inflections'
+ require "rails"
+ require "active_model/railtie"
</ruby>
-The files included here define methods for modifying strings, such as +transliterate+ which will convert a Unicode string to its ASCII version, +parameterize+ for making strings into url-safe versions, +camelize+ for camel-casing a string such as +string_other+ into +StringOther+ and +ordinalize+ converting a string such as +101+ into +101st+. More information about these methods can be found in the Active Support Core Extensions Guide. TODO: Link to AS Guide.
-
-h4. +require 'active_support/core_ext/module/delegation'+
-
-_activesupport/lib/active_support/core_ext/module/delegation.rb_ defines the +delegate+ method which can be used to delegate methods to other methods in your code. Take the following code example:
+The next +require+ in this file is to +action_controller/railtie+.
-<ruby>
- class Client < ActiveRecord::Base
- has_one :address
-
- delegate :address_line_1, :to => :address
- end
-</ruby>
+h4. +actionpack/lib/action_controller/railtie.rb+
-This defines an +address_line_1+ method which is defined as:
+This file begins with a couple more requires to files that have already been loaded:
<ruby>
- def address_line_1(*args, &block)
- address.__send__(:address_line_1, *args, &block)
- rescue NoMethodError
- if address.nil?
- raise "address_line_1 is delegated to address.address_line_1, but address is nil: #{client.inspect}"
- end
- end
+ require "rails"
+ require "action_controller"
+ require "action_dispatch/railtie"
</ruby>
-h4. +require 'active_support/core_ext/class/attribute_accessors'+
-
-The file, _activesupport/lib/active_support/core_ext/class/attribute_accessors.rb_, defines the class accessor methods +cattr_writer+, +cattr_reader+ and +cattr_accessor+. +cattr_accessor+ defines a +cattr_reader+ and +cattr_writer+ for the symbol passed in. These methods work by defining class variables when you call their dynamic methods.
-
-Throughout the Railties there a couple of common includes. They are listed here for your convenience.
-
-h4. +require 'active_support/core_ext/module/attr_internal+
-
-This file defines three methods +attr_internal_reader+, +attr_internal_writer+ and +attr_internal_accessor+. These work very similar to the +attr_reader+, +attr_writer+ and +attr_accessor+ methods, except the variables they define begin with +@_+. This was done to ensure that they do not clash with variables used people using Rails, as people are less-likely to define say, +@_request+ than they are to define +@request+. An example of where this method is used is for +params+ in the +ActionController::Metal+ class.
-
-h4. +require 'active_support/ruby/shim'+
-
-The _activesupport/lib/active_support/ruby/shim.rb_ file requires methods that have been implemented in Ruby versions greater than 1.9. This is done so you can use Rails 3 on versions earlier than 1.9, such as 1.8.7. These methods are:
-
-* +Date#next_month+
-* +Date#next_year+
-* +DateTime#to_date+
-* +DateTime#to_datetime+
-* +DateTime#xmlschema+
-* +Enumerable#group_by+
-* +Enumerable#each_with_object+
-* +Enumerable#none?+
-* +Process#daemon+
-* +String#ord+
-* +Time#to_date+
-* +Time.to_time+
-* +Time.to_datetime+
+However the require after these is to a file that hasn't yet been loaded, +action_view/railtie+, which begins by requiring +action_view+.
-For more information see the Active Support Core Extensions guide TODO: link to relevant sections for each method.
+h4. +actionpack/lib/action_view.rb+
-And "the REXML security fix detailed here":[http://weblog.rubyonrails.org/2008/8/23/dos-vulnerabilities-in-rexml]
++action_view.rb+
diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb
index cc7d54c256..f2681c6461 100644
--- a/railties/guides/source/layout.html.erb
+++ b/railties/guides/source/layout.html.erb
@@ -8,13 +8,12 @@
<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/syntax.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
-<script type="text/javascript" src="javascripts/guides.js"></script>
-<script type="text/javascript" src="javascripts/code_highlighter.js"></script>
-<script type="text/javascript" src="javascripts/highlighters.js"></script>
+<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
+<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
+<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
</head>
<body class="guide">
<% if @edge %>
@@ -76,11 +75,12 @@
<dt>Extending Rails</dt>
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
- <dd><a href="generators.html">Adding a Generator to Your Plugin</a></dd>
+ <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
- <dt>Contributing to Rails</dt>
- <dd><a href="contributing_to_rails.html">Contributing to Rails</a></dd>
+ <dt>Contributing to Ruby on Rails</dt>
+ <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
+ <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
@@ -108,6 +108,28 @@
<div class="wrapper">
<div id="mainCol">
<%= yield.html_safe %>
+
+ <h3>Feedback</h3>
+ <p>
+ You're encouraged to help in keeping the quality of this guide.
+ </p>
+ <p>
+ If you see any typos or factual errors you are confident to
+ patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %>
+ 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>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>
@@ -119,5 +141,15 @@
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
</div>
</div>
+
+ <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()
+ </script>
</body>
</html>
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index b9a201e5f0..1548da0eb5 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -27,7 +27,7 @@ I'll cover each of these methods in turn. But first, a few words about the very
h4. 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:
+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
@@ -46,7 +46,7 @@ And you have a view file +app/views/books/index.html.erb+:
<h1>Books are coming soon!</h1>
</ruby>
-Rails will automatically render +app/views/books/index.html.erb+ when you navigate to +/books+ and you will see on your screen that "Books are coming soon!"
+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+:
@@ -58,9 +58,9 @@ class BooksController < ApplicationController
end
</ruby>
-Note that again, we have convention over configuration, in that there is no explicit render at the end of this index action. The rule is that if you do not explicitly render something by the end of the controller action, rails will look for the +action_name.html.erb+ template in the controllers view path and then render that, so in this case, Rails will render the +app/views/books/index.html.erb+ file.
+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.
-So in our view, we want to display the properties of all the books, we could do this with an ERB template like this:
+If we want to display the properties of all the books in our view, we can do so with an ERB template like this:
<ruby>
<h1>Listing Books</h1>
@@ -90,7 +90,7 @@ So in our view, we want to display the properties of all the books, we could do
<%= link_to 'New book', new_book_path %>
</ruby>
-NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), +.rjs+ for RJS (javascript with embedded ruby) and +.builder+ for Builder (XML generator).
+NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), +.rjs+ for RJS (JavaScript with embedded ruby) and +.builder+ for Builder (XML generator).
h4. Using +render+
@@ -106,10 +106,10 @@ Perhaps the simplest thing you can do with +render+ is to render nothing at all:
render :nothing => true
</ruby>
-If you look at the response for this using Curl you will see the following:
+If you look at the response for this using cURL, you will see the following:
<shell>
- $ curl -i 127.0.0.1:3000/books
+$ curl -i 127.0.0.1:3000/books
HTTP/1.1 200 OK
Connection: close
Date: Sun, 24 Jan 2010 09:25:18 GMT
@@ -123,7 +123,7 @@ Cache-Control: no-cache
$
</shell>
-We see there is an empty response (no data after the +Cache-Control+ line), but that Rails has set the response to 200 OK, so the request was successful. You can set the +:status+ options on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed.
+We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ option on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed.
TIP: You should probably be using the +head+ method, discussed later in this guide, instead of +render :nothing+. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
@@ -134,27 +134,25 @@ If you want to render the view that corresponds to a different action within the
<ruby>
def update
@book = Book.find(params[:id])
- if @book.update_attributes(params[:book])
- redirect_to(@book)
- else
- render "edit"
- end
+ if @book.update_attributes(params[:book])
+ redirect_to(@book)
+ else
+ render "edit"
end
end
</ruby>
-If the call to +update_attributes+ fails, calling the +update+ action in this controller will render the +edit.html.erb+ template belonging to the same controller.
+If the call to +update_attributes+ 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_attributes(params[:book])
- redirect_to(@book)
- else
- render :edit
- end
+ if @book.update_attributes(params[:book])
+ redirect_to(@book)
+ else
+ render :edit
end
end
</ruby>
@@ -164,11 +162,10 @@ To be explicit, you can use +render+ with the +:action+ option (though this is n
<ruby>
def update
@book = Book.find(params[:id])
- if @book.update_attributes(params[:book])
- redirect_to(@book)
- else
- render :action => "edit"
- end
+ if @book.update_attributes(params[:book])
+ redirect_to(@book)
+ else
+ render :action => "edit"
end
end
</ruby>
@@ -200,7 +197,7 @@ 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 =>
+render :file =>
"/u/apps/warehouse_app/current/app/views/products/show"
</ruby>
@@ -208,13 +205,13 @@ The +:file+ option takes an absolute file-system path. Of course, you need to ha
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 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.
+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.
h5. Wrapping it up
-The above three methods of render (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually all variants of the same action.
+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 method, inside of the edit action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
+In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
<ruby>
render :edit
@@ -240,22 +237,22 @@ h5. 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 %>"
+render :inline =>
+ "<% products.each do |p| %><p><%= p.name %></p><% end %>"
</ruby>
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:
+By default, inline rendering uses ERB. You can force it to use Builder instead with the +:type+ option:
<ruby>
-render :inline =>
+render :inline =>
"xml.p {'Horrid coding practice!'}", :type => :builder
</ruby>
h5. Using +render+ with +:update+
-You can also render javascript-based page updates inline using the +:update+ option to +render+:
+You can also render JavaScript-based page updates inline using the +:update+ option to +render+:
<ruby>
render :update do |page|
@@ -263,7 +260,7 @@ render :update do |page|
end
</ruby>
-WARNING: Placing javascript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate rjs template instead, no matter how small the update.
+WARNING: Placing JavaScript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate RJS template instead, no matter how small the update.
h5. Rendering Text
@@ -275,11 +272,11 @@ 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.
+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.
h5. 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:
+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
@@ -342,14 +339,14 @@ render :layout => false
h6. The +:status+ Option
-Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
+Rails will automatically generate a response with the correct HTTP status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
<ruby>
render :status => 500
render :status => :forbidden
</ruby>
-Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how Rails maps symbols to status codes.
+Rails understands both numeric status codes and symbols for status codes.
h6. The +:location+ Option
@@ -498,7 +495,7 @@ def show
end
</ruby>
-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 +show+ view - and throw an error. The solution is simple: make sure that you only have one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method:
+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 a patched version of the method:
<ruby>
def show
@@ -568,7 +565,7 @@ def show
end
</ruby>
-With the code in this form, there will be likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering:
+With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering:
<ruby>
def index
@@ -585,7 +582,7 @@ 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 301 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.
+The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.
While in a small app, this added latency might not be a problem, it is something to think about when speed of response is of the essence. One way to handle this double request (though a contrived example) could be:
@@ -603,11 +600,11 @@ def show
end
</ruby>
-Which would detect that there are no books populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened.
+Which would detect that there are no books, populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened.
h4. Using +head+ To Build Header-Only Responses
-The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header:
+The +head+ method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header:
<ruby>
head :bad_request
@@ -654,11 +651,9 @@ When Rails renders a view as a response, it does so by combining the view with t
* +yield+ and +content_for+
* Partials
-I'll discuss each of these in turn.
-
h4. Asset Tags
-Asset tags provide methods for generating HTML that links views to assets like images, videos, audio, javascript, stylesheets, and feeds. There are six types of include tag:
+Asset tags provide methods for generating HTML that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails:
* +auto_discovery_link_tag+
* +javascript_include_tag+
@@ -676,17 +671,17 @@ h5. Linking to Feeds with +auto_discovery_link_tag+
The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag:
<erb>
-<%= auto_discovery_link_tag(:rss, {:action => "feed"},
+<%= auto_discovery_link_tag(:rss, {:action => "feed"},
{:title => "RSS Feed"}) %>
</erb>
There are three tag options available for +auto_discovery_link_tag+:
* +:rel+ specifies the +rel+ value in the link (defaults to "alternate")
-* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically
+* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
* +:title+ specifies the title of the link
-h5. Linking to Javascript Files with +javascript_include_tag+
+h5. Linking to JavaScript Files with +javascript_include_tag+
The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+:
@@ -718,7 +713,7 @@ The +defaults+ option loads the Prototype and Scriptaculous libraries:
<%= javascript_include_tag :defaults %>
</erb>
-The +all+ option loads every javascript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries:
+The +all+ option loads every JavaScript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries:
<erb>
<%= javascript_include_tag :all %>
@@ -730,7 +725,7 @@ You can supply the +:recursive+ option to load files in subfolders of +public/ja
<%= javascript_include_tag :all, :recursive => true %>
</erb>
-If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+:
+If you're loading multiple JavaScript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+:
<erb>
<%= javascript_include_tag "main", "columns", :cache => true %>
@@ -739,7 +734,7 @@ If you're loading multiple javascript files, you can create a better user experi
By default, the combined file will be delivered as +javascripts/all.js+. You can specify a location for the cached asset file instead:
<erb>
-<%= javascript_include_tag "main", "columns",
+<%= javascript_include_tag "main", "columns",
:cache => 'cache/main/display' %>
</erb>
@@ -798,7 +793,7 @@ If you're loading multiple CSS files, you can create a better user experience by
By default, the combined file will be delivered as +stylesheets/all.css+. You can specify a location for the cached asset file instead:
<erb>
-<%= stylesheet_link_tag "main", "columns",
+<%= stylesheet_link_tag "main", "columns",
:cache => 'cache/main/display' %>
</erb>
@@ -806,7 +801,9 @@ You can even use dynamic paths such as +cache/#{current_site}/main/display+.
h5. Linking to Images with +image_tag+
-The +image_tag+ helper builds an HTML +&lt;img /&gt;+ tag to the specified file. By default, files are loaded from +public/images+, note, you must specify the extension, previous versions of Rails would allow you to just call the image name and would append +.png+ if no extension was given, Rails 3.0 does not.
+The +image_tag+ helper builds an HTML +&lt;img /&gt;+ tag to the specified file. By default, files are loaded from +public/images+.
+
+WARNING: Note that you must specify the extension of the image. Previous versions of Rails would allow you to just use the image name and would append +.png+ if no extension was given but Rails 3.0 does not.
<erb>
<%= image_tag "header.png" %>
@@ -830,7 +827,7 @@ You can also supply an alternate image to show on mouseover:
<%= image_tag "home.gif", :onmouseover => "menu/home_highlight.gif" %>
</erb>
-Or alternate text if the user has rendering images turned off in their browser, if you do not specify an explicit alt tag, it defaults to the file name of the file, capitalized and with no extension, for example, these two image tags would return the same code:
+You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:
<erb>
<%= image_tag "home.gif" %>
@@ -843,7 +840,7 @@ You can also specify a special size tag, in the format "{width}x{height}":
<%= image_tag "home.gif", :size => "50x20" %>
</erb>
-In addition to the above special tags, you can supply a final hash of standard HTML options, such as +:class+ or +:id+ or +:name+:
+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",
@@ -940,7 +937,7 @@ The main body of the view will always render into the unnamed +yield+. To render
h4. Using +content_for+
-The +content_for+ method allows you to insert content into a +yield+ block in your layout. You only use +content_for+ to insert content in named yields. For example, this view would work with the layout that you just saw:
+The +content_for+ method allows you to insert content into a named +yield+ block in your layout. For example, this view would work with the layout that you just saw:
<erb>
<% content_for :head do %>
@@ -963,15 +960,15 @@ The result of rendering this page into the supplied layout would be this HTML:
</html>
</erb>
-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.
+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.
h4. Using Partials
-Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
h5. Naming Partials
-To render a partial as part of a view, you use the +render+ method within the view, and include the +:partial+ option:
+To render a partial as part of a view, you use the +render+ method within the view:
<ruby>
<%= render "menu" %>
@@ -1009,11 +1006,13 @@ h5. Partial Layouts
A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:
<erb>
-<%= render "link_area", :layout => "graybar" %>
+<%= render :partial => "link_area", :layout => "graybar" %>
</erb>
This would look for a partial named +_link_area.html.erb+ and render it using the layout +_graybar.html.erb+. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master +layouts+ folder).
+Also note that explicitly specifying +:partial+ is required when passing additional options such as +:layout+.
+
h5. Passing Local Variables
You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
@@ -1085,17 +1084,15 @@ Partials are very useful in rendering collections. When you pass a collection to
<p>Product Name: <%= product.name %></p>
</erb>
-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.
+When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered.
-In Rails 3.0 there is also a shorthand for this, assuming +@posts+ is a collection of +post+ instances, you can simply do in the +index.html.erb+:
+In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a collection of +product+ instances, you can simply write this in the +index.html.erb+ to produce the same result:
<erb>
<h1>Products</h1>
<%= render @products %>
</erb>
-To produce the same result.
-
Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
* +index.html.erb+
@@ -1132,7 +1129,7 @@ With this change, you can access an instance of the +@products+ collection as th
You can also pass in arbitrary local variables to any partial you are rendering with the +:locals => {}+ option:
<erb>
-<%= render :partial => 'products', :collection => @products,
+<%= render :partial => 'products', :collection => @products,
:as => :item, :locals => {:title => "Products Page"} %>
</erb>
@@ -1186,17 +1183,15 @@ On pages generated by +NewsController+, you want to hide the top menu and add a
<div id="right_menu">Right menu items here</div>
<%= yield(:news_content) or yield %>
<% end %>
-<%= render :file => 'layouts/application' %>
+<%= render :template => 'layouts/application' %>
</erb>
That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.
-There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :file => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +yield(:news_content) or yield+ with simply +yield+.
+There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :template => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +yield(:news_content) or yield+ with simply +yield+.
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15
-
* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* January 25, 2010: Rails 3.0 Update by "Mikel Lindsaar":credits.html#raasdnil
* December 27, 2008: Merge patch from Rodrigo Rosenfeld Rosas covering subtemplates
diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile
index 16f616a5bc..57e6bcd123 100644
--- a/railties/guides/source/migrations.textile
+++ b/railties/guides/source/migrations.textile
@@ -109,7 +109,7 @@ h4. Creating a Model
The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want then statements for adding those will also be created. For example, running
<shell>
-rails generate model Product name:string description:text
+$ rails generate model Product name:string description:text
</shell>
will create a migration that looks like this
@@ -139,7 +139,7 @@ h4. Creating a Standalone Migration
If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator:
<shell>
-rails generate migration AddPartNumberToProducts
+$ rails generate migration AddPartNumberToProducts
</shell>
This will create an empty but appropriately named migration:
@@ -157,7 +157,7 @@ end
If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate +add_column+ and +remove_column+ statements will be created.
<shell>
-rails generate migration AddPartNumberToProducts part_number:string
+$ rails generate migration AddPartNumberToProducts part_number:string
</shell>
will generate
@@ -177,7 +177,7 @@ end
Similarly,
<shell>
-rails generate migration RemovePartNumberFromProducts part_number:string
+$ rails generate migration RemovePartNumberFromProducts part_number:string
</shell>
generates
@@ -197,7 +197,7 @@ end
You are not limited to one magically generated column, for example
<shell>
-rails generate migration AddDetailsToProducts part_number:string price:decimal
+$ rails generate migration AddDetailsToProducts part_number:string price:decimal
</shell>
generates
@@ -250,7 +250,7 @@ create_table :products do |t|
end
</ruby>
-By default +create_table+ will create a primary key called +id+. You can change the name of the primary key with the +:primary_key+ option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass +:id => false+. If you need to pass database specific options you can place a SQL fragment in the +:options+ option. For example
+By default +create_table+ will create a primary key called +id+. You can change the name of the primary key with the +:primary_key+ option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass +: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|
@@ -383,7 +383,7 @@ If you specify a target version, Active Record will run the required migrations
version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run
<shell>
-rake db:migrate VERSION=20080906120000
+$ rake db:migrate VERSION=20080906120000
</shell>
If this is greater than the current version (i.e. it is migrating upwards) this will run the +up+ method on all migrations up to and including 20080906120000, if migrating downwards this will run the +down+ method on all the migrations down to, but not including, 20080906120000.
@@ -393,13 +393,13 @@ h4. Rolling Back
A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run
<shell>
-rake db:rollback
+$ rake db:rollback
</shell>
This will run the +down+ method from the latest migration. If you need to undo several migrations you can provide a +STEP+ parameter:
<shell>
-rake db:rollback STEP=3
+$ rake db:rollback STEP=3
</shell>
will run the +down+ method from the last 3 migrations.
@@ -407,7 +407,7 @@ will run the +down+ method from the last 3 migrations.
The +db:migrate:redo+ task is a shortcut for doing a rollback and then migrating back up again. As with the +db:rollback+ task you can use the +STEP+ parameter if you need to go more than one version back, for example
<shell>
-rake db:migrate:redo STEP=3
+$ rake db:migrate:redo STEP=3
</shell>
Neither of these Rake tasks do anything you could not do with +db:migrate+, they are simply more convenient since you do not need to explicitly specify the version to migrate to.
@@ -421,7 +421,7 @@ h4. Being Specific
If you need to run a specific migration up or down the +db:migrate:up+ and +db:migrate:down+ tasks will do that. Just specify the appropriate version and the corresponding migration will have its +up+ or +down+ method invoked, for example
<shell>
-rake db:migrate:up VERSION=20080906120000
+$ rake db:migrate:up VERSION=20080906120000
</shell>
will run the +up+ method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example +db:migrate:up VERSION=20080906120000+ will do nothing if Active Record believes that 20080906120000 has already been run.
@@ -546,7 +546,7 @@ Schema files are also useful if you want a quick look at what attributes an Acti
h4. Types of Schema Dumps
-There are two ways to dump the schema. This is set in +config/environment.rb+ by the +config.active_record.schema_format+ setting, which may be either +:sql+ or +:ruby+.
+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:
@@ -584,13 +584,11 @@ h3. Active Record and Referential Integrity
The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.
-Validations such as +validates_uniqueness_of+ 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.
+Validations such as +validates :foreign_key, :uniqueness => true+ are one way in which models can enforce data integrity. The +:dependent+ option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
-Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":http://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+).
+Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":https://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+).
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/6
-
* July 15, 2010: minor typos corrected by "Jaime Iniesta":http://jaimeiniesta.com
* September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung
diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile
index 39b0c32f24..55694c0eb4 100644
--- a/railties/guides/source/nested_model_forms.textile
+++ b/railties/guides/source/nested_model_forms.textile
@@ -1,6 +1,6 @@
h2. Rails nested model forms
-Creating a form for a model _and_ its associations can become quite tedious. Therefor Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
+Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
In this guide you will:
@@ -63,7 +63,7 @@ class Person
def address
Address.new
end
-
+
def address_attributes=(attributes)
# ...
end
@@ -77,7 +77,7 @@ class Person
def projects
[Project.new, Project.new]
end
-
+
def projects_attributes=(attributes)
# ...
end
@@ -101,7 +101,7 @@ class PeopleController < ActionController:Base
@person.built_address
2.times { @person.projects.build }
end
-
+
def create
@person = Person.new(params[:person])
if @person.save
@@ -142,7 +142,7 @@ 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| %>
<%= f.text_field :street %>
<% end %>
@@ -154,7 +154,7 @@ This generates:
<html>
<form action="/people" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
-
+
<input id="person_address_attributes_street" name="person[address_attributes][street]" size="30" type="text" />
</form>
</html>
@@ -183,7 +183,7 @@ The form code for an association collection is pretty similar to that of a singl
<erb>
<%= form_for @person do |f| %>
<%= f.text_field :name %>
-
+
<%= f.fields_for :projects do |pf| %>
<%= f.text_field :name %>
<% end %>
@@ -195,7 +195,7 @@ Which generates:
<html>
<form action="/people" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
-
+
<input id="person_projects_attributes_0_name" name="person[projects_attributes][0][name]" size="30" type="text" />
<input id="person_projects_attributes_1_name" name="person[projects_attributes][1][name]" size="30" type="text" />
</form>
@@ -219,4 +219,4 @@ You can basically see the +projects_attributes+ hash as an array of attribute ha
NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep.
-TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example. \ No newline at end of file
+TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example.
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index 65f8d07e7a..5679bae531 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -20,7 +20,7 @@ In a freshly generated Rails application, +test/performance/browsing_test.rb+ co
<ruby>
require 'test_helper'
-require 'performance_test_help'
+require 'rails/performance_test_help'
# Profiling results for each test method are written to tmp/performance.
class BrowsingTest < ActionController::PerformanceTest
@@ -34,17 +34,17 @@ This example is a simple performance test case for profiling a GET request to th
h4. Generating Performance Tests
-Rails provides a generator called +performance_test+ for creating new performance tests:
+Rails provides a generator called +test_unit:performance+ for creating new performance tests:
<shell>
-rails generate performance_test homepage
+$ rails generate test_unit:performance homepage
</shell>
This generates +homepage_test.rb+ in the +test/performance+ directory:
<ruby>
require 'test_helper'
-require 'performance_test_help'
+require 'rails/performance_test_help'
class HomepageTest < ActionController::PerformanceTest
# Replace this with your real tests.
@@ -60,8 +60,8 @@ Let's assume your application has the following controller and model:
<ruby>
# routes.rb
-map.root :controller => 'home'
-map.resources :posts
+root :to => 'home#index'
+resources :posts
# home_controller.rb
class HomeController < ApplicationController
@@ -103,7 +103,7 @@ Here's the performance test for +HomeController#dashboard+ and +PostsController#
<ruby>
require 'test_helper'
-require 'performance_test_help'
+require 'rails/performance_test_help'
class PostPerformanceTest < ActionController::PerformanceTest
def setup
@@ -131,7 +131,7 @@ Performance test for +Post+ model:
<ruby>
require 'test_helper'
-require 'performance_test_help'
+require 'rails/performance_test_help'
class PostModelTest < ActionController::PerformanceTest
def test_creation
@@ -316,16 +316,16 @@ Compile Ruby and apply this "GC Patch":http://rubyforge.org/tracker/download.php
h5. Download and Extract
<shell>
-[lifo@null ~]$ mkdir rubygc
-[lifo@null ~]$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby>
-[lifo@null ~]$ tar -xzvf <ruby-version.tar.gz>
-[lifo@null ~]$ cd <ruby-version>
+$ mkdir rubygc
+$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby>
+$ tar -xzvf <ruby-version.tar.gz>
+$ cd <ruby-version>
</shell>
h5. Apply the Patch
<shell>
-[lifo@null ruby-version]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
+$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
</shell>
h5. Configure and Install
@@ -333,8 +333,8 @@ h5. Configure and Install
The following will install ruby in your home directory's +/rubygc+ directory. Make sure to replace +&lt;homedir&gt;+ with a full patch to your actual home directory.
<shell>
-[lifo@null ruby-version]$ ./configure --prefix=/<homedir>/rubygc
-[lifo@null ruby-version]$ make && make install
+$ ./configure --prefix=/<homedir>/rubygc
+$ make && make install
</shell>
h5. Prepare Aliases
@@ -364,8 +364,8 @@ Additionally, install the following gems:
If installing +mysql+ fails, you can try to install it manually:
<shell>
-[lifo@null mysql]$ gcruby extconf.rb --with-mysql-config
-[lifo@null mysql]$ make && make install
+$ gcruby extconf.rb --with-mysql-config
+$ make && make install
</shell>
And you're ready to go. Don't forget to use +gcruby+ and +gcrake+ aliases when running the performance tests.
@@ -398,7 +398,7 @@ $ rails benchmarker 'Item.first' 'Item.last'
h4. +profiler+
-+profiler+ is a wrapper around http://ruby-prof.rubyforge.org/[ruby-prof] gem.
++profiler+ is a wrapper around the "ruby-prof":http://ruby-prof.rubyforge.org gem.
Usage:
@@ -436,7 +436,7 @@ h4. Model
Project.benchmark("Creating project") do
project = Project.create("name" => "stuff")
project.create_manager("name" => "David")
- project.milestones << Milestone.find(:all)
+ project.milestones << Milestone.all
end
</ruby>
@@ -469,7 +469,7 @@ And in "views":http://api.rubyonrails.org/classes/ActionController/Benchmarking/
<erb>
<% benchmark("Showing projects partial") do %>
- <%= render :partial => @projects %>
+ <%= render @projects %>
<% end %>
</erb>
@@ -500,8 +500,8 @@ h4. Rails Plugins and Gems
* "Rails Analyzer":http://rails-analyzer.rubyforge.org
* "Palmist":http://www.flyingmachinestudios.com/projects/
-* "Rails Footnotes":http://github.com/josevalim/rails-footnotes/tree/master
-* "Query Reviewer":http://github.com/dsboulder/query_reviewer/tree/master
+* "Rails Footnotes":https://github.com/josevalim/rails-footnotes/tree/master
+* "Query Reviewer":https://github.com/dsboulder/query_reviewer/tree/master
h4. Generic Tools
@@ -524,7 +524,5 @@ Rails has been lucky to have two startups dedicated to Rails specific performanc
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4
-
* January 9, 2009: Complete rewrite by "Pratik":credits.html#lifo
* September 6, 2008: Initial version by Matthew Bergman
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index 82f2276153..2d9821e627 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -10,281 +10,71 @@ After reading this guide you should be familiar with:
* Creating a plugin from scratch
* Writing and running tests for the plugin
-* Storing models, views, controllers, helpers and even other plugins in your plugins
-* Writing generators
-* Writing custom Rake tasks in your plugin
-* Generating RDoc documentation for your plugin
-* Avoiding common pitfalls with 'init.rb'
This guide describes how to build a test-driven plugin that will:
* Extend core ruby classes like Hash and String
* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
-* Add a view helper that can be used in erb templates
-* Add a new generator that will generate a migration
-* Add a custom generator command
-* A custom route method that can be used in routes.rb
+* Give you information about where to put generators in your plugin.
-For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
+For the purpose of this guide pretend for a moment that you are an avid bird watcher.
+Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle
+goodness.
endprologue.
h3. Setup
-h4. Create the Basic Application
+h4. Generating the Plugin Skeleton
-The examples in this guide require that you have a working rails application. To create a simple rails app execute:
+Rails currently ships with a generator to generate a plugin within a Rails application. Help text is available that will explain
+how this generator works.
<shell>
-gem install rails
-rails yaffle_guide
-cd yaffle_guide
-rails generate scaffold bird name:string
-rake db:migrate
-rails server
+$ rails generate plugin --help
</shell>
-Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
+This generator places the plugin into the vendor/plugins directory.
-NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
+Vendored plugins are useful for quickly prototyping your plugin but current thinking in the Rails community is shifting towards
+packaging plugins as gems, especially with the inclusion of Bundler as the Rails dependency manager.
+Packaging a plugin as a gem may be overkill for any plugins that will not be shared across projects but doing so from the start makes it easier to share the plugin going forward without adding too much additional overhead during development.
-
-h4. Generate the Plugin Skeleton
-
-Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass +--with-generator+ to add an example generator also.
-
-This creates a plugin in +vendor/plugins+ including an +init.rb+ and +README+ as well as standard +lib+, +task+, and +test+ directories.
-
-Examples:
-<shell>
-rails generate plugin yaffle
-rails generate plugin yaffle --with-generator
-</shell>
-
-To get more detailed help on the plugin generator, type +rails generate plugin+.
-
-Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the +--with-generator+ option now:
-
-<shell>
-rails generate plugin yaffle --with-generator
-</shell>
-
-You should see the following output:
-
-<shell>
-create vendor/plugins/yaffle/lib
-create vendor/plugins/yaffle/tasks
-create vendor/plugins/yaffle/test
-create vendor/plugins/yaffle/README
-create vendor/plugins/yaffle/MIT-LICENSE
-create vendor/plugins/yaffle/Rakefile
-create vendor/plugins/yaffle/init.rb
-create vendor/plugins/yaffle/install.rb
-create vendor/plugins/yaffle/uninstall.rb
-create vendor/plugins/yaffle/lib/yaffle.rb
-create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
-create vendor/plugins/yaffle/test/core_ext_test.rb
-create vendor/plugins/yaffle/generators
-create vendor/plugins/yaffle/generators/yaffle
-create vendor/plugins/yaffle/generators/yaffle/templates
-create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-create vendor/plugins/yaffle/generators/yaffle/USAGE
-</shell>
-
-h4. Organize Your Files
-
-To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this:
+Rails 3.1 will ship with a plugin generator that will default to setting up a plugin
+as a gem. This tutorial will begin to bridge that gap by demonstrating how to create a gem based plugin using the
+"Enginex gem":http://www.github.com/josevalim/enginex.
<shell>
-|-- lib
-| |-- yaffle
-| `-- yaffle.rb
-`-- rails
- |
- `-- init.rb
+$ gem install enginex
+$ enginex --help
+$ enginex yaffle
</shell>
-<ruby>
-# vendor/plugins/yaffle/init.rb
-
-require 'yaffle'
-</ruby>
-
-Now you can add any +require+ statements to +lib/yaffle.rb+ and keep +init.rb+ clean.
-
-h3. Tests
-
-In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:
-
- * A +database.yml+ file with all of your connection strings
- * A +schema.rb+ file with your table definitions
- * A test helper method that sets up the database
-
-h4. Test Setup
+This command will create a new directory named "yaffle" within the current directory.
-<yaml>
-# vendor/plugins/yaffle/test/database.yml
+h3. Testing your newly generated plugin
-sqlite:
- :adapter: sqlite
- :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
-
-sqlite3:
- :adapter: sqlite3
- :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
-
-postgresql:
- :adapter: postgresql
- :username: postgres
- :password: postgres
- :database: yaffle_plugin_test
- :min_messages: ERROR
-
-mysql:
- :adapter: mysql
- :host: localhost
- :username: root
- :password: password
- :database: yaffle_plugin_test
-</yaml>
-
-For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
-
-<ruby>
-# vendor/plugins/yaffle/test/schema.rb
-
-ActiveRecord::Schema.define(:version => 0) do
- create_table :hickwalls, :force => true do |t|
- t.string :name
- t.string :last_squawk
- t.datetime :last_squawked_at
- end
- create_table :wickwalls, :force => true do |t|
- t.string :name
- t.string :last_tweet
- t.datetime :last_tweeted_at
- end
- create_table :woodpeckers, :force => true do |t|
- t.string :name
- end
-end
-</ruby>
-
-<ruby>
-# vendor/plugins/yaffle/test/test_helper.rb
-
-ENV['RAILS_ENV'] = 'test'
-ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
-
-require 'test/unit'
-require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
-
-def load_schema
- config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
- ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
-
- db_adapter = ENV['DB']
-
- # no db passed, try one of these fine config-free DBs before bombing.
- db_adapter ||=
- begin
- require 'rubygems'
- require 'sqlite'
- 'sqlite'
- rescue MissingSourceFile
- begin
- require 'sqlite3'
- 'sqlite3'
- rescue MissingSourceFile
- end
- end
-
- if db_adapter.nil?
- raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
- end
-
- ActiveRecord::Base.establish_connection(config[db_adapter])
- load(File.dirname(__FILE__) + "/schema.rb")
- require File.dirname(__FILE__) + '/../rails/init'
-end
-</ruby>
-
-Now whenever you write a test that requires the database, you can call 'load_schema'.
-
-h4. Run the Plugin Tests
-
-Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in +vendor/plugins/yaffle/test/yaffle_test.rb+ with a sample test. Replace the contents of that file with:
-
-<ruby>
-# vendor/plugins/yaffle/test/yaffle_test.rb
-
-require File.dirname(__FILE__) + '/test_helper'
-
-class YaffleTest < Test::Unit::TestCase
- load_schema
-
- class Hickwall < ActiveRecord::Base
- end
-
- class Wickwall < ActiveRecord::Base
- end
-
- def test_schema_has_loaded_correctly
- assert_equal [], Hickwall.all
- assert_equal [], Wickwall.all
- end
-
-end
-</ruby>
-
-To run this, go to the plugin directory and run +rake+:
-
-<shell>
-cd vendor/plugins/yaffle
-rake
-</shell>
+You can navigate to the directory that contains the plugin, run the +bundle install+ command
+ and run the one generated test using the +rake+ command.
-You should see output like:
+You should see:
<shell>
-/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
- create_table(:hickwalls, {:force=>true})
- -> 0.0220s
--- create_table(:wickwalls, {:force=>true})
- -> 0.0077s
--- initialize_schema_migrations_table()
- -> 0.0007s
--- assume_migrated_upto_version(0)
- -> 0.0007s
-Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
-Started
-.
-Finished in 0.002236 seconds.
-
-1 test, 1 assertion, 0 failures, 0 errors
+ 2 tests, 2 assertions, 0 failures, 0 errors, 0 skips
</shell>
-By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake:
-
-<shell>
-rake DB=sqlite
-rake DB=sqlite3
-rake DB=mysql
-rake DB=postgresql
-</shell>
-
-Now you are ready to test-drive your plugin!
+This will tell you that everything got generated properly and you are ready to start adding functionality.
h3. Extending Core Classes
-This section will explain how to add a method to String that will be available anywhere in your rails app.
+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>
-# vendor/plugins/yaffle/test/core_ext_test.rb
+# yaffle/test/core_ext_test.rb
-require File.dirname(__FILE__) + '/test_helper'
+require 'test_helper'
class CoreExtTest < Test::Unit::TestCase
def test_to_squawk_prepends_the_word_squawk
@@ -293,20 +83,13 @@ class CoreExtTest < Test::Unit::TestCase
end
</ruby>
-Navigate to your plugin directory and run +rake test+:
+Run +rake+ to run the test. This test should fail because we haven't implemented the +to_squak+ method:
<shell>
-cd vendor/plugins/yaffle
-rake test
-</shell>
-
-The test above should fail with the message:
-
-<shell>
- 1) Error:
-test_to_squawk_prepends_the_word_squawk(CoreExtTest):
-NoMethodError: undefined method `to_squawk' for "Hello World":String
- ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
+ 1) Error:
+ test_to_squawk_prepends_the_word_squawk(CoreExtTest):
+ NoMethodError: undefined method `to_squawk' for "Hello World":String
+ test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
</shell>
Great - now you are ready to start development.
@@ -314,16 +97,19 @@ Great - now you are ready to start development.
Then in +lib/yaffle.rb+ require +lib/core_ext+:
<ruby>
-# vendor/plugins/yaffle/lib/yaffle.rb
+# yaffle/lib/yaffle.rb
require "yaffle/core_ext"
+
+module Yaffle
+end
</ruby>
Finally, create the +core_ext.rb+ file and add the +to_squawk+ method:
<ruby>
-# vendor/plugins/yaffle/lib/yaffle/core_ext.rb
-
+# yaffle/lib/yaffle/core_ext.rb
+
String.class_eval do
def to_squawk
"squawk! #{self}".strip
@@ -331,7 +117,13 @@ String.class_eval do
end
</ruby>
-To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory. To see this in action, fire up a console and start squawking:
+To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory.
+
+<shell>
+ 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
+</shell>
+
+To see this in action, change to the test/dummy directory, fire up a console and start squawking:
<shell>
$ rails console
@@ -339,115 +131,56 @@ $ rails console
=> "squawk! Hello World"
</shell>
-h4. Working with +init.rb+
-
-When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior.
-
-NOTE: The plugins loader also looks for +rails/init.rb+, but that one is deprecated in favor of the top-level +init.rb+ aforementioned.
-
-Under certain circumstances if you reopen classes or modules in +init.rb+ you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from +init.rb+, as shown above.
-
-If you must reopen a class in +init.rb+ you can use +module_eval+ or +class_eval+ to avoid any issues:
-
-<ruby>
-# vendor/plugins/yaffle/init.rb
-
-Hash.class_eval do
- def is_a_special_hash?
- true
- end
-end
-</ruby>
-
-Another way is to explicitly define the top-level module space for all modules and classes, like +::Hash+:
-
-<ruby>
-# vendor/plugins/yaffle/init.rb
-
-class ::Hash
- def is_a_special_hash?
- true
- end
-end
-</ruby>
-
h3. Add an "acts_as" Method to Active Record
-A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
+A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you
+want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your Active Record models.
To begin, set up your files so that you have:
-* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
-
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
+# yaffle/test/acts_as_yaffle_test.rb
+
+require 'test_helper'
class ActsAsYaffleTest < Test::Unit::TestCase
end
</ruby>
-* *vendor/plugins/yaffle/lib/yaffle.rb*
-
<ruby>
-require 'yaffle/acts_as_yaffle'
-</ruby>
+# yaffle/lib/yaffle.rb
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+require "yaffle/core_ext"
+require 'yaffle/acts_as_yaffle'
-<ruby>
module Yaffle
- # your code will go here
end
</ruby>
-Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.
-
-One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so:
-
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
-
<ruby>
-module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
-
- module ClassMethods
- # any method placed here will apply to classes, like Hickwall
- def acts_as_something
- send :include, InstanceMethods
- end
- end
+# yaffle/lib/yaffle/acts_as_yaffle.rb
- module InstanceMethods
- # any method placed here will apply to instaces, like @hickwall
+module Yaffle
+ module ActsAsYaffle
+ # your code will go here
end
end
</ruby>
-With structure you can easily separate the methods that will be used for the class (like +Hickwall.some_method+) and the instance (like +@hickwell.some_method+).
-
h4. Add a Class Method
-This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
+This plugin will expect that you've added a method to your model named 'last_squawk'. However, the
+plugin users might have already defined a method on their model named 'last_squawk' that they use
+for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
To start out, write a failing test that shows the behavior you'd like:
-* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
-
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle
-end
+# yaffle/test/acts_as_yaffle_test.rb
-class Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_tweet
-end
+require 'test_helper'
class ActsAsYaffleTest < Test::Unit::TestCase
- load_schema
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
@@ -456,1060 +189,281 @@ class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
+
end
</ruby>
-To make these tests pass, you could modify your +acts_as_yaffle+ file like so:
+When you run +rake+, you should see the following:
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+<shell>
+ 1) Error:
+ test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
+ NameError: uninitialized constant ActsAsYaffleTest::Hickwall
+ test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
-<ruby>
-module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
+ 2) Error:
+ test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
+ NameError: uninitialized constant ActsAsYaffleTest::Wickwall
+ test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- end
- end
-end
+ 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
+</shell>
-ActiveRecord::Base.send :include, Yaffle
-</ruby>
+This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test.
+We can easily generate these models in our "dummy" Rails application by running the following commands from the
+test/dummy directory:
-h4. Add an Instance Method
+<shell>
+$ cd test/dummy
+$ rails generate model Hickwall last_squak:string
+$ rails generate model Wickwall last_squak:string last_tweet:string
+</shell>
-This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
+Now you can create the necessary database tables in your testing database by navigating to your dummy app
+and migrating the database. First
-To start out, write a failing test that shows the behavior you'd like:
+<shell>
+$ cd test/dummy
+$ rake db:migrate
+$ rake db:test:prepare
+</shell>
-* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act
+like yaffles.
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
+# test/dummy/app/models/hickwall.rb
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
+# test/dummy/app/models/wickwall.rb
+
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet
end
-class ActsAsYaffleTest < Test::Unit::TestCase
- load_schema
-
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_squawk", Hickwall.yaffle_text_field
- end
-
- def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
- assert_equal "last_tweet", Wickwall.yaffle_text_field
- end
-
- def test_hickwalls_squawk_should_populate_last_squawk
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", hickwall.last_squawk
- end
-
- def test_wickwalls_squawk_should_populate_last_tweeted_at
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", wickwall.last_tweet
- end
-end
</ruby>
-Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this:
-
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+We will also add code to define the acts_as_yaffle method.
<ruby>
+# yaffle/lib/yaffle/acts_as_yaffle.rb
module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- send :include, InstanceMethods
+ included do
end
- end
- module InstanceMethods
- def squawk(string)
- write_attribute(self.class.yaffle_text_field, string.to_squawk)
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ # your code will go here
+ end
end
end
end
-ActiveRecord::Base.send :include, Yaffle
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
</ruby>
-NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
-
-h3. Models
-
-This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
+You can then return to the root directory (+cd ../..+) of your plugin and rerun the tests using +rake+.
<shell>
-vendor/plugins/yaffle/
-|-- lib
-| |-- app
-| | |-- controllers
-| | |-- helpers
-| | |-- models
-| | | `-- woodpecker.rb
-| | `-- views
-| |-- yaffle
-| | |-- acts_as_yaffle.rb
-| | |-- commands.rb
-| | `-- core_ext.rb
-| `-- yaffle.rb
-</shell>
-
-As always, start with a test:
-
-* *vendor/plugins/yaffle/test/woodpecker_test.rb:*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-
-class WoodpeckerTest < Test::Unit::TestCase
- load_schema
-
- def test_woodpecker
- assert_kind_of Woodpecker, Woodpecker.new
- end
-end
-</ruby>
-
-This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-%w{ models }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.load_paths << path
- ActiveSupport::Dependencies.load_once_paths.delete(path)
-end
-</ruby>
-
-Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
-
-* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
-
-<ruby>
-class Woodpecker < ActiveRecord::Base
-end
-</ruby>
-
-Finally, add the following to your plugin's 'schema.rb':
-
-* *vendor/plugins/yaffle/test/schema.rb:*
-
-<ruby>
-create_table :woodpeckers, :force => true do |t|
- t.string :name
-end
-</ruby>
-
-Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.
-
-h3. Controllers
-
-This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
-
-You can test your plugin's controller as you would test any other controller:
-
-* *vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'woodpeckers_controller'
-require 'action_controller/test_process'
-
-class WoodpeckersController; def rescue_action(e) raise e end; end
-
-class WoodpeckersControllerTest < Test::Unit::TestCase
- def setup
- @controller = WoodpeckersController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
-
- ActionController::Routing::Routes.draw do |map|
- map.resources :woodpeckers
- end
- end
-
- def test_index
- get :index
- assert_response :success
- end
-end
-</ruby>
-
-This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-%w{ models controllers }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.load_paths << path
- ActiveSupport::Dependencies.load_once_paths.delete(path)
-end
-</ruby>
-
-* *vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:*
-
-<ruby>
-class WoodpeckersController < ActionController::Base
-
- def index
- render :text => "Squawk!"
- end
-
-end
-</ruby>
+ 1) Error:
+ test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
+ NoMethodError: undefined method `yaffle_text_field' for #<Class:0x000001016661b8>
+ /Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
+ test/acts_as_yaffle_test.rb:5:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
-Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
+ 2) Error:
+ test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
+ NoMethodError: undefined method `yaffle_text_field' for #<Class:0x00000101653748>
+ Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
+ test/acts_as_yaffle_test.rb:9:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
-h3. Helpers
+ 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
-This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
-
-You can test your plugin's helper as you would test any other helper:
-
-* *vendor/plugins/yaffle/test/woodpeckers_helper_test.rb*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-include WoodpeckersHelper
-
-class WoodpeckersHelperTest < Test::Unit::TestCase
- def test_tweet
- assert_equal "Tweet! Hello", tweet("Hello")
- end
-end
-</ruby>
-
-This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-%w{ models controllers helpers }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.load_paths << path
- ActiveSupport::Dependencies.load_once_paths.delete(path)
-end
-</ruby>
-
-* *vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:*
-
-<ruby>
-module WoodpeckersHelper
-
- def tweet(text)
- "Tweet! #{text}"
- end
-
-end
-</ruby>
-
-Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.
-
-h3. Routes
-
-In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'.
-
-Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this:
+</shell>
-* *vendor/plugins/yaffle/test/routing_test.rb*
+Getting closer...now we will implement the code of the acts_as_yaffle method to make the tests pass.
<ruby>
-require "#{File.dirname(__FILE__)}/test_helper"
-
-class RoutingTest < Test::Unit::TestCase
-
- def setup
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- end
- end
-
- def test_yaffles_route
- assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
- end
+# yaffle/lib/yaffle/acts_as_yaffle.rb
- private
+module Yaffle
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
- def assert_recognition(method, path, options)
- result = ActionController::Routing::Routes.recognize_path(path, :method => method)
- assert_equal options, result
+ included do
end
-end
-</ruby>
-
-Once you see the tests fail by running 'rake', you can make them pass with:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb*
-
-<ruby>
-require "yaffle/routing"
-</ruby>
-
-* *vendor/plugins/yaffle/lib/yaffle/routing.rb*
-<ruby>
-module Yaffle #:nodoc:
- module Routing #:nodoc:
- module MapperExtensions
- def yaffles
- @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ cattr_accessor :yaffle_text_field
+ self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
end
end
end
end
-ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
-</ruby>
-
-* *config/routes.rb*
-
-<ruby>
-ActionController::Routing::Routes.draw do |map|
- map.yaffles
-end
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
</ruby>
-You can also see if your routes work by running +rake routes+ from your app directory.
-
-h3. Generators
-
-Many plugins ship with generators. When you created the plugin above, you specified the +--with-generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
-
-Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.
-
-h4. Testing Generators
-
-Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
-
- * Creates a new fake rails root directory that will serve as destination
- * Runs the generator
- * Asserts that the correct files were generated
- * Removes the fake rails root
-
-This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
-
-* *vendor/plugins/yaffle/test/definition_generator_test.rb*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'rails_generator'
-require 'rails_generator/scripts/generate'
-
-class DefinitionGeneratorTest < Test::Unit::TestCase
-
- def setup
- FileUtils.mkdir_p(fake_rails_root)
- @original_files = file_list
- end
-
- def teardown
- FileUtils.rm_r(fake_rails_root)
- end
-
- def test_generates_correct_file_name
- Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root)
- new_file = (file_list - @original_files).first
- assert_equal "definition.txt", File.basename(new_file)
- end
-
- private
-
- def fake_rails_root
- File.join(File.dirname(__FILE__), 'rails_root')
- end
-
- def file_list
- Dir.glob(File.join(fake_rails_root, "*"))
- end
-
-end
-</ruby>
-
-You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
-
-To make it pass, create the generator:
-
-* *vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb*
-
-<ruby>
-class YaffleDefinitionGenerator < Rails::Generator::Base
- def manifest
- record do |m|
- m.file "definition.txt", "definition.txt"
- end
- end
-end
-</ruby>
-
-h4. The +USAGE+ File
-
-If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
-
-Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
-
-<shell>
-rails generate
-</shell>
-
-You should see something like this:
-
-<shell>
-Installed Generators
- Plugins (vendor/plugins): yaffle_definition
- Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
-</shell>
-
-When you run +rails generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'.
-
-For this plugin, update the USAGE file could look like this:
+When you run +rake+ you should see the tests all pass:
<shell>
-Description:
- Adds a file with the definition of a Yaffle to the app's main directory
+ 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips
</shell>
-h3. Add a Custom Generator Command
-
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
-
-This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
-
-To start, add the following test method:
-
-* *vendor/plugins/yaffle/test/generator_test.rb*
-
-<ruby>
-def test_generates_definition
- Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
- definition = File.read(File.join(fake_rails_root, "definition.txt"))
- assert_match /Yaffle\:/, definition
-end
-</ruby>
-
-Run +rake+ to watch the test fail, then make the test pass add the following:
-
-* *vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
-
-<shell>
-Yaffle: A bird
-</shell>
-
-* *vendor/plugins/yaffle/lib/yaffle.rb*
-
-<ruby>
-require "yaffle/commands"
-</ruby>
-
-* *vendor/plugins/yaffle/lib/commands.rb*
-
-<ruby>
-require 'rails_generator'
-require 'rails_generator/commands'
-
-module Yaffle #:nodoc:
- module Generator #:nodoc:
- module Commands #:nodoc:
- module Create
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module Destroy
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module List
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module Update
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
- end
- end
-end
-
-Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
-Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
-Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
-Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
-</ruby>
-
-Finally, call your new method in the manifest:
-
-* *vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
-
-<ruby>
-class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
-</ruby>
-
-h3. Generator Commands
-
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
-
-This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'.
+h4. Add an Instance Method
-To start, add the following test method:
+This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk'
+method will simply set the value of one of the fields in the database.
-* *vendor/plugins/yaffle/test/route_generator_test.rb*
+To start out, write a failing test that shows the behavior you'd like:
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'rails_generator'
-require 'rails_generator/scripts/generate'
-require 'rails_generator/scripts/destroy'
+# yaffle/test/acts_as_yaffle_test.rb
+require 'test_helper'
-class RouteGeneratorTest < Test::Unit::TestCase
+class ActsAsYaffleTest < Test::Unit::TestCase
- def setup
- FileUtils.mkdir_p(File.join(fake_rails_root, "config"))
+ def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
+ assert_equal "last_squawk", Hickwall.yaffle_text_field
end
- def teardown
- FileUtils.rm_r(fake_rails_root)
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
+ assert_equal "last_tweet", Wickwall.yaffle_text_field
end
- def test_generates_route
- content = <<-END
- ActionController::Routing::Routes.draw do |map|
- map.connect ':controller/:action/:id'
- map.connect ':controller/:action/:id.:format'
- end
- END
- File.open(routes_path, 'wb') {|f| f.write(content) }
-
- Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root)
- assert_match /map\.yaffles/, File.read(routes_path)
+ def test_hickwalls_squawk_should_populate_last_squawk
+ hickwall = Hickwall.new
+ hickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", hickwall.last_squawk
end
- def test_destroys_route
- content = <<-END
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- map.connect ':controller/:action/:id'
- map.connect ':controller/:action/:id.:format'
- end
- END
- File.open(routes_path, 'wb') {|f| f.write(content) }
-
- Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root)
- assert_no_match /map\.yaffles/, File.read(routes_path)
+ def test_wickwalls_squawk_should_populate_last_tweeted_at
+ wickwall = Wickwall.new
+ wickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", wickwall.last_tweet
end
-
- private
-
- def fake_rails_root
- File.join(File.dirname(__FILE__), "rails_root")
- end
-
- def routes_path
- File.join(fake_rails_root, "config", "routes.rb")
- end
-
end
</ruby>
-Run +rake+ to watch the test fail, then make the test pass add the following:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb*
+Run the test to make sure the last two tests fail the an error that contains "NoMethodError: undefined method `squawk'",
+then update 'acts_as_yaffle.rb' to look like this:
<ruby>
-require "yaffle/commands"
-</ruby>
+# yaffle/lib/yaffle/acts_as_yaffle.rb
-* *vendor/plugins/yaffle/lib/yaffle/commands.rb*
-
-<ruby>
-require 'rails_generator'
-require 'rails_generator/commands'
-
-module Yaffle #:nodoc:
- module Generator #:nodoc:
- module Commands #:nodoc:
- module Create
- def yaffle_route
- logger.route "map.yaffle"
- look_for = 'ActionController::Routing::Routes.draw do |map|'
- unless options[:pretend]
- gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"}
- end
- end
- end
-
- module Destroy
- def yaffle_route
- logger.route "map.yaffle"
- gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, ''
- end
- end
-
- module List
- def yaffle_route
- end
- end
+module Yaffle
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
- module Update
- def yaffle_route
- end
- end
+ included do
end
- end
-end
-Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
-Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
-Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
-Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
-</ruby>
-
-* *vendor/plugins/yaffle/generators/yaffle_route/yaffle_route_generator.rb*
-
-<ruby>
-class YaffleRouteGenerator < Rails::Generator::Base
- def manifest
- record do |m|
- m.yaffle_route
- end
- end
-end
-</ruby>
-
-To see this work, type:
-
-<shell>
-rails generate yaffle_route
-rails destroy yaffle_route
-</shell>
-
-NOTE: If you haven't set up the custom route from above, 'rails destroy' will fail and you'll have to remove it manually.
-
-h3. Migrations
-
-If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.
-
-If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.
-
-Let's say you have the following migration in your plugin:
-
-* *vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:*
-
-<ruby>
-class CreateBirdhouses < ActiveRecord::Migration
- def self.up
- create_table :birdhouses, :force => true do |t|
- t.string :name
- t.timestamps
+ 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
-
- def self.down
- drop_table :birdhouses
- end
-end
-</ruby>
-
-Here are a few possibilities for how to allow developers to use your plugin migrations:
-
-h4. Create a Custom Rake Task
-
-* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake:*
-<ruby>
-namespace :db do
- namespace :migrate do
- description = "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate"
- description << "and update db/schema.rb by invoking db:schema:dump."
- description << "Target specific version with VERSION=x. Turn off output with VERBOSE=false."
-
- desc description
- task :yaffle => :environment do
- ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
- ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
- Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
+ def squawk(string)
+ write_attribute(self.class.yaffle_text_field, string.to_squawk)
end
- end
-end
-</ruby>
-
-h4. Call Migrations Directly
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
- require file
-end
-</ruby>
-
-* *db/migrate/20081116181115_create_birdhouses.rb:*
-
-<ruby>
-class CreateBirdhouses < ActiveRecord::Migration
- def self.up
- Yaffle::CreateBirdhouses.up
- end
-
- def self.down
- Yaffle::CreateBirdhouses.down
- end
-end
-</ruby>
-
-NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
-
-h4. Generate Migrations
-
-Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
-
- * call your rails generate script and pass in whatever options they need
- * examine the generated migration, adding/removing columns or other options as necessary
-
-This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
-
-* *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'rails_generator'
-require 'rails_generator/scripts/generate'
-class MigrationGeneratorTest < Test::Unit::TestCase
-
- def setup
- FileUtils.mkdir_p(fake_rails_root)
- @original_files = file_list
- end
-
- def teardown
- ActiveRecord::Base.pluralize_table_names = true
- FileUtils.rm_r(fake_rails_root)
- end
-
- def test_generates_correct_file_name
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
- :destination => fake_rails_root)
- new_file = (file_list - @original_files).first
- assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file
- assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file)
end
-
- def test_pluralizes_properly
- ActiveRecord::Base.pluralize_table_names = false
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
- :destination => fake_rails_root)
- new_file = (file_list - @original_files).first
- assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file
- assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file)
- end
-
- private
- def fake_rails_root
- File.join(File.dirname(__FILE__), 'rails_root')
- end
-
- def file_list
- Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
- end
-
end
-</ruby>
-NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.
-
-After running the test with 'rake' you can make it pass with:
-
-* *vendor/plugins/yaffle/generators/yaffle_migration/yaffle_migration_generator.rb*
-
-<ruby>
-class YaffleMigrationGenerator < Rails::Generator::NamedBase
- def manifest
- record do |m|
- m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
- :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
- }
- end
- end
-
- private
- def custom_file_name
- custom_name = class_name.underscore.downcase
- custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
- custom_name
- end
-
- def yaffle_local_assigns
- {}.tap do |assigns|
- assigns[:migration_action] = "add"
- assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
- assigns[:table_name] = custom_file_name
- assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
- end
- end
-end
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
</ruby>
-The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in rails +migration_template+ method, and reuses the built-in rails migration template.
-
-It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
-
-To run the generator, type the following at the command line:
-
+Run +rake+ one final time and you should see:
<shell>
-rails generate yaffle_migration bird
+ 7 tests, 7 assertions, 0 failures, 0 errors, 0 skips
</shell>
-and you will see a new file:
-
-* *db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
-
-<ruby>
-class AddYaffleFieldsToBirds < ActiveRecord::Migration
- def self.up
- add_column :birds, :last_squawk, :string
- end
-
- def self.down
- remove_column :birds, :last_squawk
- end
-end
-</ruby>
+NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can
+interact with the model, and will not always be the right method to use. For example, you could also
+use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
-h3. Rake tasks
+h3. Generators
-When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app.
+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
-Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
+h3. Publishing your Gem
-* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake*
+Gem plugins in progress can be easily be shared from any Git repository. To share the Yaffle gem with others, simply
+commit the code to a Git repository (like Github) and add a line to the Gemfile of the any application:
<ruby>
-namespace :yaffle do
- desc "Prints out the word 'Yaffle'"
- task :squawk => :environment do
- puts "squawk!"
- end
-end
+gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
</ruby>
-When you run +rake -T+ from your plugin you will see:
-
-<shell>
-yaffle:squawk # Prints out the word 'Yaffle'
-</shell>
+After running +bundle install+, your gem functionality will be available to the application.
-You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
+When the gem is ready to be shared as a formal release, it can be published to "RubyGems":http://www.rubygems.org.
+For more information about publishing gems to RubyGems, see: "http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html
-Note that tasks from +vendor/plugins/yaffle/Rakefile+ are not available to the main app.
+h3. Non-Gem Plugins
-h3. Plugins as Gems
+Non-gem plugins are useful for functionality that won't be shared with another project. Keeping your custom functionality in the
+vendor/plugins directory un-clutters the rest of the application.
-Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.
-
-The initialization file has to be called +rails/init.rb+, the root +init.rb+ file, if any, is ignored by Rails. Also, the name of the plugin now is relevant since +config.gem+ tries to load it. Either name the main file after your gem, or document that users should use the +:lib+ option.
-
-It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this:
-
-* *vendor/plugins/yaffle/Rakefile:*
+Move the directory that you created for the gem based plugin into the vendor/plugins directory of a generated Rails application, create a vendor/plugins/yaffle/init.rb file that contains "require 'yaffle'" and everything will still work.
<ruby>
-PKG_FILES = FileList[
- '[a-zA-Z]*',
- 'generators/**/*',
- 'lib/**/*',
- 'rails/**/*',
- 'tasks/**/*',
- 'test/**/*'
-]
-
-spec = Gem::Specification.new do |s|
- s.name = "yaffle"
- s.version = "0.0.1"
- s.author = "Gleeful Yaffler"
- s.email = "yaffle@example.com"
- s.homepage = "http://yafflers.example.com/"
- s.platform = Gem::Platform::RUBY
- s.summary = "Sharing Yaffle Goodness"
- s.files = PKG_FILES.to_a
- s.require_path = "lib"
- s.has_rdoc = false
- s.extra_rdoc_files = ["README"]
-end
+# yaffle/init.rb
-desc 'Turn this plugin into a gem.'
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.gem_spec = spec
-end
+require 'yaffle'
</ruby>
-To build and install the gem locally, run the following commands:
-
+You can test this by changing to the Rails application that you added the plugin to and starting a rails console. Once in the
+console we can check to see if the String has an instance method of to_squawk.
<shell>
-cd vendor/plugins/yaffle
-rake gem
-sudo gem install pkg/yaffle-0.0.1.gem
+$ cd my_app
+$ rails console
+$ String.instance_methods.sort
</shell>
-To test this, create a new rails app, add +config.gem "yaffle"+ to +config/environment.rb+ and all of your plugin's functionality will be available to you.
+You can also remove the .gemspec, Gemfile and Gemfile.lock files as they will no longer be needed.
h3. RDoc Documentation
Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
-The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
* Your name
* How to install
* How to add the functionality to the app (several examples of common use cases)
* Warning, gotchas or tips that might help save users time
-Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api.
+Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api.
Once your comments are good to go, navigate to your plugin directory and run:
<shell>
-rake rdoc
+$ rake rdoc
</shell>
-h3. Appendix
-
-If you prefer to use RSpec instead of Test::Unit, you may be interested in the "RSpec Plugin Generator":http://github.com/patmaddox/rspec-plugin-generator.
-
h4. References
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii
-* http://github.com/technoweenie/attachment_fu/tree/master
-* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
-* http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
-* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
-
-h4. Contents of +lib/yaffle.rb+
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-require "yaffle/core_ext"
-require "yaffle/acts_as_yaffle"
-require "yaffle/commands"
-require "yaffle/routing"
-
-%w{ models controllers helpers }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.load_paths << path
- ActiveSupport::Dependencies.load_once_paths.delete(path)
-end
-
-# optionally:
-# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
-# require file
-# end
-</ruby>
-
-h4. Final Plugin Directory Structure
-
-The final plugin should have a directory structure that looks something like this:
-
-<shell>
-|-- MIT-LICENSE
-|-- README
-|-- Rakefile
-|-- generators
-| |-- yaffle_definition
-| | |-- USAGE
-| | |-- templates
-| | | `-- definition.txt
-| | `-- yaffle_definition_generator.rb
-| |-- yaffle_migration
-| | |-- USAGE
-| | |-- templates
-| | `-- yaffle_migration_generator.rb
-| `-- yaffle_route
-| |-- USAGE
-| |-- templates
-| `-- yaffle_route_generator.rb
-|-- install.rb
-|-- lib
-| |-- app
-| | |-- controllers
-| | | `-- woodpeckers_controller.rb
-| | |-- helpers
-| | | `-- woodpeckers_helper.rb
-| | `-- models
-| | `-- woodpecker.rb
-| |-- db
-| | `-- migrate
-| | `-- 20081116181115_create_birdhouses.rb
-| |-- yaffle
-| | |-- acts_as_yaffle.rb
-| | |-- commands.rb
-| | |-- core_ext.rb
-| | `-- routing.rb
-| `-- yaffle.rb
-|-- pkg
-| `-- yaffle-0.0.1.gem
-|-- rails
-| `-- init.rb
-|-- tasks
-| `-- yaffle_tasks.rake
-|-- test
-| |-- acts_as_yaffle_test.rb
-| |-- core_ext_test.rb
-| |-- database.yml
-| |-- debug.log
-| |-- definition_generator_test.rb
-| |-- migration_generator_test.rb
-| |-- route_generator_test.rb
-| |-- routes_test.rb
-| |-- schema.rb
-| |-- test_helper.rb
-| |-- woodpecker_test.rb
-| |-- woodpeckers_controller_test.rb
-| |-- wookpeckers_helper_test.rb
-| |-- yaffle_plugin.sqlite3.db
-| `-- yaffle_test.rb
-`-- uninstall.rb
-</shell>
+* "Developing a RubyGem using Bundler":https://github.com/radar/guides/blob/master/gem-development.md
+* "Using Gemspecs As Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/
+* "Gemspec Reference":http://docs.rubygems.org/read/chapter/20
+* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
+* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/32-update-plugins-guide
-
+* March 10, 2011: Minor formatting tweaks.
+* February 13, 2011: Get guide in synch with Rails 3.0.3. Remove information not compatible with Rails 3. Send reader elsewhere
+for information that is covered elsewhere.
* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* November 17, 2008: Major revision by Jeff Dean
diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile
index 1bf9cfec33..8e51f9e23b 100644
--- a/railties/guides/source/rails_application_templates.textile
+++ b/railties/guides/source/rails_application_templates.textile
@@ -20,7 +20,7 @@ $ rails new blog -m ~/template.rb
It's also possible to apply a template using a URL :
<shell>
-$ rails new blog -m http://gist.github.com/31208.txt
+$ rails new blog -m https://gist.github.com/755496.txt
</shell>
Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application :
@@ -37,7 +37,7 @@ Rails templates API is very self explanatory and easy to understand. Here's an e
# template.rb
run "rm public/index.html"
generate(:scaffold, "person name:string")
-route "map.root :controller => 'people'"
+route "root :to => 'people#index'"
rake("db:migrate")
git :init
@@ -49,7 +49,7 @@ The following sections outlines the primary methods provided by the API :
h4. gem(name, options = {})
-Adds a +config.gem+ entry for the supplied gem to the generated application’s +config/environment.rb+.
+Adds a +gem+ entry for the supplied gem to the generated application’s +Gemfile+.
For example, if your application depends on the gems +bj+ and +nokogiri+ :
@@ -66,6 +66,16 @@ rake "gems:install"
And let Rails take care of installing the required gems if they’re not already installed.
+h4. add_source(source, options = {})
+
+Adds the given source to the generated application's +Gemfile+.
+
+For example, if you need to source a gem from "http://code.whytheluckystiff.net":
+
+<ruby>
+add_source "http://code.whytheluckystiff.net"
+</ruby>
+
h4. plugin(name, options = {})
Installs a plugin to the generated application.
@@ -79,7 +89,7 @@ plugin 'authentication', :git => 'git://github.com/foor/bar.git'
You can even install plugins as git submodules :
<ruby>
-plugin 'authentication', :git => 'git://github.com/foor/bar.git',
+plugin 'authentication', :git => 'git://github.com/foor/bar.git',
:submodule => true
</ruby>
@@ -103,7 +113,7 @@ class Object
def not_nil?
!nil?
end
-
+
def not_blank?
!blank?
end
@@ -183,12 +193,12 @@ h4. route(routing_code)
This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application :
<ruby>
-route "map.root :controller => :person"
+route "root :to => 'person#index'"
</ruby>
h4. inside(dir)
-I have my edge rails lying at +~/commit-rails/rails+. So every time i have to manually symlink edge from my new app. But now :
+Enables you to run a command from the given directory. For example, if you have a copy of edge rails that you wish to symlink from your new apps, you can do this:
<ruby>
inside('vendor') do
@@ -196,8 +206,6 @@ inside('vendor') do
end
</ruby>
-So +inside()+ runs the command from the given directory.
-
h4. ask(question)
+ask()+ gives you a chance to get some feedback from the user and use it in your templates. Lets say you want your user to name the new shiny library you’re adding :
@@ -233,6 +241,4 @@ git :commit => "-a -m 'Initial commit'"
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/78
-
* April 29, 2009: Initial version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index eaebb05f17..b1db2942dd 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -17,12 +17,7 @@ bq. Rack provides a minimal, modular and adaptable interface for developing web
- "Rack API Documentation":http://rack.rubyforge.org/doc/
-Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the following links:
-
-* "Official Rack Website":http://rack.github.com
-* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder
+Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below.
h3. Rails on Rack
@@ -68,13 +63,13 @@ run ActionController::Dispatcher.new
And start the server:
<shell>
-[lifo@null application]$ rackup config.ru
+$ rackup config.ru
</shell>
To find out more about different +rackup+ options:
<shell>
-[lifo@null application]$ rackup --help
+$ rackup --help
</shell>
h3. Action Controller Middleware Stack
@@ -165,7 +160,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
|_.Middleware|_.Purpose|
|+Rack::Lock+|Sets +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.|
|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.|
-|+ActiveRecord::QueryCache+|Enable the Active Record query cache.|
+|+ActiveRecord::QueryCache+|Enables the Active Record query cache.|
|+ActionController::Session::CookieStore+|Uses the cookie based session store.|
|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.|
|+ActiveRecord::SessionStore+|Uses the database based session store.|
@@ -228,8 +223,8 @@ h4. Learning Rack
* "Official Rack Website":http://rack.github.com
* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder
+* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack
+* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder
h4. Understanding Middlewares
@@ -237,7 +232,5 @@ h4. Understanding Middlewares
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/58
-
* February 7, 2009: Second version by "Pratik":credits.html#lifo
* January 11, 2009: First version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 625941ba31..c447fd911a 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -3,7 +3,7 @@ h2. Rails Routing from the Outside In
This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to:
* Understand the code in +routes.rb+
-* Construct your own routes, using either the preferred resourceful style or with the <tt>match</tt> method
+* Construct your own routes, using either the preferred resourceful style or the <tt>match</tt> method
* Identify what parameters to expect an action to receive
* Automatically create paths and URLs using route helpers
* Use advanced techniques such as constraints and Rack endpoints
@@ -39,10 +39,10 @@ You can also generate paths and URLs. If your application contains this code:
</ruby>
<erb>
-<%= link_to "Patient Record", patients_path(@patient.id) %>
+<%= link_to "Patient Record", patient_path(@patient) %>
</erb>
-The router will generate the path +/patients/17+. This reduces the brittleness of your view and makes your code easier to understand.
+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.
h3. Resource Routing: the Rails Default
@@ -50,7 +50,7 @@ Resource routing allows you to quickly declare all of the common routes for a gi
h4. 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+, +PUT+ and +DELETE+. Each method is a request to perform an operation on the resource. A resource route maps a number of related request to the actions in a single controller.
+Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as +GET+, +POST+, +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
@@ -76,14 +76,17 @@ resources :photos
creates seven different routes in your application, all mapping to the +Photos+ controller:
-|_. 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|
-|PUT |/photos/:id |update |update a specific photo|
-|DELETE |/photos/:id |destroy |delete a specific photo|
+|_. 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 |
+|PUT |/photos/:id |update |update a specific photo |
+|DELETE |/photos/:id |destroy |delete a specific photo |
+
+
+NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first.
h4. Paths and URLs
@@ -91,7 +94,7 @@ Creating a resourceful route will also expose a number of helpers to the control
* +photos_path+ returns +/photos+
* +new_photo_path+ returns +/photos/new+
-* +edit_photo_path+ returns +/photos/edit+
+* +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.
@@ -116,7 +119,7 @@ resources :videos
h4. Singular Resources
-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.
+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>
match "profile" => "users#show"
@@ -130,13 +133,13 @@ resource :geocoder
creates six different routes in your application, all mapping to the +Geocoders+ controller:
-|_. 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|
-|PUT |/geocoder |update |update the one and only geocoder resource|
-|DELETE |/geocoder |destroy |delete the geocoder resource|
+|_.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 |
+|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.
@@ -153,23 +156,23 @@ h4. 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
+namespace :admin do
resources :posts, :comments
end
</ruby>
This will create a number of routes for each of the +posts+ and +comments+ controller. For +Admin::PostsController+, Rails will create:
-|_. Verb |_.Path |_.action |_. helper |
-|GET |/admin/photos |index | admin_photos_path |
-|GET |/admin/photos/new |new | new_admin_photos_path |
-|POST |/admin/photos |create | admin_photos_path |
-|GET |/admin/photos/1 |show | admin_photo_path(id) |
-|GET |/admin/photos/1/edit |edit | edit_admin_photo_path(id) |
-|PUT |/admin/photos/1 |update | admin_photo_path(id) |
-|DELETE |/admin/photos/1 |destroy | admin_photo_path(id) |
+|_.HTTP Verb |_.Path |_.action |_.named helper |
+|GET |/admin/posts |index | admin_posts_path |
+|GET |/admin/posts/new |new | new_admin_posts_path |
+|POST |/admin/posts |create | admin_posts_path |
+|GET |/admin/posts/1 |show | admin_post_path(id) |
+|GET |/admin/posts/1/edit |edit | edit_admin_post_path(id) |
+|PUT |/admin/posts/1 |update | admin_post_path(id) |
+|DELETE |/admin/posts/1 |destroy | admin_post_path(id) |
-If you want to route +/photos+ (without the prefix +/admin+) to +Admin::PostsController+, you could use
+If you want to route +/posts+ (without the prefix +/admin+) to +Admin::PostsController+, you could use
<ruby>
scope :module => "admin" do
@@ -183,7 +186,7 @@ or, for a single case
resources :posts, :module => "admin"
</ruby>
-If you want to route +/admin/photos+ to +PostsController+ (without the +Admin::+ module prefix), you could use
+If you want to route +/admin/posts+ to +PostsController+ (without the +Admin::+ module prefix), you could use
<ruby>
scope "/admin" do
@@ -194,19 +197,19 @@ end
or, for a single case
<ruby>
-resources :posts, :path => "/admin"
+resources :posts, :path => "/admin/posts"
</ruby>
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+:
-|_. Verb |_.Path |_.action |_. helper |
-|GET |/admin/photos |index | photos_path |
-|GET |/admin/photos/new |new | photos_path |
-|POST |/admin/photos |create | photos_path |
-|GET |/admin/photos/1 |show | photo_path(id) |
-|GET |/admin/photos/1/edit |edit | edit_photo_path(id) |
-|PUT |/admin/photos/1 |update | photo_path(id) |
-|DELETE |/admin/photos/1 |destroy | photo_path(id) |
+|_.HTTP Verb |_.Path |_.action |_.named helper |
+|GET |/admin/posts |index | posts_path |
+|GET |/admin/posts/new |new | posts_path |
+|POST |/admin/posts |create | posts_path |
+|GET |/admin/posts/1 |show | post_path(id) |
+|GET |/admin/posts/1/edit |edit | edit_post_path(id) |
+|PUT |/admin/posts/1 |update | post_path(id) |
+|DELETE |/admin/posts/1 |destroy | post_path(id) |
h4. Nested Resources
@@ -232,14 +235,14 @@ end
In addition to the routes for magazines, this declaration will also route ads to an +AdsController+. The ad URLs require a magazine:
-|_.Verb |_.Path |_.action |_.used for|
-|GET |/magazines/1/ads |index |display a list of all ads for a specific magazine|
-|GET |/magazines/1/ads/new |new |return an HTML form for creating a new ad belonging to a specific magazine|
-|POST |/magazines/1/ads |create |create a new ad belonging to a specific magazine|
-|GET |/magazines/1/ads/1 |show |display a specific ad belonging to a specific magazine|
-|GET |/magazines/1/ads/1/edit |edit |return an HTML form for editing an ad belonging to a specific magazine|
-|PUT |/magazines/1/ads/1 |update |update a specific ad belonging to a specific magazine|
-|DELETE |/magazines/1/ads/1 |destroy |delete a specific ad belonging to a specific magazine|
+|_.HTTP Verb |_.Path |_.action |_.used for |
+|GET |/magazines/1/ads |index |display a list of all ads for a specific magazine |
+|GET |/magazines/1/ads/new |new |return an HTML form for creating a new ad belonging to a specific magazine |
+|POST |/magazines/1/ads |create |create a new ad belonging to a specific magazine |
+|GET |/magazines/1/ads/1 |show |display a specific ad belonging to a specific magazine |
+|GET |/magazines/1/ads/1/edit |edit |return an HTML form for editing an ad belonging to a specific magazine |
+|PUT |/magazines/1/ads/1 |update |update a specific ad belonging to a specific magazine |
+|DELETE |/magazines/1/ads/1 |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)+).
@@ -313,7 +316,7 @@ To add a member route, just add a +member+ block into the resource block:
<ruby>
resources :photos do
member do
- get :preview
+ get 'preview'
end
end
</ruby>
@@ -324,7 +327,7 @@ Within the block of member routes, each route name specifies the HTTP verb that
<ruby>
resources :photos do
- get :preview, :on => :member
+ get 'preview', :on => :member
end
</ruby>
@@ -335,7 +338,7 @@ To add a route to the collection:
<ruby>
resources :photos do
collection do
- get :search
+ get 'search'
end
end
</ruby>
@@ -346,7 +349,7 @@ Just as with member routes, you can pass +:on+ to a route:
<ruby>
resources :photos do
- get :search, :on => :collection
+ get 'search', :on => :collection
end
</ruby>
@@ -370,7 +373,7 @@ When you set up a regular route, you supply a series of symbols that Rails maps
match ':controller(/:action(/:id))'
</ruby>
-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+, since +:action+ and +:id+ are optional parameters, denoted by parentheses.
+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.
h4. Dynamic Segments
@@ -388,6 +391,8 @@ NOTE: You can't use +namespace+ or +:module+ with a +:controller+ path segment.
match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/
</ruby>
+TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this - for example +:id => /[^\/]<plus>/+ allows anything except a slash.
+
h4. Static Segments
You can specify static segments when creating a route:
@@ -434,7 +439,27 @@ You can specify a name for any route using the +:as+ option.
match 'exit' => 'sessions#destroy', :as => :logout
</ruby>
-This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/logout+
+This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/exit+
+
+h4. HTTP Verb Constraints
+
+You can use the +:via+ option to constrain the request to one or more HTTP methods:
+
+<ruby>
+match 'photos/show' => 'photos#show', :via => :get
+</ruby>
+
+There is a shorthand version of this as well:
+
+<ruby>
+get 'photos/show'
+</ruby>
+
+You can also permit more than one verb to a single route:
+
+<ruby>
+match 'photos/show' => 'photos#show', :via => [:get, :post]
+</ruby>
h4. Segment Constraints
@@ -450,7 +475,7 @@ This route would match paths such as +/photos/A12345+. You can more succinctly e
match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
</ruby>
-+:constraints+ takes regular expression. However note that regexp anchors can't be used within constraints. For example following route will not work:
++:constraints+ takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work:
<ruby>
match '/:id' => 'posts#show', :constraints => {:id => /^\d/}
@@ -475,10 +500,10 @@ You specify a request-based constraint the same way that you specify a segment c
match "photos", :constraints => {:subdomain => "admin"}
</ruby>
-You can also specify constrains in a block form:
+You can also specify constraints in a block form:
<ruby>
-namespace "admin" do
+namespace :admin do
constraints :subdomain => "admin" do
resources :photos
end
@@ -501,7 +526,7 @@ class BlacklistConstraint
end
TwitterClone::Application.routes.draw do
- match "*path" => "blacklist#index",
+ match "*path" => "blacklist#index",
:constraints => BlacklistConstraint.new
end
</ruby>
@@ -516,6 +541,22 @@ match 'photos/*other' => 'photos#unknown'
This route would match +photos/12+ or +/photos/long/path/to/12+, setting +params[:other]+ to +"12"+ or +"long/path/to/12"+.
+Wildcard segments can occur anywhere in a route. For example,
+
+<ruby>
+match 'books/*section/:title' => 'books#show'
+</ruby>
+
+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>
+match '*a/foo/*b' => 'test#index'
+</ruby>
+
+would match +zoo/woo/foo/bar/baz+ with +params[:a]+ equals +"zoo/woo"+, and +params[:b]+ equals +"bar/baz"+.
+
h4. Redirection
You can redirect any path to another path using the +redirect+ helper in your router:
@@ -559,7 +600,7 @@ You can specify what Rails should route +"/"+ to with the +root+ method:
root :to => 'pages#main'
</ruby>
-You should put the +root+ route at the end of the file.
+You should put the +root+ route at the end of the file. You also need to delete the +public/index.html+ file for the root route to take effect.
h3. Customizing Resourceful Routes
@@ -573,16 +614,16 @@ The +:controller+ option lets you explicitly specify a controller to use for the
resources :photos, :controller => "images"
</ruby>
-will recognize incoming paths beginning with +/photo+ but route to the +Images+ controller:
+will recognize incoming paths beginning with +/photos+ but route to the +Images+ controller:
-|_. Verb |_.Path |_.action |
-|GET |/photos |index |
-|GET |/photos/new |new |
-|POST |/photos |create |
-|GET |/photos/1 |show |
-|GET |/photos/1/edit |edit |
-|PUT |/photos/1 |update |
-|DELETE |/photos/1 |destroy |
+|_.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/1 |show | photo_path(id) |
+|GET |/photos/1/edit |edit | edit_photo_path(id) |
+|PUT |/photos/1 |update | photo_path(id) |
+|DELETE |/photos/1 |destroy | photo_path(id) |
NOTE: Use +photos_path+, +new_photos_path+, etc. to generate paths for this resource.
@@ -594,7 +635,7 @@ You can use the +:constraints+ option to specify a required format on the implic
resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}
</ruby>
-This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
+This declaration constraints the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
You can specify a single constraint to apply to a number of routes by using the block form:
@@ -605,7 +646,9 @@ constraints(:id => /[A-Z][A-Z][0-9]+/) do
end
</ruby>
-NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context
+NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context.
+
+TIP: By default the +:id+ parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an +:id+ add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash.
h4. Overriding the Named Helpers
@@ -615,16 +658,16 @@ The +:as+ option lets you override the normal naming for the named route helpers
resources :photos, :as => "images"
</ruby>
-will recognize incoming paths beginning with +/photos+ and route the requests to +PhotosController+:
+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/1 |show | image_path |
-|GET |/photos/1/edit |edit | edit_image_path |
-|PUT |/photos/1 |update | image_path |
-|DELETE |/photos/1 |destroy | image_path |
+|_.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/1 |show | image_path(id) |
+|GET |/photos/1/edit |edit | edit_image_path(id) |
+|PUT |/photos/1 |update | image_path(id) |
+|DELETE |/photos/1 |destroy | image_path(id) |
h4. Overriding the +new+ and +edit+ Segments
@@ -643,7 +686,7 @@ This would cause the routing to recognize paths such as
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:
+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
@@ -665,7 +708,7 @@ resources :photos
This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc.
-To prefix a group of routes, use +:as+ with +scope+:
+To prefix a group of route helpers, use +:as+ with +scope+:
<ruby>
scope "admin", :as => "admin" do
@@ -675,11 +718,23 @@ end
resources :photos, :accounts
</ruby>
+This will generate routes such as +admin_photos_path+ and +admin_accounts_path+ which map to +/admin/photos+ and +/admin/accounts+ respectively.
+
NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes.
+You can prefix routes with a named parameter also:
+
+<ruby>
+scope ":username" do
+ resources :posts
+end
+</ruby>
+
+This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views.
+
h4. Restricting the Routes Created
-By default, Rails creates routes for all seven of the 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:
+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]
@@ -707,16 +762,16 @@ scope(:path_names => { :new => "neu", :edit => "bearbeiten" }) do
end
</ruby>
-Rails now creates routes to the +CategoriesControlleR+.
+Rails now creates routes to the +CategoriesController+.
-|_.HTTP verb|_.Path |_.action |
-|GET |/kategorien |index |
-|GET |/kategorien/neu |new |
-|POST |/kategorien |create |
-|GET |/kategorien/1 |show |
-|GET |/kategorien/:id/bearbeiten |edit |
-|PUT |/kategorien/1 |update |
-|DELETE |/kategorien/1 |destroy |
+|_.HTTP verb|_.Path |_.action |_.named helper |
+|GET |/kategorien |index | categories_path |
+|GET |/kategorien/neu |new | new_category_path |
+|POST |/kategorien |create | categories_path |
+|GET |/kategorien/1 |show | category_path(id) |
+|GET |/kategorien/1/bearbeiten |edit | edit_category_path(id) |
+|PUT |/kategorien/1 |update | category_path(id) |
+|DELETE |/kategorien/1 |destroy | category_path(id) |
h4. Overriding the Singular Form
@@ -765,14 +820,14 @@ formatted_users GET /users.:format {:controller=>"users", :action=>"index"}
You may restrict the listing to the routes that map to a particular controller setting the +CONTROLLER+ environment variable:
<shell>
-$ CONTROLLER=users rake routes
+$ CONTROLLER=users rake routes
</shell>
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.
h4. 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/ActionController/Assertions/RoutingAssertions.html designed to make testing routes simpler:
+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+
@@ -780,7 +835,7 @@ Routes should be included in your testing strategy (just like the rest of your a
h5. The +assert_generates+ Assertion
-Use +assert_generates+ to assert that a particular set of options generate a particular path. You can use this with default routes or custom routes
++assert_generates+ asserts that a particular set of options generate a particular path and can be used with default routes or custom routes.
<ruby>
assert_generates "/photos/1", { :controller => "photos", :action => "show", :id => "1" }
@@ -789,7 +844,7 @@ assert_generates "/about", :controller => "pages", :action => "about"
h5. The +assert_recognizes+ Assertion
-The +assert_recognizes+ assertion is the inverse of +assert_generates+. It asserts that Rails recognizes the given path and routes it to a particular spot in your application.
++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.
<ruby>
assert_recognizes({ :controller => "photos", :action => "show", :id => "1" }, "/photos/1")
@@ -801,12 +856,6 @@ You can supply a +:method+ argument to specify the HTTP verb:
assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post })
</ruby>
-You can also use the resourceful helpers to test recognition of a RESTful route:
-
-<ruby>
-assert_recognizes new_photo_url, { :path => "photos", :method => :post }
-</ruby>
-
h5. The +assert_routing+ Assertion
The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+.
@@ -817,8 +866,6 @@ assert_routing({ :path => "photos", :method => :post }, { :controller => "photos
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/3
-
* April 10, 2010: Updated guide to remove outdated and superfluous information, and to provide information about new features, by "Yehuda Katz":http://www.yehudakatz.com
* April 2, 2010: Updated guide to match new Routing DSL in Rails 3, by "Rizwan Reza":http://www.rizwanreza.com/
* Febuary 1, 2010: Modifies the routing documentation to match new routing DSL in Rails 3, by Prem Sichanugrist
diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
new file mode 100644
index 0000000000..6576758856
--- /dev/null
+++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
@@ -0,0 +1,83 @@
+h2. Ruby on Rails Guides Guidelines
+
+This guide documents guidelines for writing guides. This guide follows itself in a gracile loop.
+
+endprologue.
+
+h3. Textile
+
+Guides are written in "Textile":http://www.textism.com/tools/textile/. There's comprehensive documentation "here":http://redcloth.org/hobix.com/textile/ and a cheatsheet for markup "here":http://redcloth.org/hobix.com/textile/quick.html.
+
+h3. 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 readers what's the guide about, and what will they learn. See for example the "Routing Guide":routing.html.
+
+h3. Titles
+
+The title of every guide uses +h2+, guide sections use +h3+, subsections +h4+, etc.
+
+Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be:
+
+<plain>
+h5. Middleware Stack is an Array
+h5. When are Objects Saved?
+</plain>
+
+Use same typography as in regular text:
+
+<plain>
+h6. The +:content_type+ Option
+</plain>
+
+h3. API Documentation Guidelines
+
+The guides and the API should be coherent 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.
+
+h3. HTML Generation
+
+To generate all the guides just cd into the +railties+ directory and execute
+
+<plain>
+bundle exec rake generate_guides
+</plain>
+
+You'll need the gems erubis, i18n, and RedCloth.
+
+To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable:
+
+<plain>
+bundle exec rake generate_guides ONLY=my_guide
+</plain>
+
+Although by default guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice.
+
+To force process of 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 languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +LANGUAGE+ environment variable.
+
+<plain>
+rake generate_guides LANGUAGE=es
+</plain>
+
+h3. HTML Validation
+
+Please do validate the generated HTML with
+
+<plain>
+rake validate_guides
+</plain>
+
+Particularly, titles get an ID generated from their content and this often leads to duplicates. Please set +WARNINGS=1+ when generating guides to detect them. The warning messages suggest a way to fix them.
+
+h3. Changelog
+
+* October 5, 2010: ported from the docrails wiki and revised by "Xavier Noria":credits.html#fxn
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index 8ce0001080..182f3631ef 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -166,7 +166,7 @@ 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.to_s(:db)}' OR
+delete_all "updated_at < '#{time.ago.to_s(:db)}' OR
created_at < '#{2.days.ago.to_s(:db)}'"
</ruby>
@@ -240,7 +240,7 @@ There are many other possibilities, including Ajax to attack the victim in the b
protect_from_forgery :secret => "123456789012345678901234567890..."
</ruby>
-This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. It will raise an ActionController::InvalidAuthenticityToken error, if the security token doesn't match what was expected.
+This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. *Note:* In Rails versions prior to 3.0.4, this raised an <tt>ActionController::InvalidAuthenticityToken</tt> error.
Note that _(highlight)cross-site scripting (XSS) vulnerabilities bypass all CSRF protections_. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read <a href="#cross-site-scripting-xss">more about XSS</a> later.
@@ -282,7 +282,7 @@ h4. File Uploads
Many web applications allow users to upload files. _(highlight)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 other programs as a less privileged Unix user.
-When filtering user input file names, _(highlight)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 _(highlight)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 replace not accepted characters), but don't remove them. Here is the file name sanitizer from the "attachment_fu plugin":http://github.com/technoweenie/attachment_fu/tree/master:
+When filtering user input file names, _(highlight)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 _(highlight)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 replace not accepted characters), but don't remove them. Here is the file name sanitizer from the "attachment_fu plugin":https://github.com/technoweenie/attachment_fu/tree/master:
<ruby>
def sanitize_filename(filename)
@@ -371,7 +371,7 @@ The mass-assignment feature may become a problem, as it allows an attacker to se
<ruby>
def signup
- params[:user] #=> {:name => “ow3ned”, :admin => true}
+ params[:user] # => {:name => “ow3ned”, :admin => true}
@user = User.new(params[:user])
end
</ruby>
@@ -385,7 +385,7 @@ Mass-assignment saves you much work, because you don't have to set each value in
This will set the following parameters in the controller:
<ruby>
-params[:user] #=> {:name => “ow3ned”, :admin => true}
+params[:user] # => {:name => “ow3ned”, :admin => true}
</ruby>
So if you create a new user using mass-assignment, it may be too easy to become an administrator.
@@ -401,7 +401,7 @@ Note that this vulnerability is not restricted to database columns. Any setter
class Child < ActiveRecord::Base
belongs_to :person
- end
+ end
</ruby>
As a result, the vulnerability is extended beyond simply exposing column assignment, allowing attackers the ability to create entirely new records in referenced tables (children in this case).
@@ -423,11 +423,11 @@ attr_accessible :name
If you want to set a protected attribute, you will to have to assign it individually:
<ruby>
-params[:user] #=> {:name => "ow3ned", :admin => true}
+params[:user] # => {:name => "ow3ned", :admin => true}
@user = User.new(params[:user])
-@user.admin #=> false # not mass-assigned
+@user.admin # => false # not mass-assigned
@user.admin = true
-@user.admin #=> true
+@user.admin # => true
</ruby>
A more paranoid technique to protect your whole project would be to enforce that all models whitelist their accessible attributes. This can be easily achieved with a very simple initializer:
@@ -524,10 +524,10 @@ h4. Logging
-- _Tell Rails not to put passwords in the log files._
-By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by the filter_parameter_logging method in a controller. These parameters will be marked [FILTERED] in the log.
+By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
<ruby>
-filter_parameter_logging :password
+config.filter_parameters << :password
</ruby>
h4. Good Passwords
@@ -550,7 +550,7 @@ Ruby uses a slightly different approach than many other languages to match the e
<ruby>
class File < ActiveRecord::Base
- validates_format_of :name, :with => /^[\w\.\-\+]+$/
+ validates :name, :format => /^[\w\.\-\+]+$/
end
</ruby>
@@ -616,7 +616,7 @@ h5(#sql-injection-introduction). Introduction
SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be:
@@ -632,7 +632,7 @@ h5. Bypassing Authorization
Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.
<ruby>
-User.find(:first, "login = '#{params[:name]}' AND password = '#{params[:password]}'")
+User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
</ruby>
If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be:
@@ -648,7 +648,7 @@ h5. Unauthorized Reading
The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
And now let's inject another query using the UNION statement:
@@ -675,13 +675,13 @@ Ruby on Rails has a built-in filter for special SQL characters, which will escap
Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:
<ruby>
-Model.find(:first, :conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
+Model.first(:conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
</ruby>
As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:
<ruby>
-Model.find(:first, :conditions => {:login => entered_user_name, :password => entered_password})
+Model.first(:conditions => {:login => entered_user_name, :password => entered_password})
</ruby>
The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_.
@@ -979,6 +979,4 @@ The security landscape shifts and it is important to keep up to date, because mi
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/7
-
* November 1, 2008: First approved version by Heiko Webers
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
index 69695c93c8..4ebdb3edf6 100644
--- a/railties/guides/source/testing.textile
+++ b/railties/guides/source/testing.textile
@@ -182,21 +182,27 @@ 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.
-<ruby>
-def test_truth
-</ruby>
-
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_+.
+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
</ruby>
-This makes test names more readable by replacing underscores with regular language.
+acts as if you had written
+
+<ruby>
+def test_the_truth
+ assert true
+end
+</ruby>
+
+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
@@ -223,13 +229,13 @@ $ rake db:test:load
Above +rake db:migrate+ runs any pending migrations on the _development_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately.
-NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exists.
+NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist.
h5. Rake Tasks for Preparing your Application for Testing
|_.Tasks |_.Description|
|+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
-|+rake db:test:clone_structure+ |Recreate the test databases from the development structure|
+|+rake db:test:clone_structure+ |Recreate the test database from the development structure|
|+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
|+rake db:test:prepare+ |Check for pending migrations and load the test schema|
|+rake db:test:purge+ |Empty the test database.|
@@ -241,8 +247,7 @@ h4. Running Tests
Running a test is as simple as invoking the file containing the test cases through Ruby:
<shell>
-$ cd test
-$ ruby unit/post_test.rb
+$ ruby -Itest test/unit/post_test.rb
Loaded suite unit/post_test
Started
@@ -252,12 +257,12 @@ Finished in 0.023513 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
</shell>
-This will run all the test methods from the test case.
+This will run all the 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.
You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
<shell>
-$ ruby unit/post_test.rb -n test_truth
+$ ruby -Itest test/unit/post_test.rb -n test_the_truth
Loaded suite unit/post_test
Started
@@ -316,7 +321,7 @@ Now to get this test to pass we can add a model level validation for the _title_
<ruby>
class Post < ActiveRecord::Base
- validates_presence_of :title
+ validates :title, :presence => true
end
</ruby>
@@ -381,7 +386,7 @@ There are a bunch of different types of assertions you can use. Here's the compl
|+assert( boolean, [msg] )+ |Ensures that the object/expression is true.|
|+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.|
|+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.|
-|+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.|
+|+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.|
|+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.|
|+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.|
|+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.|
@@ -389,7 +394,7 @@ There are a bunch of different types of assertions you can use. Here's the compl
|+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't matches 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_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+.|
@@ -495,6 +500,8 @@ If you're familiar with the HTTP protocol, you'll know that +get+ is a type of r
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.
+
h4. 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:
@@ -507,12 +514,12 @@ After a request has been made by using one of the 5 methods (+get+, +post+, etc.
As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
<ruby>
- flash["gordon"] flash[:gordon]
- session["shmession"] session[:shmession]
- cookies["are_good_for_u"] cookies[:are_good_for_u]
+flash["gordon"] flash[:gordon]
+session["shmession"] session[:shmession]
+cookies["are_good_for_u"] cookies[:are_good_for_u]
# Because you can't use assigns[:something] for historical reasons:
- assigns["something"] assigns(:something)
+assigns["something"] assigns(:something)
</ruby>
h4. Instance Variables Available
@@ -577,7 +584,7 @@ assert_select "ol" do
end
</ruby>
-The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html.
+The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
h5. Additional View-Based Assertions
@@ -614,7 +621,7 @@ Here's what a freshly-generated integration test looks like:
<ruby>
require 'test_helper'
-class UserFlowsTest < ActionController::IntegrationTest
+class UserFlowsTest < ActionDispatch::IntegrationTest
fixtures :all
# Replace this with your real tests.
@@ -624,7 +631,7 @@ class UserFlowsTest < ActionController::IntegrationTest
end
</ruby>
-Integration tests inherit from +ActionController::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.
+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.
h4. Helpers Available for Integration Tests
@@ -650,7 +657,7 @@ A simple integration test that exercises multiple controllers:
<ruby>
require 'test_helper'
-class UserFlowsTest < ActionController::IntegrationTest
+class UserFlowsTest < ActionDispatch::IntegrationTest
fixtures :users
test "login and browse site" do
@@ -678,7 +685,7 @@ Here's an example of multiple sessions and custom DSL in an integration test
<ruby>
require 'test_helper'
-class UserFlowsTest < ActionController::IntegrationTest
+class UserFlowsTest < ActionDispatch::IntegrationTest
fixtures :users
test "login and browse site" do
@@ -735,7 +742,7 @@ You don't need to set up and run your tests by hand on a test-by-test basis. Rai
|+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)|
|+rake test:profile+ |Profile the performance tests|
|+rake test:recent+ |Tests recent changes|
-|+rake test:uncommitted+ |Runs all the tests which are uncommitted. Only supports Subversion|
+|+rake test:uncommitted+ |Runs all the tests which are uncommitted. Supports Subversion and Git|
|+rake test:units+ |Runs all the unit tests from +test/unit+|
@@ -934,15 +941,13 @@ h3. 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":http://github.com/thoughtbot/factory_girl/tree/master, as replacement for fixtures.
-* "Machinist":http://github.com/notahat/machinist/tree/master, another replacement for fixtures.
+* "Factory Girl":https://github.com/thoughtbot/factory_girl/tree/master, as replacement for fixtures.
+* "Machinist":https://github.com/notahat/machinist/tree/master, another replacement for fixtures.
* "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions.
* "RSpec":http://rspec.info/, a behavior-driven development framework
h3. Changelog
-"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8
-
* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* November 13, 2008: Revised based on feedback from Pratik Naik by "Akshay Surve":credits.html#asurve (not yet approved for publication)
* October 14, 2008: Edit and formatting pass by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
diff --git a/railties/guides/w3c_validator.rb b/railties/guides/w3c_validator.rb
index 4da48bf3fb..f1fe1e0f33 100644
--- a/railties/guides/w3c_validator.rb
+++ b/railties/guides/w3c_validator.rb
@@ -21,7 +21,7 @@
#
# Separate many using commas:
#
-# # validates only
+# # validates only association_basics.html and migrations.html
# ONLY=assoc,migrations rake validate_guides
#
# ---------------------------------------------------------------------------
@@ -32,13 +32,13 @@ include W3CValidators
module RailsGuides
class Validator
-
+
def validate
validator = MarkupValidator.new
STDOUT.sync = true
errors_on_guides = {}
- guides_to_validate.each do |f|
+ guides_to_validate.each do |f|
results = validator.validate_file(f)
if results.validity
@@ -48,10 +48,10 @@ module RailsGuides
errors_on_guides[f] = results.errors
end
end
-
+
show_results(errors_on_guides)
end
-
+
private
def guides_to_validate
guides = Dir["./guides/output/*.html"]
@@ -65,13 +65,13 @@ module RailsGuides
prefixes.any? {|p| guide.start_with?("./guides/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"
@@ -79,13 +79,13 @@ module RailsGuides
error_detail += "\n "+error.to_s.gsub("\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 \ No newline at end of file
+RailsGuides::Validator.new.validate
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
index bbf28a8c08..cca0891835 100644
--- a/railties/lib/rails.rb
+++ b/railties/lib/rails.rb
@@ -8,7 +8,6 @@ require 'active_support/core_ext/logger'
require 'rails/application'
require 'rails/version'
-require 'rails/deprecation'
require 'active_support/railtie'
require 'action_dispatch/railtie'
@@ -93,12 +92,7 @@ module Rails
end
def public_path
- application && application.paths.public.to_a.first
- end
-
- def public_path=(path)
- ActiveSupport::Deprecation.warn "Setting Rails.public_path= is deprecated. " <<
- "Please set paths.public = in config/application.rb instead.", caller
+ application && application.paths["public"].first
end
end
end
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 5b26333486..94819820bc 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -35,30 +35,12 @@ module Rails
#
class Application < Engine
autoload :Bootstrap, 'rails/application/bootstrap'
- autoload :Configurable, 'rails/application/configurable'
autoload :Configuration, 'rails/application/configuration'
autoload :Finisher, 'rails/application/finisher'
autoload :Railties, 'rails/application/railties'
+ autoload :RoutesReloader, 'rails/application/routes_reloader'
class << self
- private :new
-
- def configure(&block)
- class_eval(&block)
- end
-
- def instance
- if self == Rails::Application
- if Rails.application
- ActiveSupport::Deprecation.warn "Calling a method in Rails::Application is deprecated, " <<
- "please call it directly in your application constant #{Rails.application.class.name}.", caller
- end
- Rails.application
- else
- @@instance ||= new
- end
- end
-
def inherited(base)
raise "You cannot have more than one Rails::Application" if Rails.application
super
@@ -66,19 +48,9 @@ module Rails
Rails.application.add_lib_to_load_path!
ActiveSupport.run_load_hooks(:before_configuration, base.instance)
end
-
- def respond_to?(*args)
- super || instance.respond_to?(*args)
- end
-
- protected
-
- def method_missing(*args, &block)
- instance.send(*args, &block)
- end
end
- delegate :middleware, :to => :config
+ delegate :default_url_options, :default_url_options=, :to => :routes
# 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
@@ -99,7 +71,7 @@ module Rails
end
def require_environment! #:nodoc:
- environment = paths.config.environment.to_a.first
+ environment = paths["config/environment"].existent.first
require environment if environment
end
@@ -108,30 +80,18 @@ module Rails
super
end
- def routes
- @routes ||= ActionDispatch::Routing::RouteSet.new
- end
-
- def railties
- @railties ||= Railties.new(config)
+ def reload_routes!
+ routes_reloader.reload!
end
def routes_reloader
- @routes_reloader ||= ActiveSupport::FileUpdateChecker.new([]){ reload_routes! }
- end
-
- def reload_routes!
- _routes = self.routes
- _routes.disable_clear_and_finalize = true
- _routes.clear!
- routes_reloader.paths.each { |path| load(path) }
- ActiveSupport.on_load(:action_controller) { _routes.finalize! }
- ensure
- _routes.disable_clear_and_finalize = false
+ @routes_reloader ||= RoutesReloader.new
end
def initialize!
+ raise "Application has been already initialized." if @initialized
run_initializers(self)
+ @initialized = true
self
end
@@ -156,45 +116,52 @@ module Rails
self
end
- def app
- @app ||= begin
- config.middleware = config.middleware.merge_into(default_middleware_stack)
- config.middleware.build(routes)
- end
- end
alias :build_middleware_stack :app
- def call(env)
- app.call(env.reverse_merge!(env_defaults))
- end
-
- def env_defaults
- @env_defaults ||= {
+ def env_config
+ @env_config ||= super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
- "action_dispatch.secret_token" => config.secret_token
- }
+ "action_dispatch.secret_token" => config.secret_token,
+ "action_dispatch.asset_path" => nil,
+ "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
+ })
end
def initializers
- initializers = Bootstrap.initializers_for(self)
- railties.all { |r| initializers += r.initializers }
- initializers += super
- initializers += Finisher.initializers_for(self)
- initializers
+ Bootstrap.initializers_for(self) +
+ super +
+ Finisher.initializers_for(self)
+ end
+
+ def config
+ @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
end
protected
+ def default_asset_path
+ nil
+ end
+
def default_middleware_stack
ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use ::ActionDispatch::Static, paths.public.to_a.first if config.serve_static_assets
- middleware.use ::Rack::Lock if !config.allow_concurrency
+ rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
+
+ require "action_dispatch/http/rack_cache" if rack_cache
+ middleware.use ::Rack::Cache, rack_cache if rack_cache
+
+ if config.serve_static_assets
+ asset_paths = ActiveSupport::OrderedHash[config.static_asset_paths.to_a.reverse]
+ middleware.use ::ActionDispatch::Static, asset_paths
+ end
+ middleware.use ::Rack::Lock unless config.allow_concurrency
middleware.use ::Rack::Runtime
middleware.use ::Rails::Rack::Logger
- middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local if config.action_dispatch.show_exceptions
+ middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
- middleware.use ::ActionDispatch::Callbacks, !config.cache_classes
+ middleware.use ::ActionDispatch::Reloader unless config.cache_classes
+ middleware.use ::ActionDispatch::Callbacks
middleware.use ::ActionDispatch::Cookies
if config.session_store
@@ -205,6 +172,8 @@ module Rails
middleware.use ::ActionDispatch::ParamsParser
middleware.use ::Rack::MethodOverride
middleware.use ::ActionDispatch::Head
+ middleware.use ::Rack::ConditionalGet
+ middleware.use ::Rack::ETag, "no-cache"
middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support if config.action_dispatch.best_standards_support
end
end
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index 44e26b5713..9c9d85eed6 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -6,10 +6,7 @@ module Rails
module Bootstrap
include Initializable
- initializer :load_environment_config do
- environment = config.paths.config.environments.to_a.first
- require environment if environment
- end
+ initializer :load_environment_hook do end
initializer :load_active_support do
require 'active_support/dependencies'
@@ -26,7 +23,7 @@ module Rails
# Initialize the logger early in the stack in case we need to log some deprecation.
initializer :initialize_logger do
Rails.logger ||= config.logger || begin
- path = config.paths.log.to_a.first
+ path = config.paths["log"].first
logger = ActiveSupport::BufferedLogger.new(path)
logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase)
logger.auto_flushing = false if Rails.env.production?
@@ -54,11 +51,9 @@ module Rails
end
initializer :set_clear_dependencies_hook do
- unless config.cache_classes
- ActionDispatch::Callbacks.after do
- ActiveSupport::DescendantsTracker.clear
- ActiveSupport::Dependencies.clear
- end
+ ActionDispatch::Reloader.to_cleanup do
+ ActiveSupport::DescendantsTracker.clear
+ ActiveSupport::Dependencies.clear
end
end
@@ -73,4 +68,4 @@ module Rails
end
end
end
-end \ No newline at end of file
+end
diff --git a/railties/lib/rails/application/configurable.rb b/railties/lib/rails/application/configurable.rb
deleted file mode 100644
index f598e33965..0000000000
--- a/railties/lib/rails/application/configurable.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-module Rails
- class Application
- module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
-
- module ClassMethods
- def inherited(base)
- raise "You cannot inherit from a Rails::Application child"
- end
- end
-
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
- end
- end
-end \ No newline at end of file
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 465851c0e6..c74bcbedf2 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -1,31 +1,37 @@
-require 'active_support/deprecation'
require 'active_support/core_ext/string/encoding'
require 'rails/engine/configuration'
module Rails
class Application
class Configuration < ::Rails::Engine::Configuration
- include ::Rails::Configuration::Deprecated
-
- attr_accessor :allow_concurrency, :cache_classes, :cache_store,
+ attr_accessor :allow_concurrency, :asset_host, :cache_classes, :cache_store,
:encoding, :consider_all_requests_local, :dependency_loading,
- :filter_parameters, :log_level, :logger, :middleware,
- :plugins, :preload_frameworks, :reload_plugins,
+ :filter_parameters, :helpers_paths, :logger,
+ :preload_frameworks, :reload_plugins,
:secret_token, :serve_static_assets, :session_options,
:time_zone, :whiny_nils
+ attr_writer :log_level
+
def initialize(*)
super
- @allow_concurrency = false
+ self.encoding = "utf-8"
+ @allow_concurrency = false
@consider_all_requests_local = false
- @encoding = "utf-8"
- @filter_parameters = []
- @dependency_loading = true
- @serve_static_assets = true
- @session_store = :cookie_store
- @session_options = {}
- @time_zone = "UTC"
- @middleware = app_middleware
+ @filter_parameters = []
+ @helpers_paths = []
+ @dependency_loading = true
+ @serve_static_assets = true
+ @session_store = :cookie_store
+ @session_options = {}
+ @time_zone = "UTC"
+ @log_level = nil
+ @middleware = app_middleware
+ @generators = app_generators
+ end
+
+ def compiled_asset_path
+ "/"
end
def encoding=(value)
@@ -45,23 +51,12 @@ module Rails
def paths
@paths ||= begin
paths = super
- paths.app.controllers << builtin_controller if builtin_controller
- paths.config.database "config/database.yml"
- paths.config.environment "config/environment.rb"
- paths.config.environments "config/environments", :glob => "#{Rails.env}.rb"
- paths.lib.templates "lib/templates"
- paths.log "log/#{Rails.env}.log"
- paths.tmp "tmp"
- paths.tmp.cache "tmp/cache"
- paths.vendor "vendor", :load_path => true
- paths.vendor.plugins "vendor/plugins"
-
- if File.exists?("#{root}/test/mocks/#{Rails.env}")
- ActiveSupport::Deprecation.warn "\"Rails.root/test/mocks/#{Rails.env}\" won't be added " <<
- "automatically to load paths anymore in future releases"
- paths.mocks_path "test/mocks", :autoload => true, :glob => Rails.env
- end
-
+ 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 "tmp"
+ paths.add "tmp/cache"
paths
end
end
@@ -83,7 +78,7 @@ module Rails
# YAML::load.
def database_configuration
require 'erb'
- YAML::load(ERB.new(IO.read(paths.config.database.to_a.first)).result)
+ YAML::load(ERB.new(IO.read(paths["config/database"].first)).result)
end
def cache_store
@@ -96,10 +91,6 @@ module Rails
end
end
- def builtin_controller
- File.expand_path('../info_routes', __FILE__) if Rails.env.development?
- end
-
def log_level
@log_level ||= Rails.env.production? ? :info : :debug
end
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index 855467227b..a45b61c99c 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -4,7 +4,7 @@ module Rails
include Initializable
initializer :add_generator_templates do
- config.generators.templates.unshift(*paths.lib.templates.to_a)
+ config.generators.templates.unshift(*paths["lib/templates"].existent)
end
initializer :ensure_autoload_once_paths_as_subset do
@@ -21,13 +21,15 @@ module Rails
initializer :add_to_prepare_blocks do
config.to_prepare_blocks.each do |block|
- ActionDispatch::Callbacks.to_prepare(&block)
+ ActionDispatch::Reloader.to_prepare(&block)
end
end
initializer :add_builtin_route do |app|
if Rails.env.development?
- app.routes_reloader.paths << File.expand_path('../../info_routes.rb', __FILE__)
+ app.routes.append do
+ match '/rails/info/properties' => "rails/info#properties"
+ end
end
end
@@ -35,6 +37,10 @@ module Rails
build_middleware_stack
end
+ initializer :run_prepare_callbacks do
+ ActionDispatch::Reloader.prepare!
+ end
+
initializer :eager_load! do
if config.cache_classes && !$rails_rake_task
ActiveSupport.run_load_hooks(:before_eager_load, self)
@@ -46,6 +52,13 @@ module Rails
ActiveSupport.run_load_hooks(:after_initialize, self)
end
+ # Force routes to be loaded just at the end and add it to to_prepare callbacks
+ initializer :set_routes_reloader do |app|
+ reloader = lambda { app.routes_reloader.execute_if_updated }
+ reloader.call
+ ActionDispatch::Reloader.to_prepare(&reloader)
+ end
+
# Disable dependency loading during request cycle
initializer :disable_dependency_loading do
if config.cache_classes && !config.dependency_loading
diff --git a/railties/lib/rails/application/railties.rb b/railties/lib/rails/application/railties.rb
index b3e6693f89..4fc5e92837 100644
--- a/railties/lib/rails/application/railties.rb
+++ b/railties/lib/rails/application/railties.rb
@@ -1,31 +1,13 @@
-module Rails
- class Application
- class Railties
- # TODO Write tests for this behavior extracted from Application
- def initialize(config)
- @config = config
- end
+require 'rails/engine/railties'
+module Rails
+ class Application < Engine
+ class Railties < Rails::Engine::Railties
def all(&block)
- @all ||= railties + engines + plugins
+ @all ||= railties + engines + super
@all.each(&block) if block
@all
end
-
- def railties
- @railties ||= ::Rails::Railtie.subclasses.map(&:new)
- end
-
- def engines
- @engines ||= ::Rails::Engine.subclasses.map(&:new)
- end
-
- def plugins
- @plugins ||= begin
- plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
- Plugin.all(plugin_names, @config.paths.vendor.plugins)
- end
- end
end
end
-end \ No newline at end of file
+end
diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb
new file mode 100644
index 0000000000..1d1f5e1b06
--- /dev/null
+++ b/railties/lib/rails/application/routes_reloader.rb
@@ -0,0 +1,45 @@
+module Rails
+ class Application
+ class RoutesReloader < ::ActiveSupport::FileUpdateChecker
+ attr_reader :route_sets
+
+ def initialize
+ super([]) { reload! }
+ @route_sets = []
+ end
+
+ def reload!
+ clear!
+ load_paths
+ finalize!
+ ensure
+ revert
+ end
+
+ protected
+
+ 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|
+ ActiveSupport.on_load(:action_controller) { 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
index bedefaa51c..36fd9aea19 100644
--- a/railties/lib/rails/backtrace_cleaner.rb
+++ b/railties/lib/rails/backtrace_cleaner.rb
@@ -22,7 +22,7 @@ module Rails
gems_paths = (Gem.path + [Gem.default_dir]).uniq.map!{ |p| Regexp.escape(p) }
return if gems_paths.empty?
- gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w\.]+)/(.*)}
+ gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
end
end
diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb
index d49431919d..443d6f47ad 100644
--- a/railties/lib/rails/cli.rb
+++ b/railties/lib/rails/cli.rb
@@ -1,12 +1,16 @@
require 'rbconfig'
require 'rails/script_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::ScriptRailsLoader.exec_script_rails!
-railties_path = File.expand_path('../../lib', __FILE__)
-$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path)
-
require 'rails/ruby_version_check'
-Signal.trap("INT") { puts; exit }
+Signal.trap("INT") { puts; exit(1) }
-require 'rails/commands/application'
+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
index 740d8a1767..40416dd83a 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -12,7 +12,7 @@ class CodeStatistics #:nodoc:
print_header
@pairs.each { |pair| print_line(pair.first, @statistics[pair.first]) }
print_splitter
-
+
if @total
print_line("Total", @total)
print_splitter
@@ -23,13 +23,13 @@ class CodeStatistics #:nodoc:
private
def calculate_statistics
- @pairs.inject({}) { |stats, pair| stats[pair.first] = calculate_directory_statistics(pair.last); stats }
+ Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}]
end
def calculate_directory_statistics(directory, pattern = /.*\.rb$/)
stats = { "lines" => 0, "codelines" => 0, "classes" => 0, "methods" => 0 }
- Dir.foreach(directory) do |file_name|
+ Dir.foreach(directory) do |file_name|
if File.stat(directory + "/" + file_name).directory? and (/^\./ !~ file_name)
newstats = calculate_directory_statistics(directory + "/" + file_name, pattern)
stats.each { |k, v| stats[k] += newstats[k] }
@@ -85,10 +85,10 @@ class CodeStatistics #:nodoc:
start = if TEST_TYPES.include? name
"| #{name.ljust(20)} "
else
- "| #{name.ljust(20)} "
+ "| #{name.ljust(20)} "
end
- puts start +
+ puts start +
"| #{statistics["lines"].to_s.rjust(5)} " +
"| #{statistics["codelines"].to_s.rjust(5)} " +
"| #{statistics["classes"].to_s.rjust(7)} " +
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index 60a93c9848..02ccdf8060 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -11,7 +11,21 @@ command = ARGV.shift
command = aliases[command] || command
case command
-when 'generate', 'destroy', 'plugin', 'benchmarker', 'profiler'
+when 'generate', 'destroy', 'plugin'
+ if command == 'plugin' && ARGV.first == 'new'
+ require "rails/commands/plugin_new"
+ else
+ require APP_PATH
+ Rails.application.require_environment!
+
+ if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
+ Rails.application = engine
+ end
+
+ require "rails/commands/#{command}"
+ end
+
+when 'benchmarker', 'profiler'
require APP_PATH
Rails.application.require_environment!
require "rails/commands/#{command}"
@@ -23,8 +37,15 @@ when 'console'
Rails::Console.start(Rails.application)
when 'server'
+ # Change to the application's path if there is no config.ru file in current dir.
+ # This allows us to run script/rails server from other directories, but still get
+ # the main config.ru and properly set the tmp directory.
+ Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
+
require 'rails/commands/server'
Rails::Server.new.tap { |server|
+ # We need to require application after the server sets environment,
+ # otherwise the --environment option given to the server won't propagate.
require APP_PATH
Dir.chdir(Rails.application.root)
server.start
@@ -41,6 +62,7 @@ when 'application', 'runner'
when 'new'
puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
puts "Type 'rails' for help."
+ exit(1)
when '--version', '-v'
ARGV.unshift '--version'
@@ -70,4 +92,5 @@ In addition to those, there are:
All commands can be run with -h for more information.
EOT
+ exit(1)
end
diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb
index 47c6752ca3..3b57b925ba 100644
--- a/railties/lib/rails/commands/application.rb
+++ b/railties/lib/rails/commands/application.rb
@@ -15,4 +15,16 @@ require 'rubygems' if ARGV.include?("--dev")
require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
+module Rails
+ module Generators
+ class AppGenerator
+ # We want to exit on failure to be kind to other libraries
+ # This is only when accessing via CLI
+ def self.exit_on_failure?
+ true
+ end
+ end
+ end
+end
+
Rails::Generators::AppGenerator.start
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index 834a120c01..de2f190ad5 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -48,5 +48,5 @@ end
# Has to set the RAILS_ENV before config/application is required
if ARGV.first && !ARGV.first.index("-") && env = ARGV.pop # has to pop the env ARGV so IRB doesn't freak
- ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env
+ ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
end
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 5bbaf725df..f0d6ea1687 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -1,4 +1,10 @@
require 'erb'
+
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
require 'optparse'
require 'rbconfig'
@@ -42,7 +48,7 @@ module Rails
def find_cmd(*commands)
dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
- commands += commands.map{|cmd| "#{cmd}.exe"} if Config::CONFIG['host_os'] =~ /mswin|mingw/
+ commands += commands.map{|cmd| "#{cmd}.exe"} if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
full_path_command = nil
found = commands.detect do |cmd|
@@ -74,7 +80,7 @@ module Rails
exec(find_cmd('mysql', 'mysql5'), *args)
- when "postgresql"
+ when "postgresql", "postgres"
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
@@ -113,5 +119,5 @@ end
# Has to set the RAILS_ENV before config/application is required
if ARGV.first && !ARGV.first.index("-") && env = ARGV.first
- ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env
+ ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
end
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
index 96b6f9c372..048af7cbef 100644
--- a/railties/lib/rails/commands/plugin.rb
+++ b/railties/lib/rails/commands/plugin.rb
@@ -58,7 +58,7 @@ class RailsEnvironment
else
plugin = name_uri_or_plugin
end
- unless plugin.nil?
+ if plugin
plugin.install
else
puts "Plugin not found: #{name_uri_or_plugin}"
@@ -276,12 +276,11 @@ end
require 'optparse'
module Commands
class Plugin
- attr_reader :environment, :script_name, :sources
+ attr_reader :environment, :script_name
def initialize
@environment = RailsEnvironment.default
@rails_root = RailsEnvironment.default.root
@script_name = File.basename($0)
- @sources = []
end
def environment=(value)
@@ -301,8 +300,6 @@ module Commands
o.on("-r", "--root=DIR", String,
"Set an explicit rails app directory.",
"Default: #{@rails_root}") { |rails_root| @rails_root = rails_root; self.environment = RailsEnvironment.new(@rails_root) }
- o.on("-s", "--source=URL1,URL2", Array,
- "Use the specified plugin repositories instead of the defaults.") { |sources| @sources = sources}
o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
o.on("-h", "--help", "Show this help message.") { puts o; exit }
@@ -315,8 +312,6 @@ module Commands
o.separator ""
o.separator "EXAMPLES"
- o.separator " Install a plugin:"
- o.separator " #{@script_name} plugin install continuous_builder\n"
o.separator " Install a plugin from a subversion URL:"
o.separator " #{@script_name} plugin install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder\n"
o.separator " Install a plugin from a git URL:"
@@ -375,7 +370,7 @@ module Commands
"Enables updating but does not add a svn:externals entry.") { |v| @method = :checkout }
o.on( "-e", "--export",
"Use svn export to grab the plugin.",
- "Exports the plugin, allowing you to check it into your local repository. Does not enable updates, or add an svn:externals entry.") { |v| @method = :export }
+ "Exports the plugin, allowing you to check it into your local repository. Does not enable updates or add an svn:externals entry.") { |v| @method = :export }
o.on( "-q", "--quiet",
"Suppresses the output from installation.",
"Ignored if -v is passed (rails plugin -v install ...)") { |v| @options[:quiet] = true }
diff --git a/railties/lib/rails/commands/plugin_new.rb b/railties/lib/rails/commands/plugin_new.rb
new file mode 100644
index 0000000000..8baa8ebfd4
--- /dev/null
+++ b/railties/lib/rails/commands/plugin_new.rb
@@ -0,0 +1,10 @@
+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
diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb
index c43a233bc3..1a91d477ec 100644
--- a/railties/lib/rails/commands/runner.rb
+++ b/railties/lib/rails/commands/runner.rb
@@ -17,13 +17,13 @@ ARGV.clone.options do |opts|
opts.separator ""
opts.on("-h", "--help",
- "Show this help message.") { $stderr.puts opts; exit }
+ "Show this help message.") { $stdout.puts opts; exit }
- if Config::CONFIG['host_os'] !~ /mswin|mingw/
+ if RbConfig::CONFIG['host_os'] !~ /mswin|mingw/
opts.separator ""
opts.separator "You can also use runner as a shebang line for your scripts like this:"
opts.separator "-------------------------------------------------------------"
- opts.separator "#!/usr/bin/env #{File.expand_path($0)}"
+ opts.separator "#!/usr/bin/env #{File.expand_path($0)} runner"
opts.separator ""
opts.separator "Product.find(:all).each { |p| p.price *= 2 ; p.save! }"
opts.separator "-------------------------------------------------------------"
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index c3927b6613..e447209242 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -42,6 +42,10 @@ module Rails
set_environment
end
+ def app
+ @app ||= super.instance
+ end
+
def opt_parser
Options.new
end
diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb
index e5af12b901..66fab0a760 100644
--- a/railties/lib/rails/configuration.rb
+++ b/railties/lib/rails/configuration.rb
@@ -1,5 +1,6 @@
require 'active_support/deprecation'
require 'active_support/ordered_options'
+require 'active_support/core_ext/hash/deep_dup'
require 'rails/paths'
require 'rails/rack'
@@ -51,6 +52,13 @@ module Rails
@colorize_logging = true
end
+ def initialize_copy(source)
+ @aliases = @aliases.deep_dup
+ @options = @options.deep_dup
+ @fallbacks = @fallbacks.deep_dup
+ @templates = @templates.dup
+ end
+
def method_missing(method, *args)
method = method.to_s.sub(/=$/, '').to_sym
@@ -71,86 +79,5 @@ module Rails
end
end
end
-
- module Deprecated
- def frameworks(*args)
- raise "config.frameworks in no longer supported. See the generated " \
- "config/boot.rb for steps on how to limit the frameworks that " \
- "will be loaded"
- end
- alias :frameworks= :frameworks
-
- def view_path=(value)
- ActiveSupport::Deprecation.warn "config.view_path= is deprecated, " <<
- "please do paths.app.views= instead", caller
- paths.app.views = value
- end
-
- def view_path
- ActiveSupport::Deprecation.warn "config.view_path is deprecated, " <<
- "please do paths.app.views instead", caller
- paths.app.views.to_a.first
- end
-
- def routes_configuration_file=(value)
- ActiveSupport::Deprecation.warn "config.routes_configuration_file= is deprecated, " <<
- "please do paths.config.routes= instead", caller
- paths.config.routes = value
- end
-
- def routes_configuration_file
- ActiveSupport::Deprecation.warn "config.routes_configuration_file is deprecated, " <<
- "please do paths.config.routes instead", caller
- paths.config.routes.to_a.first
- end
-
- def database_configuration_file=(value)
- ActiveSupport::Deprecation.warn "config.database_configuration_file= is deprecated, " <<
- "please do paths.config.database= instead", caller
- paths.config.database = value
- end
-
- def database_configuration_file
- ActiveSupport::Deprecation.warn "config.database_configuration_file is deprecated, " <<
- "please do paths.config.database instead", caller
- paths.config.database.to_a.first
- end
-
- def log_path=(value)
- ActiveSupport::Deprecation.warn "config.log_path= is deprecated, " <<
- "please do paths.log= instead", caller
- paths.config.log = value
- end
-
- def log_path
- ActiveSupport::Deprecation.warn "config.log_path is deprecated, " <<
- "please do paths.log instead", caller
- paths.config.log.to_a.first
- end
-
- def controller_paths=(value)
- ActiveSupport::Deprecation.warn "config.controller_paths= is deprecated, " <<
- "please do paths.app.controllers= instead", caller
- paths.app.controllers = value
- end
-
- def controller_paths
- ActiveSupport::Deprecation.warn "config.controller_paths is deprecated, " <<
- "please do paths.app.controllers instead", caller
- paths.app.controllers.to_a.uniq
- end
-
- def cookie_secret=(value)
- ActiveSupport::Deprecation.warn "config.cookie_secret= is deprecated, " <<
- "please use config.secret_token= instead", caller
- self.secret_token = value
- end
-
- def cookie_secret
- ActiveSupport::Deprecation.warn "config.cookie_secret is deprecated, " <<
- "please use config.secret_token instead", caller
- self.secret_token
- end
- end
end
end
diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb
index 9d9763699d..95c74baae2 100644
--- a/railties/lib/rails/console/app.rb
+++ b/railties/lib/rails/console/app.rb
@@ -26,7 +26,7 @@ end
# reloads the environment
def reload!(print=true)
puts "Reloading..." if print
- # This triggers the to_prepare callbacks
- ActionDispatch::Callbacks.new(Proc.new {}, false).call({})
+ ActionDispatch::Reloader.cleanup!
+ ActionDispatch::Reloader.prepare!
true
end
diff --git a/railties/lib/rails/deprecation.rb b/railties/lib/rails/deprecation.rb
deleted file mode 100644
index 1eb6d804b6..0000000000
--- a/railties/lib/rails/deprecation.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-require "active_support/string_inquirer"
-require "active_support/deprecation"
-
-RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
- cattr_accessor :warned
- self.warned = false
-
- def target
- Rails.root
- end
-
- def replace(*args)
- warn(caller, :replace, *args)
- end
-
- def warn(callstack, called, args)
- unless warned
- ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack)
- self.warned = true
- end
- end
-end).new
-
-RAILS_ENV = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
- cattr_accessor :warned
- self.warned = false
-
- def target
- Rails.env
- end
-
- def replace(*args)
- warn(caller, :replace, *args)
- end
-
- def warn(callstack, called, args)
- unless warned
- ActiveSupport::Deprecation.warn("RAILS_ENV is deprecated! Use Rails.env instead", callstack)
- self.warned = true
- end
- end
-end).new
-
-RAILS_DEFAULT_LOGGER = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
- cattr_accessor :warned
- self.warned = false
-
- def target
- Rails.logger
- end
-
- def replace(*args)
- warn(caller, :replace, *args)
- end
-
- def warn(callstack, called, args)
- unless warned
- ActiveSupport::Deprecation.warn("RAILS_DEFAULT_LOGGER is deprecated! Use Rails.logger instead", callstack)
- self.warned = true
- end
- end
-end).new
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index ee3e3ba040..4fc23fe277 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -2,21 +2,23 @@ require 'rails/railtie'
require 'active_support/core_ext/module/delegation'
require 'pathname'
require 'rbconfig'
+require 'rails/engine/railties'
module Rails
- # Rails::Engine allows you to wrap a specific Rails application and share it accross
- # different applications. Since Rails 3.0, every Rails::Application is nothing
- # more than an Engine, allowing you to share it very easily.
+ # Rails::Engine allows you to wrap a specific Rails application and share it across
+ # different applications. Since Rails 3.0, every <tt>Rails::Application</tt> is nothing
+ # more than an engine, allowing you to share it very easily.
#
- # Any Rails::Engine is also a Rails::Railtie, so the same methods (like rake_tasks and
- # generators) and configuration available in the latter can also be used in the former.
+ # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same methods
+ # (like <tt>rake_tasks</tt> and +generators+) and configuration available in the
+ # latter can also be used in the former.
#
# == Creating an Engine
#
- # In Rails versions before to 3.0, your gems automatically behaved as Engine, however
+ # In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
- # behave as Engine, you have to specify an Engine for it somewhere inside your plugin
- # lib folder (similar with how we spceify a Railtie):
+ # behave as an engine, you have to specify an +Engine+ for it somewhere inside
+ # your plugin's +lib+ folder (similar to how we specify a +Railtie+):
#
# # lib/my_engine.rb
# module MyEngine
@@ -24,16 +26,17 @@ module Rails
# end
# end
#
- # Then ensure that this file is loaded at the top of your config/application.rb (or in
- # your Gemfile) and it will automatically load models, controllers and helpers
- # inside app, load routes at "config/routes.rb", load locales at "config/locales/*",
- # load tasks at "lib/tasks/*".
+ # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
+ # (or in your +Gemfile+) and it will automatically load models, controllers and helpers
+ # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
+ # <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
#
# == Configuration
#
- # Besides the Railtie configuration which is shared across the application, in a
- # Rails::Engine you can access autoload_paths, eager_load_paths and autoload_once_paths,
- # which differently from a Railtie, are scoped to the current Engine.
+ # Besides the +Railtie+ configuration which is shared across the application, in a
+ # <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
+ # and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
+ # the current engine.
#
# Example:
#
@@ -46,89 +49,352 @@ module Rails
# 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, both your Application and Engines do not have hardcoded paths.
- # This means that you are not required to place your controllers at "app/controllers",
+ # Since Rails 3.0, both your application and engines do not have hardcoded paths.
+ # This means that you are not required to place your controllers at <tt>app/controllers</tt>,
# but in any place which you find convenient.
#
- # For example, let's suppose you want to lay your controllers at lib/controllers, all
- # you need to do is:
+ # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
+ # All you would need to do is:
#
# class MyEngine < Rails::Engine
- # paths.app.controllers = "lib/controllers"
+ # paths["app/controllers"] = "lib/controllers"
# end
#
- # You can also have your controllers being loaded from both "app/controllers" and
- # "lib/controllers":
+ # You can also have your controllers loaded from both <tt>app/controllers</tt> and
+ # <tt>lib/controllers</tt>:
#
# class MyEngine < Rails::Engine
- # paths.app.controllers << "lib/controllers"
+ # paths["app/controllers"] << "lib/controllers"
# end
#
- # The available paths in an Engine are:
+ # The available paths in an engine are:
#
# class MyEngine < Rails::Engine
- # paths.app = "app"
- # 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
- #
- # Your Application class adds a couple more paths to this set. And as in your Application,
- # all folders under "app" are automatically added to the load path. So if you have
- # "app/observers", it's added by default.
+ # 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
+ #
+ # Your <tt>Application</tt> class adds a couple more paths to this set. And as in your
+ # <tt>Application</tt>,all folders under +app+ are automatically added to the load path.
+ # So if you have <tt>app/observers</tt>, it's added by default.
+ #
+ # == Endpoint
+ #
+ # 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 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
+ # match "/" => "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"
+ # match "/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
+ # match "/blog/omg" => "main#omg"
+ # mount MyEngine::Engine => "/blog"
+ # end
+ #
+ # Now, +Engine+ will get only requests that were not handled by +Application+.
+ #
+ # == Asset path
+ #
+ # When you use +Engine+ with its own public directory, you will probably want to copy or symlink it
+ # to application's public directory. To simplify generating paths for assets, you can set <tt>asset_path</tt>
+ # for an engine:
+ #
+ # module MyEngine
+ # class Engine < Rails::Engine
+ # config.asset_path = "/my_engine/%s"
+ # end
+ # end
+ #
+ # With such a config, asset paths will be automatically modified inside +Engine+:
+ #
+ # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"
+ #
+ # == Serving static files
+ #
+ # By default, Rails uses <tt>ActionDispatch::Static</tt> to serve static files in development mode. This is ok
+ # while you develop your application, but when you want to deploy it, assets from an engine will not be
+ # served by default. You should choose one of the two following strategies:
+ #
+ # * enable serving static files by setting config.serve_static_assets to true
+ # * copy engine's public files to application's public folder with <tt>rake ENGINE_NAME:install:assets</tt>, for example
+ # <tt>rake my_engine:install:assets</tt>
+ #
+ # == 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 :as option
+ # * some of the rake tasks are based on engine name, e.g. <tt>my_engine:install:migrations</tt>,
+ # <tt>my_engine:install:assets</tt>
+ #
+ # Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
+ # <tt>my_engine_engine</tt>. You can change it manually it manually using the <tt>engine_name</tt> method:
+ #
+ # module MyEngine
+ # class Engine < Rails::Engine
+ # engine_name "my_engine"
+ # end
+ # end
+ #
+ # == Isolated Engine
+ #
+ # Normally when you create controllers, helpers and models inside an engine, they are treated
+ # as they were created inside the application. This means all application helpers and named routes
+ # will be available to your engine's controllers.
+ #
+ # However, sometimes you want to isolate your engine from the application, 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 behaviour of routes. Normally, when you namespace
+ # your controllers, you also need to do namespace all your routes. With an isolated engine,
+ # the namespace is applied by default, so you can ignore it in routes:
+ #
+ # MyEngine::Engine.routes.draw do
+ # resources :articles
+ # end
+ #
+ # The routes above will automatically point to <tt>MyEngine::ApplicationContoller</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 behaviour consistent with other parts of the framework, an isolated engine also has influence on
+ # <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
+ # use the prefix "my_engine". In an isolated engine, the prefix will be 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 isolated engine will set its name according to namespace, so
+ # MyEngine::Engine.engine_name #=> "my_engine". It will also set MyEngine.table_name_prefix
+ # to "my_engine_", changing MyEngine::Article model to use my_engine_article 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:
+ #
+ # # APP/config/routes.rb
+ # MyApplication::Application.routes.draw do
+ # mount MyEngine::Engine => "/my_engine", :as => "my_engine"
+ # match "/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.
+ #
+ # == 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 application and rerun copying migrations.
+ #
+ # If your engine has migrations, you may also want to prepare data for the database in
+ # the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
+ #
+ # MyEngine::Engine.load_seed
#
class Engine < Railtie
- autoload :Configurable, "rails/engine/configurable"
autoload :Configuration, "rails/engine/configuration"
+ autoload :Railties, "rails/engine/railties"
class << self
- attr_accessor :called_from
-
- # TODO Remove this. It's deprecated.
+ attr_accessor :called_from, :isolated
+ alias :isolated? :isolated
alias :engine_name :railtie_name
def inherited(base)
unless base.abstract_railtie?
base.called_from = begin
# Remove the line number from backtraces making sure we don't leave anything behind
- call_stack = caller.map { |p| p.split(':')[0..-2].join(':') }
- File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] })
+ 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 find_root_with_flag(flag, default=nil)
- root_path = self.called_from
+ def endpoint(endpoint = nil)
+ @endpoint = endpoint if endpoint
+ @endpoint
+ end
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
+ def isolate_namespace(mod)
+ engine_name(generate_railtie_name(mod))
+
+ name = engine_name
+ self.routes.default_scope = {:module => name}
+ self.isolated = true
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
+ unless mod.respond_to?(:_railtie)
+ _railtie = self
+ mod.singleton_class.instance_eval do
+ define_method(:_railtie) do
+ _railtie
+ end
- Config::CONFIG['host_os'] =~ /mswin|mingw/ ?
- Pathname.new(root).expand_path : Pathname.new(root).realpath
+ unless mod.respond_to?(:table_name_prefix)
+ define_method(:table_name_prefix) do
+ "#{name}_"
+ end
+ end
+ end
+ end
+ end
+
+ # Finds engine with given path
+ def find(path)
+ expanded_path = File.expand_path path.to_s
+ Rails::Engine::Railties.engines.find { |engine|
+ File.expand_path(engine.root.to_s) == expanded_path
+ }
end
end
- delegate :paths, :root, :to => :config
+ delegate :middleware, :root, :paths, :to => :config
+ delegate :engine_name, :isolated?, :to => "self.class"
def load_tasks
super
- config.paths.lib.tasks.to_a.sort.each { |ext| load(ext) }
+ paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
end
def eager_load!
@@ -140,6 +406,58 @@ module Rails
end
end
+ def railties
+ @railties ||= self.class::Railties.new(config)
+ end
+
+ def app
+ @app ||= begin
+ config.middleware = config.middleware.merge_into(default_middleware_stack)
+ config.middleware.build(endpoint)
+ end
+ end
+
+ def endpoint
+ self.class.endpoint || routes
+ end
+
+ def call(env)
+ app.call(env.merge!(env_config))
+ end
+
+ def env_config
+ @env_config ||= {
+ 'action_dispatch.routes' => routes,
+ 'action_dispatch.asset_path' => config.asset_path
+ }
+ end
+
+ def routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ @routes.append(&Proc.new) if block_given?
+ @routes
+ end
+
+ def initializers
+ initializers = []
+ railties.all { |r| initializers += r.initializers }
+ initializers += super
+ initializers
+ end
+
+ 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"].existent.first
+ load(seed_file) if File.exist?(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|
@@ -155,7 +473,7 @@ module Rails
# per engine and get the engine as a block parameter
initializer :set_autoload_paths, :before => :bootstrap_hook do |app|
ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
- ActiveSupport::Dependencies.autoload_once_paths.unshift(*config.autoload_once_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
@@ -164,40 +482,50 @@ module Rails
end
initializer :add_routing_paths do |app|
- paths.config.routes.to_a.each do |route|
- app.routes_reloader.paths.unshift(route) if File.exists?(route)
- end
- end
+ paths = self.paths["config/routes"].existent
- # DEPRECATED: Remove in 3.1
- initializer :add_routing_namespaces do |app|
- paths.app.controllers.to_a.each do |load_path|
- load_path = File.expand_path(load_path)
- Dir["#{load_path}/*/**/*_controller.rb"].collect do |path|
- namespace = File.dirname(path).sub(/#{Regexp.escape(load_path)}\/?/, '')
- app.routes.controller_namespaces << namespace unless namespace.empty?
- end
+ 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.to_a)
+ config.i18n.railties_load_path.concat(paths["config/locales"].existent)
end
initializer :add_view_paths do
- views = paths.app.views.to_a
- ActiveSupport.on_load(:action_controller) do
- prepend_view_path(views)
+ views = paths["app/views"].existent
+ unless views.empty?
+ ActiveSupport.on_load(:action_controller){ prepend_view_path(views) }
+ ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
end
- ActiveSupport.on_load(:action_mailer) do
- prepend_view_path(views)
+ end
+
+ initializer :load_environment_config, :before => :load_environment_hook do
+ environment = paths["config/environments"].existent.first
+ require environment if environment
+ end
+
+ initializer :append_asset_paths do
+ config.asset_path ||= default_asset_path
+
+ public_path = paths["public"].first
+ if config.compiled_asset_path && File.exist?(public_path)
+ config.static_asset_paths[config.compiled_asset_path] = public_path
+ end
+ 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
- paths.config.initializers.to_a.sort.each do |initializer|
+ config.paths["config/initializers"].existent.sort.each do |initializer|
load(initializer)
end
end
@@ -207,8 +535,67 @@ module Rails
# consistently executed after all the initializers above across all engines.
end
+ rake_tasks do
+ next if self.is_a?(Rails::Application)
+
+ namespace railtie_name do
+ desc "Shortcut for running both rake #{railtie_name}:install:migrations and #{railtie_name}:install:assets"
+ task :install do
+ Rake::Task["#{railtie_name}:install:migrations"].invoke
+ Rake::Task["#{railtie_name}:install:assets"].invoke
+ end
+
+ namespace :install do
+ # TODO Add assets copying to this list
+ # TODO Skip this if there is no paths["db/migrate"] for the engine
+ desc "Copy migrations from #{railtie_name} to application"
+ task :migrations do
+ ENV["FROM"] = railtie_name
+ Rake::Task["railties:install:migrations"].invoke
+ end
+
+ desc "Copy assets from #{railtie_name} to application"
+ task :assets do
+ ENV["FROM"] = railtie_name
+ Rake::Task["railties:install:assets"].invoke
+ end
+ end
+ end
+ end
+
protected
+ def default_asset_path
+ "/#{railtie_name}%s"
+ end
+
+ def routes?
+ defined?(@routes)
+ end
+
+ def find_root_with_flag(flag, default=nil)
+ 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
+
+ RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ?
+ Pathname.new(root).expand_path : Pathname.new(root).realpath
+ end
+
+ def default_middleware_stack
+ ActionDispatch::MiddlewareStack.new
+ end
+
+ def _all_autoload_once_paths
+ config.autoload_once_paths
+ end
+
def _all_autoload_paths
@_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
end
diff --git a/railties/lib/rails/engine/configurable.rb b/railties/lib/rails/engine/configurable.rb
deleted file mode 100644
index 9a370f0abb..0000000000
--- a/railties/lib/rails/engine/configurable.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-module Rails
- class Engine
- module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
-
- module ClassMethods
- delegate :middleware, :root, :paths, :to => :config
-
- def config
- @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
- end
-
- def inherited(base)
- raise "You cannot inherit from a Rails::Engine child"
- end
- end
-
- def config
- self.class.config
- end
- end
- end
-end \ No newline at end of file
diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb
index 521ed95447..4f458b0aee 100644
--- a/railties/lib/rails/engine/configuration.rb
+++ b/railties/lib/rails/engine/configuration.rb
@@ -4,31 +4,62 @@ module Rails
class Engine
class Configuration < ::Rails::Railtie::Configuration
attr_reader :root
- attr_writer :eager_load_paths, :autoload_once_paths, :autoload_paths
+ attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths
+ attr_accessor :plugins, :asset_path
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 :datamapper, :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.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.mailers "app/mailers", :eager_load => true
- paths.app.views "app/views"
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths.public "public"
- paths.public.javascripts "public/javascripts"
- paths.public.stylesheets "public/stylesheets"
+ paths.add "app", :eager_load => true, :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 "lib", :load_path => true
+ 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", :with => "config/routes.rb"
+ paths.add "db"
+ paths.add "db/migrate"
+ paths.add "db/seeds", :with => "db/seeds.rb"
+ paths.add "public"
+ paths.add "public/javascripts"
+ paths.add "public/stylesheets"
+ paths.add "vendor", :load_path => true
+ paths.add "vendor/plugins"
paths
end
end
@@ -48,6 +79,10 @@ module Rails
def autoload_paths
@autoload_paths ||= paths.autoload_paths
end
+
+ def compiled_asset_path
+ asset_path % "" if asset_path
+ 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 0000000000..d5ecd2e48d
--- /dev/null
+++ b/railties/lib/rails/engine/railties.rb
@@ -0,0 +1,33 @@
+module Rails
+ class Engine < Railtie
+ class Railties
+ # TODO Write tests for this behavior extracted from Application
+ def initialize(config)
+ @config = config
+ end
+
+ def all(&block)
+ @all ||= plugins
+ @all.each(&block) if block
+ @all
+ end
+
+ def plugins
+ @plugins ||= begin
+ plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
+ Plugin.all(plugin_names, @config.paths["vendor/plugins"].existent)
+ end
+ end
+
+ def self.railties
+ @railties ||= ::Rails::Railtie.subclasses.map(&:instance)
+ end
+
+ def self.engines
+ @engines ||= ::Rails::Engine.subclasses.map(&:instance)
+ end
+
+ delegate :railties, :engines, :to => "self.class"
+ end
+ end
+end
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 8794392a7d..29e693dfb0 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -140,10 +140,7 @@ module Rails
lookup(lookups)
- namespaces = subclasses.inject({}) do |hash, klass|
- hash[klass.namespace] = klass
- hash
- end
+ namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }]
lookups.each do |namespace|
klass = namespaces[namespace]
@@ -158,7 +155,7 @@ module Rails
# commands.
def self.invoke(namespace, args=ARGV, config={})
names = namespace.to_s.split(':')
- if klass = find_by_namespace(names.pop, names.shift)
+ if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
klass.start(args, config)
else
@@ -218,11 +215,11 @@ module Rails
puts "Usage: rails #{command} GENERATOR [args] [options]"
puts
puts "General options:"
- puts " -h, [--help] # Print generators options and usage"
+ 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] # Supress status output"
+ puts " -q, [--quiet] # Suppress status output"
puts
puts "Please choose a generator below."
puts
@@ -231,6 +228,7 @@ module Rails
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) }
@@ -304,6 +302,7 @@ module Rails
$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 => e
# No problem
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index 668ef48892..c323df3e95 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -1,5 +1,4 @@
require 'open-uri'
-require 'active_support/deprecation'
require 'rbconfig'
module Rails
@@ -45,7 +44,7 @@ module Rails
#
# ==== Example
#
- # gem "rspec", :env => :test
+ # 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"
#
@@ -53,20 +52,6 @@ module Rails
options = args.extract_options!
name, version = args
- # Deal with deprecated options
- { :env => :group, :only => :group,
- :lib => :require, :require_as => :require }.each do |old, new|
- next unless options[old]
- options[new] = options.delete(old)
- ActiveSupport::Deprecation.warn "#{old.inspect} option in gem is deprecated, use #{new.inspect} instead"
- end
-
- # Deal with deprecated source
- if source = options.delete(:source)
- ActiveSupport::Deprecation.warn ":source option in gem is deprecated, use add_source method instead"
- add_source(source)
- end
-
# 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
@@ -202,8 +187,8 @@ module Rails
# initializer("globals.rb") do
# data = ""
#
- # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do
- # data << "#{const} = :entp"
+ # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do |const|
+ # data << "#{const} = :entp\n"
# end
#
# data
@@ -242,7 +227,7 @@ module Rails
def rake(command, options={})
log :rake, command
env = options[:env] || 'development'
- sudo = options[:sudo] && Config::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : ''
+ sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : ''
in_root { run("#{sudo}#{extify(:rake)} #{command} RAILS_ENV=#{env}", :verbose => false) }
end
@@ -257,16 +242,6 @@ module Rails
in_root { run("#{extify(:capify)} .", :verbose => false) }
end
- # Add Rails to /vendor/rails
- #
- # ==== Example
- #
- # freeze!
- #
- def freeze!(args={})
- ActiveSupport::Deprecation.warn "freeze! is deprecated since your rails app now comes bundled with Rails by default, please check your Gemfile"
- end
-
# Make an entry in Rails routing file config/routes.rb
#
# === Example
@@ -289,17 +264,18 @@ module Rails
# readme "README"
#
def readme(path)
- say File.read(find_in_source_paths(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.
+ # 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
+ say args.first.to_s unless options.quiet?
else
args << (self.behavior == :invoke ? :green : :red)
say_status *args
@@ -309,7 +285,7 @@ module Rails
# Add an extension to the given name based on the platform.
#
def extify(name)
- if Config::CONFIG['host_os'] =~ /mswin|mingw/
+ if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
"#{name}.bat"
else
name
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
new file mode 100644
index 0000000000..ab7ed4eb9e
--- /dev/null
+++ b/railties/lib/rails/generators/app_base.rb
@@ -0,0 +1,170 @@
+require 'digest/md5'
+require 'active_support/secure_random'
+require 'rails/version' unless defined?(Rails::VERSION)
+require 'rbconfig'
+require 'open-uri'
+require 'uri'
+
+module Rails
+ module Generators
+ class AppBase < Base
+ DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ JAVASCRIPTS = %w( prototype jquery )
+
+ attr_accessor :rails_template
+ add_shebang_option!
+
+ argument :app_path, :type => :string
+
+ def self.add_shared_options_for(name)
+ class_option :builder, :type => :string, :aliases => "-b",
+ :desc => "Path to a #{name} builder (can be a filesystem path or URL)"
+
+ class_option :template, :type => :string, :aliases => "-m",
+ :desc => "Path to an #{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_git, :type => :boolean, :aliases => "-G", :default => false,
+ :desc => "Skip Git ignores and keeps"
+
+ class_option :skip_active_record, :type => :boolean, :aliases => "-O", :default => false,
+ :desc => "Skip Active Record 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 => "prototype",
+ :desc => "Preconfigure for selected javascript library (options: #{JAVASCRIPTS.join('/')})"
+
+ 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 :help, :type => :boolean, :aliases => "-h", :group => :rails,
+ :desc => "Show this help message and quit"
+ end
+
+ def initialize(*args)
+ @original_wd = Dir.pwd
+
+ super
+ end
+
+ protected
+
+ def builder
+ @builder ||= begin
+ if path = options[:builder]
+ if URI(path).is_a?(URI::HTTP)
+ contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read }
+ else
+ contents = open(File.expand_path(path, @original_wd)) {|io| io.read }
+ end
+
+ prok = eval("proc { #{contents} }", TOPLEVEL_BINDING, path, 1)
+ instance_eval(&prok)
+ end
+
+ 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] ? "" : "gem '#{gem_for_database}'"
+ end
+
+ def rails_gemfile_entry
+ if options.dev?
+ <<-GEMFILE
+gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}'
+gem 'arel', :git => 'git://github.com/rails/arel.git'
+gem "rack", :git => "git://github.com/rack/rack.git"
+ GEMFILE
+ elsif options.edge?
+ <<-GEMFILE
+gem 'rails', :git => 'git://github.com/rails/rails.git'
+gem 'arel', :git => 'git://github.com/rails/arel.git'
+gem "rack", :git => "git://github.com/rack/rack.git"
+ GEMFILE
+ else
+ <<-GEMFILE
+gem 'rails', '#{Rails::VERSION::STRING}'
+
+# Bundle edge Rails instead:
+# gem 'rails', :git => 'git://github.com/rails/rails.git'
+# gem 'arel', :git => 'git://github.com/rails/arel.git'
+# gem "rack", :git => "git://github.com/rack/rack.git"
+ GEMFILE
+ end
+ end
+
+ def gem_for_database
+ # %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ case options[:database]
+ when "oracle" then "ruby-oci8"
+ when "postgresql" then "pg"
+ when "frontbase" then "ruby-frontbase"
+ when "mysql" then "mysql2"
+ else options[:database]
+ end
+ end
+
+ def bundle_if_dev_or_edge
+ bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
+ run "#{bundle_command} install" if dev_or_edge?
+ end
+
+ def dev_or_edge?
+ options.dev? || options.edge?
+ end
+
+ def empty_directory_with_gitkeep(destination, config = {})
+ empty_directory(destination, config)
+ create_file("#{destination}/.gitkeep") unless options[:skip_git]
+ end
+
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index fdfceb14ce..dfecd2a6e4 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -3,7 +3,7 @@ begin
rescue LoadError
puts "Thor is not available.\nIf you ran this command from a git checkout " \
"of Rails, please make sure thor is installed,\nand run this command " \
- "as `ruby #{$0} #{ARGV.join(" ")} --dev`"
+ "as `ruby #{$0} #{(ARGV | ['--dev']).join(" ")}`"
exit
end
@@ -81,7 +81,7 @@ module Rails
# 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
+ # 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
@@ -274,7 +274,7 @@ module Rails
# Use Rails default banner.
#
def self.banner
- "rails generate #{generator_name} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]"
+ "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ')
end
# Sets the base_name taking into account the current class namespace.
diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb
index 3b9fff2f4a..64273e4ca4 100644
--- a/railties/lib/rails/generators/generated_attribute.rb
+++ b/railties/lib/rails/generators/generated_attribute.rb
@@ -6,6 +6,7 @@ module Rails
attr_accessor :name, :type
def initialize(name, type)
+ raise Thor::Error, "Missing type for attribute '#{name}'.\nExample: '#{name}:string' where string is the type." if type.blank?
@name, @type = name, type.to_sym
end
diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb
index 9244307261..0c5c4f6e09 100644
--- a/railties/lib/rails/generators/migration.rb
+++ b/railties/lib/rails/generators/migration.rb
@@ -52,8 +52,12 @@ module Rails
destination = self.class.migration_exists?(migration_dir, @migration_file_name)
- if behavior == :invoke
- raise Error, "Another migration is already named #{@migration_file_name}: #{destination}" if destination
+ 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}"
+ end
destination = File.join(migration_dir, "#{@migration_number}_#{@migration_file_name}.rb")
end
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index 44f831e6f3..2af7f85463 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -5,6 +5,8 @@ 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:
# Unfreeze name in case it's given as a frozen string
@@ -14,17 +16,78 @@ module Rails
parse_attributes! if respond_to?(:attributes)
end
- protected
+ no_tasks do
+ def template(source, *args, &block)
+ inside_template do
+ super
+ end
+ end
+ end
- attr_reader :class_path, :file_name
+ 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 = content.each_line.map {|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
+ @namespace ||= if defined?(Rails) && Rails.application
+ Rails.application.class.parents.detect { |n| n.respond_to?(:_railtie) }
+ end
+ 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_class_path
+ @namespaced_class_path ||= begin
+ namespace_path = namespace.name.split("::").map {|m| m.underscore }
+ namespace_path + @class_path
+ end
+ end
+
def class_name
- @class_name ||= (class_path + [file_name]).map!{ |m| m.camelize }.join('::')
+ (class_path + [file_name]).map!{ |m| m.camelize }.join('::')
end
def human_name
@@ -55,11 +118,11 @@ module Rails
end
def singular_table_name
- @singular_table_name ||= table_name.singularize
+ @singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name)
end
def plural_table_name
- @plural_table_name ||= table_name.pluralize
+ @plural_table_name ||= (pluralize_table_names? ? table_name : table_name.pluralize)
end
def plural_file_name
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index a90f109844..3f6ff35a86 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -1,9 +1,4 @@
-require 'digest/md5'
-require 'active_support/secure_random'
-require 'rails/version' unless defined?(Rails::VERSION)
-require 'rbconfig'
-require 'open-uri'
-require 'uri'
+require 'rails/generators/app_base'
module Rails
module ActionMethods
@@ -14,23 +9,20 @@ module Rails
@options = generator.options
end
- private
- %w(template copy_file directory empty_directory inside
- empty_directory_with_gitkeep 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
+ private
- # TODO: Remove once this is fully in place
- def method_missing(meth, *args, &block)
- STDERR.puts "Calling #{meth} with #{args.inspect} with #{block}"
- @generator.send(meth, *args, &block)
- end
+ 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"
@@ -71,7 +63,7 @@ module Rails
end
def database_yml
- template "config/databases/#{@options[:database]}.yml", "config/database.yml"
+ template "config/databases/#{options[:database]}.yml", "config/database.yml"
end
def db
@@ -111,12 +103,20 @@ module Rails
end
def javascripts
- unless options[:skip_prototype]
- directory "public/javascripts"
- else
- empty_directory_with_gitkeep "public/javascripts"
- create_file "public/javascripts/application.js"
+ empty_directory "public/javascripts"
+
+ unless options[:skip_javascript]
+ copy_file "public/javascripts/#{options[:javascript]}.js"
+ copy_file "public/javascripts/#{options[:javascript]}_ujs.js", "public/javascripts/rails.js"
+
+ if options[:javascript] == "prototype"
+ copy_file "public/javascripts/controls.js"
+ copy_file "public/javascripts/dragdrop.js"
+ copy_file "public/javascripts/effects.js"
+ end
end
+
+ copy_file "public/javascripts/application.js"
end
def script
@@ -153,71 +153,28 @@ module Rails
RESERVED_NAMES = %w[application destroy benchmarker profiler
plugin runner test]
- class AppGenerator < Base
- DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
-
- attr_accessor :rails_template
- add_shebang_option!
-
- argument :app_path, :type => :string
-
- class_option :database, :type => :string, :aliases => "-d", :default => "sqlite3",
- :desc => "Preconfigure for selected database (options: #{DATABASES.join('/')})"
-
- class_option :builder, :type => :string, :aliases => "-b",
- :desc => "Path to an application builder (can be a filesystem path or URL)"
-
- class_option :template, :type => :string, :aliases => "-m",
- :desc => "Path to an application template (can be a filesystem path or URL)"
-
- class_option :dev, :type => :boolean, :default => false,
- :desc => "Setup the application with Gemfile pointing to your Rails checkout"
-
- class_option :edge, :type => :boolean, :default => false,
- :desc => "Setup the application with Gemfile pointing to Rails repository"
-
- class_option :skip_gemfile, :type => :boolean, :default => false,
- :desc => "Don't create a Gemfile"
-
- class_option :skip_active_record, :type => :boolean, :aliases => "-O", :default => false,
- :desc => "Skip Active Record files"
-
- class_option :skip_test_unit, :type => :boolean, :aliases => "-T", :default => false,
- :desc => "Skip Test::Unit files"
-
- class_option :skip_prototype, :type => :boolean, :aliases => "-J", :default => false,
- :desc => "Skip Prototype files"
-
- class_option :skip_git, :type => :boolean, :aliases => "-G", :default => false,
- :desc => "Skip Git ignores and keeps"
+ class AppGenerator < AppBase
+ 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"
- class_option :help, :type => :boolean, :aliases => "-h", :group => :rails,
- :desc => "Show this help message and quit"
-
def initialize(*args)
raise Error, "Options should be given after the application name. For details run: rails --help" if args[0].blank?
- @original_wd = Dir.pwd
-
super
if !options[:skip_active_record] && !DATABASES.include?(options[:database])
raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}."
end
+
+ if !options[:skip_javascript] && !JAVASCRIPTS.include?(options[:javascript])
+ raise Error, "Invalid value for --javascript option. Supported for preconfiguration are: #{JAVASCRIPTS.join(", ")}."
+ end
end
- def create_root
- self.destination_root = File.expand_path(app_path, destination_root)
- valid_app_const?
-
- empty_directory '.'
- set_default_accessors!
- FileUtils.cd(destination_root) unless options[:pretend]
- end
+ public_task :create_root
def create_root_files
build(:readme)
@@ -272,7 +229,7 @@ module Rails
build(:stylesheets)
end
- def create_prototype_files
+ def create_javascript_files
build(:javascripts)
end
@@ -296,16 +253,7 @@ module Rails
build(:leftovers)
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 bundle_if_dev_or_edge
- bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
- run "#{bundle_command} install" if dev_or_edge?
- end
+ public_task :apply_rails_template, :bundle_if_dev_or_edge
protected
@@ -313,47 +261,17 @@ module Rails
"rails new #{self.arguments.map(&:usage).join(' ')} [options]"
end
- def builder
- @builder ||= begin
- if path = options[:builder]
- if URI(path).is_a?(URI::HTTP)
- contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read }
- else
- contents = open(File.expand_path(path, @original_wd)) {|io| io.read }
- end
-
- prok = eval("proc { #{contents} }", TOPLEVEL_BINDING, path, 1)
- instance_eval(&prok)
- end
-
- builder_class = defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
- 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 set_default_accessors!
- self.rails_template = case options[:template]
- when /^http:\/\//
- options[:template]
- when String
- File.expand_path(options[:template], Dir.pwd)
- else
- options[:template]
- end
- 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 ||= File.basename(destination_root)
+ @app_name ||= defined_app_const_base? ? defined_app_name : File.basename(destination_root)
+ end
+
+ def defined_app_name
+ defined_app_const_base.underscore
end
def defined_app_const_base
@@ -361,15 +279,18 @@ module Rails
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_app_const?
+ 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)
@@ -383,27 +304,6 @@ module Rails
ActiveSupport::SecureRandom.hex(64)
end
- def dev_or_edge?
- options.dev? || options.edge?
- end
-
- def gem_for_database
- # %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
- case options[:database]
- when "oracle" then "ruby-oci8"
- when "postgresql" then "pg"
- when "sqlite3" then "sqlite3-ruby"
- when "frontbase" then "ruby-frontbase"
- else options[:database]
- end
- end
-
- def require_for_database
- case options[:database]
- when "sqlite3" then "sqlite3"
- end
- end
-
def mysql_socket
@mysql_socket ||= [
"/tmp/mysql.sock", # default
@@ -415,12 +315,11 @@ module Rails
"/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 Config::CONFIG['host_os'] =~ /mswin|mingw/
+ ].find { |f| File.exist?(f) } unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
end
- def empty_directory_with_gitkeep(destination, config = {})
- empty_directory(destination, config)
- create_file("#{destination}/.gitkeep") unless options[:skip_git]
+ def get_builder_class
+ defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
end
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 1980684a94..c383d4842f 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -1,21 +1,8 @@
source 'http://rubygems.org'
-<%- if options.dev? -%>
-gem 'rails', :path => '<%= Rails::Generators::RAILS_DEV_PATH %>'
-gem 'arel', :git => 'git://github.com/rails/arel.git'
-<%- elsif options.edge? -%>
-gem 'rails', :git => 'git://github.com/rails/rails.git'
-gem 'arel', :git => 'git://github.com/rails/arel.git'
-<%- else -%>
-gem 'rails', '<%= Rails::VERSION::STRING %>'
-
-# Bundle edge Rails instead:
-# gem 'rails', :git => 'git://github.com/rails/rails.git'
-<%- end -%>
-
-<% unless options[:skip_activerecord] -%>
-gem '<%= gem_for_database %>'<% if require_for_database %>, :require => '<%= require_for_database %>'<% end %>
-<% end -%>
+<%= rails_gemfile_entry -%>
+
+<%= database_gemfile_entry -%>
# Use unicorn as the web server
# gem 'unicorn'
@@ -23,14 +10,15 @@ gem '<%= gem_for_database %>'<% if require_for_database %>, :require => '<%= req
# Deploy with Capistrano
# gem 'capistrano'
-# To use debugger
+# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
+# gem 'ruby-debug19', :require => 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
-# gem 'sqlite3-ruby', :require => 'sqlite3'
-# gem 'aws-s3', :require => 'aws/s3'
+# gem 'sqlite3'
+# gem 'rack-bug', :require => 'rack/bug'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
@@ -38,3 +26,6 @@ gem '<%= gem_for_database %>'<% if require_for_database %>, :require => '<%= req
# group :development, :test do
# gem 'webrat'
# end
+
+# Needed for guides generation
+# gem "RedCloth", "~> 4.2"
diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README
index 6966fe987e..9f0f1d0e38 100644
--- a/railties/lib/rails/generators/rails/app/templates/README
+++ b/railties/lib/rails/generators/rails/app/templates/README
@@ -91,7 +91,7 @@ mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
- @posts = Post.find(:all)
+ @posts = Post.all
debugger
end
end
@@ -139,7 +139,7 @@ To reload your controllers and models after launching the console run
<tt>reload!</tt>
More information about irb can be found at:
-link:http://www.rubycentral.com/pickaxe/irb.html
+link:http://www.rubycentral.org/pickaxe/irb.html
== dbconsole
@@ -158,6 +158,7 @@ The default directory structure of a generated Ruby on Rails application:
|-- app
| |-- controllers
| |-- helpers
+ | |-- mailers
| |-- models
| `-- views
| `-- layouts
@@ -175,7 +176,6 @@ The default directory structure of a generated Ruby on Rails application:
| |-- javascripts
| `-- stylesheets
|-- script
- | `-- performance
|-- test
| |-- fixtures
| |-- functional
diff --git a/railties/lib/rails/generators/rails/app/templates/Rakefile b/railties/lib/rails/generators/rails/app/templates/Rakefile
index d83cafc3be..4dc1023f1f 100644..100755
--- a/railties/lib/rails/generators/rails/app/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/app/templates/Rakefile
@@ -1,7 +1,7 @@
+#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
-require 'rake'
<%= app_const %>.load_tasks
diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
index 1dd112b4a6..6d56c331c1 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
@@ -1,10 +1,10 @@
<!DOCTYPE html>
<html>
<head>
- <title><%= app_const_base %></title>
+ <title><%= camelized %></title>
<%%= stylesheet_link_tag :all %>
<%%= javascript_include_tag :defaults %>
- <%%= csrf_meta_tag %>
+ <%%= csrf_meta_tags %>
</head>
<body>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index 7d63e99e05..b7f64af339 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -40,16 +40,27 @@ module <%= app_const_base %>
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
-<% if options[:skip_prototype] -%>
+<% if options[:skip_javascript] -%>
config.action_view.javascript_expansions[:defaults] = %w()
+<% elsif options[:javascript] == 'jquery' -%>
+ config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
<% else -%>
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
<% end -%>
+<% if options[:skip_test_unit] -%>
+ config.generators.test_framework = false
+<% end -%>
+
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
+
+<% unless options[:skip_active_record] -%>
+ # Enable IdentityMap for Active Record, to disable set to false or remove the line below.
+ config.active_record.identity_map = true
+<% end -%>
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/boot.rb b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
index ab6cb374de..4489e58688 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/boot.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
@@ -1,13 +1,6 @@
require 'rubygems'
# Set up gems listed in the Gemfile.
-gemfile = File.expand_path('../../Gemfile', __FILE__)
-begin
- ENV['BUNDLE_GEMFILE'] = gemfile
- require 'bundler'
- Bundler.setup
-rescue Bundler::GemNotFound => e
- STDERR.puts e.message
- STDERR.puts "Try running `bundle install`."
- exit!
-end if File.exist?(gemfile)
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
index ffc8a0a8cb..5d28c7c312 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
@@ -1,21 +1,12 @@
# MySQL. Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
-# gem install mysql
-# On Mac OS X:
-# sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
-# On Mac OS X Leopard:
-# sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
-# This sets the ARCHFLAGS environment variable to your native architecture
-# On Windows:
-# gem install mysql
-# Choose the win32 build.
-# Install MySQL and put its /bin directory on your path.
+# gem install mysql2
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
- adapter: mysql
+ adapter: mysql2
encoding: utf8
reconnect: false
database: <%= app_name %>_development
@@ -32,7 +23,7 @@ development:
# 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
+ adapter: mysql2
encoding: utf8
reconnect: false
database: <%= app_name %>_test
@@ -46,7 +37,7 @@ test:
<% end -%>
production:
- adapter: mysql
+ adapter: mysql2
encoding: utf8
reconnect: false
database: <%= app_name %>_production
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
index fddf8b8144..b661a60389 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
@@ -10,7 +10,7 @@
#
# 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 configation below; the defaults
+# to 'similar'. Both can be changed in the configuration below; the defaults
# are equivalent to specifying:
#
# prefetch_rows: 100
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
index 025d62a8d8..90d87cc295 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
@@ -1,5 +1,5 @@
# SQLite version 3.x
-# gem install sqlite3-ruby (not necessary on OS X Leopard)
+# gem install sqlite3
development:
adapter: sqlite3
database: db/development.sqlite3
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 7616614aff..91d3133ea4 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -1,5 +1,5 @@
<%= app_const %>.configure do
- # Settings specified here will take precedence over those in config/environment.rb
+ # 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
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
index 500fc4d860..89bb891ddd 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -1,5 +1,5 @@
<%= app_const %>.configure do
- # Settings specified here will take precedence over those in config/environment.rb
+ # Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
index 26cdef071a..d8d1e55157 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -1,5 +1,5 @@
<%= app_const %>.configure do
- # Settings specified here will take precedence over those in config/environment.rb
+ # 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
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
index 0aed79bb70..62aa06dc3e 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
@@ -4,5 +4,5 @@
# 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 "rake db:sessions:create")
+# (create the session table with "rails generate session_migration")
# <%= app_const %>.config.session_store :active_record_store
diff --git a/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
index a747bfa698..179c14ca52 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
@@ -1,5 +1,5 @@
# Sample localization file for English. Add more files in this directory for other locales.
-# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
hello: "Hello world"
diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
index d42cf3bfdf..d50f536164 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
@@ -16,12 +16,12 @@
# Sample resource route with options:
# resources :products do
# member do
- # get :short
- # post :toggle
+ # get 'short'
+ # post 'toggle'
# end
#
# collection do
- # get :sold
+ # get 'sold'
# end
# end
@@ -35,7 +35,7 @@
# resources :products do
# resources :comments
# resources :sales do
- # get :recent, :on => :collection
+ # get 'recent', :on => :collection
# end
# end
@@ -48,7 +48,7 @@
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
- # root :to => "welcome#index"
+ # root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index af64fae5e7..f0fa30c536 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -1,4 +1,4 @@
.bundle
db/*.sqlite3
log/*.log
-tmp/**/*
+tmp/
diff --git a/railties/lib/rails/generators/rails/app/templates/public/index.html b/railties/lib/rails/generators/rails/app/templates/public/index.html
index 75d5edd06d..13a203dd08 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/index.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/index.html
@@ -52,7 +52,6 @@
clear: both;
}
-
#header, #about, #getting-started {
padding-left: 75px;
padding-right: 30px;
@@ -168,6 +167,9 @@
margin-bottom: 5px;
}
+ .filename {
+ font-style: italic;
+ }
</style>
<script type="text/javascript">
function about() {
@@ -190,10 +192,10 @@
<li>
<h3>Browse the documentation</h3>
<ul class="links">
- <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
- <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
- <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
<li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
+ <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
+ <li><a href="http://www.ruby-doc.org/core/">Ruby core</a></li>
+ <li><a href="http://www.ruby-doc.org/stdlib/">Ruby standard library</a></li>
</ul>
</li>
</ul>
@@ -221,13 +223,13 @@
</li>
<li>
- <h2>Set up a default route and remove or rename this file</h2>
- <p>Routes are set up in config/routes.rb.</p>
+ <h2>Set up a default route and remove <span class="filename">public/index.html</span></h2>
+ <p>Routes are set up in <span class="filename">config/routes.rb</span>.</p>
</li>
<li>
<h2>Create your database</h2>
- <p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p>
+ <p>Run <code>rake db:create</code> to create your database. If you're not using SQLite (the default), edit <span class="filename">config/database.yml</span> with your username and password.</p>
</li>
</ol>
</div>
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js
index 066ee5909c..c81e6c7d5f 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/effects.js
@@ -150,7 +150,7 @@ var Effect = {
toggle: function(element, effect, options) {
element = $(element);
effect = (effect || 'appear').toLowerCase();
-
+
return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
}, options || {}));
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
new file mode 100644
index 0000000000..aa3a4f34fd
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
@@ -0,0 +1,8176 @@
+/*!
+ * jQuery JavaScript Library v1.5
+ * http://jquery.com/
+ *
+ * Copyright 2011, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Mon Jan 31 08:31:29 2011 -0500
+ */
+(function( window, undefined ) {
+
+// Use the correct document accordingly with window argument (sandbox)
+var document = window.document;
+var jQuery = (function() {
+
+// Define a local copy of jQuery
+var jQuery = function( selector, context ) {
+ // The jQuery object is actually just the init constructor 'enhanced'
+ return new jQuery.fn.init( selector, context, rootjQuery );
+ },
+
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+
+ // Map over the $ in case of overwrite
+ _$ = window.$,
+
+ // A central reference to the root jQuery(document)
+ rootjQuery,
+
+ // A simple way to check for HTML strings or ID strings
+ // (both of which we optimize for)
+ quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
+
+ // Check if a string has a non-whitespace character in it
+ rnotwhite = /\S/,
+
+ // Used for trimming whitespace
+ trimLeft = /^\s+/,
+ trimRight = /\s+$/,
+
+ // Check for digits
+ rdigit = /\d/,
+
+ // Match a standalone tag
+ rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
+
+ // JSON RegExp
+ rvalidchars = /^[\],:{}\s]*$/,
+ rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
+ rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
+ rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
+
+ // Useragent RegExp
+ rwebkit = /(webkit)[ \/]([\w.]+)/,
+ ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
+ rmsie = /(msie) ([\w.]+)/,
+ rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
+
+ // Keep a UserAgent string for use with jQuery.browser
+ userAgent = navigator.userAgent,
+
+ // For matching the engine and version of the browser
+ browserMatch,
+
+ // Has the ready events already been bound?
+ readyBound = false,
+
+ // The deferred used on DOM ready
+ readyList,
+
+ // Promise methods
+ promiseMethods = "then done fail isResolved isRejected promise".split( " " ),
+
+ // The ready event handler
+ DOMContentLoaded,
+
+ // Save a reference to some core methods
+ toString = Object.prototype.toString,
+ hasOwn = Object.prototype.hasOwnProperty,
+ push = Array.prototype.push,
+ slice = Array.prototype.slice,
+ trim = String.prototype.trim,
+ indexOf = Array.prototype.indexOf,
+
+ // [[Class]] -> type pairs
+ class2type = {};
+
+jQuery.fn = jQuery.prototype = {
+ constructor: jQuery,
+ init: function( selector, context, rootjQuery ) {
+ var match, elem, ret, doc;
+
+ // Handle $(""), $(null), or $(undefined)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle $(DOMElement)
+ if ( selector.nodeType ) {
+ this.context = this[0] = selector;
+ this.length = 1;
+ return this;
+ }
+
+ // The body element only exists once, optimize finding it
+ if ( selector === "body" && !context && document.body ) {
+ this.context = document;
+ this[0] = document.body;
+ this.selector = "body";
+ this.length = 1;
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ // Are we dealing with HTML string or an ID?
+ match = quickExpr.exec( selector );
+
+ // Verify a match, and that no context was specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
+ doc = (context ? context.ownerDocument || context : document);
+
+ // If a single string is passed in and it's a single tag
+ // just do a createElement and skip the rest
+ ret = rsingleTag.exec( selector );
+
+ if ( ret ) {
+ if ( jQuery.isPlainObject( context ) ) {
+ selector = [ document.createElement( ret[1] ) ];
+ jQuery.fn.attr.call( selector, context, true );
+
+ } else {
+ selector = [ doc.createElement( ret[1] ) ];
+ }
+
+ } else {
+ ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
+ selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
+ }
+
+ return jQuery.merge( this, selector );
+
+ // HANDLE: $("#id")
+ } else {
+ elem = document.getElementById( match[2] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id !== match[2] ) {
+ return rootjQuery.find( selector );
+ }
+
+ // Otherwise, we inject the element directly into the jQuery object
+ this.length = 1;
+ this[0] = elem;
+ }
+
+ this.context = document;
+ this.selector = selector;
+ return this;
+ }
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return (context || rootjQuery).find( selector );
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return this.constructor( context ).find( selector );
+ }
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) ) {
+ return rootjQuery.ready( selector );
+ }
+
+ if (selector.selector !== undefined) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.makeArray( selector, this );
+ },
+
+ // Start with an empty selector
+ selector: "",
+
+ // The current version of jQuery being used
+ jquery: "1.5",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ // The number of elements contained in the matched element set
+ size: function() {
+ return this.length;
+ },
+
+ toArray: function() {
+ return slice.call( this, 0 );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num == null ?
+
+ // Return a 'clean' array
+ this.toArray() :
+
+ // Return just the object
+ ( num < 0 ? this[ this.length + num ] : this[ num ] );
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems, name, selector ) {
+ // Build a new jQuery matched element set
+ var ret = this.constructor();
+
+ if ( jQuery.isArray( elems ) ) {
+ push.apply( ret, elems );
+
+ } else {
+ jQuery.merge( ret, elems );
+ }
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+
+ ret.context = this.context;
+
+ if ( name === "find" ) {
+ ret.selector = this.selector + (this.selector ? " " : "") + selector;
+ } else if ( name ) {
+ ret.selector = this.selector + "." + name + "(" + selector + ")";
+ }
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function( callback, args ) {
+ return jQuery.each( this, callback, args );
+ },
+
+ ready: function( fn ) {
+ // Attach the listeners
+ jQuery.bindReady();
+
+ // Add the callback
+ readyList.done( fn );
+
+ return this;
+ },
+
+ eq: function( i ) {
+ return i === -1 ?
+ this.slice( i ) :
+ this.slice( i, +i + 1 );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ),
+ "slice", slice.call(arguments).join(",") );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ end: function() {
+ return this.prevObject || this.constructor(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+ var options, name, src, copy, copyIsArray, clone,
+ target = arguments[0] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+ target = arguments[1] || {};
+ // skip the boolean and the target
+ i = 2;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+ target = {};
+ }
+
+ // extend jQuery itself if only one argument is passed
+ if ( length === i ) {
+ target = this;
+ --i;
+ }
+
+ for ( ; i < length; i++ ) {
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null ) {
+ // Extend the base object
+ for ( name in options ) {
+ src = target[ name ];
+ copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging plain objects or arrays
+ if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+ if ( copyIsArray ) {
+ copyIsArray = false;
+ clone = src && jQuery.isArray(src) ? src : [];
+
+ } else {
+ clone = src && jQuery.isPlainObject(src) ? src : {};
+ }
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ noConflict: function( deep ) {
+ window.$ = _$;
+
+ if ( deep ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+ },
+
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // A counter to track how many items to wait for before
+ // the ready event fires. See #6781
+ readyWait: 1,
+
+ // Handle when the DOM is ready
+ ready: function( wait ) {
+ // A third-party is pushing the ready event forwards
+ if ( wait === true ) {
+ jQuery.readyWait--;
+ }
+
+ // Make sure that the DOM is not already loaded
+ if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( !document.body ) {
+ return setTimeout( jQuery.ready, 1 );
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If a normal DOM Ready event fired, decrement, and wait if need be
+ if ( wait !== true && --jQuery.readyWait > 0 ) {
+ return;
+ }
+
+ // If there are functions bound, to execute
+ readyList.resolveWith( document, [ jQuery ] );
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.trigger ) {
+ jQuery( document ).trigger( "ready" ).unbind( "ready" );
+ }
+ }
+ },
+
+ bindReady: function() {
+ if ( readyBound ) {
+ return;
+ }
+
+ readyBound = true;
+
+ // Catch cases where $(document).ready() is called after the
+ // browser event has already occurred.
+ if ( document.readyState === "complete" ) {
+ // Handle it asynchronously to allow scripts the opportunity to delay ready
+ return setTimeout( jQuery.ready, 1 );
+ }
+
+ // Mozilla, Opera and webkit nightlies currently support this event
+ if ( document.addEventListener ) {
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+
+ // A fallback to window.onload, that will always work
+ window.addEventListener( "load", jQuery.ready, false );
+
+ // If IE event model is used
+ } else if ( document.attachEvent ) {
+ // ensure firing before onload,
+ // maybe late but safe also for iframes
+ document.attachEvent("onreadystatechange", DOMContentLoaded);
+
+ // A fallback to window.onload, that will always work
+ window.attachEvent( "onload", jQuery.ready );
+
+ // If IE and not a frame
+ // continually check to see if the document is ready
+ var toplevel = false;
+
+ try {
+ toplevel = window.frameElement == null;
+ } catch(e) {}
+
+ if ( document.documentElement.doScroll && toplevel ) {
+ doScrollCheck();
+ }
+ }
+ },
+
+ // See test/unit/core.js for details concerning isFunction.
+ // Since version 1.3, DOM methods and functions like alert
+ // aren't supported. They return false on IE (#2968).
+ isFunction: function( obj ) {
+ return jQuery.type(obj) === "function";
+ },
+
+ isArray: Array.isArray || function( obj ) {
+ return jQuery.type(obj) === "array";
+ },
+
+ // A crude way of determining if an object is a window
+ isWindow: function( obj ) {
+ return obj && typeof obj === "object" && "setInterval" in obj;
+ },
+
+ isNaN: function( obj ) {
+ return obj == null || !rdigit.test( obj ) || isNaN( obj );
+ },
+
+ type: function( obj ) {
+ return obj == null ?
+ String( obj ) :
+ class2type[ toString.call(obj) ] || "object";
+ },
+
+ isPlainObject: function( obj ) {
+ // Must be an Object.
+ // Because of IE, we also have to check the presence of the constructor property.
+ // Make sure that DOM nodes and window objects don't pass through, as well
+ if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ // Not own constructor property must be Object
+ if ( obj.constructor &&
+ !hasOwn.call(obj, "constructor") &&
+ !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
+ return false;
+ }
+
+ // Own properties are enumerated firstly, so to speed up,
+ // if last one is own, then all properties are own.
+
+ var key;
+ for ( key in obj ) {}
+
+ return key === undefined || hasOwn.call( obj, key );
+ },
+
+ isEmptyObject: function( obj ) {
+ for ( var name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ error: function( msg ) {
+ throw msg;
+ },
+
+ parseJSON: function( data ) {
+ if ( typeof data !== "string" || !data ) {
+ return null;
+ }
+
+ // Make sure leading/trailing whitespace is removed (IE can't handle it)
+ data = jQuery.trim( data );
+
+ // Make sure the incoming data is actual JSON
+ // Logic borrowed from http://json.org/json2.js
+ if ( rvalidchars.test(data.replace(rvalidescape, "@")
+ .replace(rvalidtokens, "]")
+ .replace(rvalidbraces, "")) ) {
+
+ // Try to use the native JSON parser first
+ return window.JSON && window.JSON.parse ?
+ window.JSON.parse( data ) :
+ (new Function("return " + data))();
+
+ } else {
+ jQuery.error( "Invalid JSON: " + data );
+ }
+ },
+
+ // Cross-browser xml parsing
+ // (xml & tmp used internally)
+ parseXML: function( data , xml , tmp ) {
+
+ if ( window.DOMParser ) { // Standard
+ tmp = new DOMParser();
+ xml = tmp.parseFromString( data , "text/xml" );
+ } else { // IE
+ xml = new ActiveXObject( "Microsoft.XMLDOM" );
+ xml.async = "false";
+ xml.loadXML( data );
+ }
+
+ tmp = xml.documentElement;
+
+ if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
+ jQuery.error( "Invalid XML: " + data );
+ }
+
+ return xml;
+ },
+
+ noop: function() {},
+
+ // Evalulates a script in a global context
+ globalEval: function( data ) {
+ if ( data && rnotwhite.test(data) ) {
+ // Inspired by code by Andrea Giammarchi
+ // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
+ var head = document.getElementsByTagName("head")[0] || document.documentElement,
+ script = document.createElement("script");
+
+ script.type = "text/javascript";
+
+ if ( jQuery.support.scriptEval() ) {
+ script.appendChild( document.createTextNode( data ) );
+ } else {
+ script.text = data;
+ }
+
+ // Use insertBefore instead of appendChild to circumvent an IE6 bug.
+ // This arises when a base node is used (#2709).
+ head.insertBefore( script, head.firstChild );
+ head.removeChild( script );
+ }
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
+ },
+
+ // args is for internal usage only
+ each: function( object, callback, args ) {
+ var name, i = 0,
+ length = object.length,
+ isObj = length === undefined || jQuery.isFunction(object);
+
+ if ( args ) {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.apply( object[ name ], args ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( ; i < length; ) {
+ if ( callback.apply( object[ i++ ], args ) === false ) {
+ break;
+ }
+ }
+ }
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( var value = object[0];
+ i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
+ }
+ }
+
+ return object;
+ },
+
+ // Use native String.trim function wherever possible
+ trim: trim ?
+ function( text ) {
+ return text == null ?
+ "" :
+ trim.call( text );
+ } :
+
+ // Otherwise use our own trimming functionality
+ function( text ) {
+ return text == null ?
+ "" :
+ text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
+ },
+
+ // results is for internal usage only
+ makeArray: function( array, results ) {
+ var ret = results || [];
+
+ if ( array != null ) {
+ // The window, strings (and functions) also have 'length'
+ // The extra typeof function check is to prevent crashes
+ // in Safari 2 (See: #3039)
+ // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
+ var type = jQuery.type(array);
+
+ if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
+ push.call( ret, array );
+ } else {
+ jQuery.merge( ret, array );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, array ) {
+ if ( array.indexOf ) {
+ return array.indexOf( elem );
+ }
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ if ( array[ i ] === elem ) {
+ return i;
+ }
+ }
+
+ return -1;
+ },
+
+ merge: function( first, second ) {
+ var i = first.length,
+ j = 0;
+
+ if ( typeof second.length === "number" ) {
+ for ( var l = second.length; j < l; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+
+ } else {
+ while ( second[j] !== undefined ) {
+ first[ i++ ] = second[ j++ ];
+ }
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, inv ) {
+ var ret = [], retVal;
+ inv = !!inv;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ retVal = !!callback( elems[ i ], i );
+ if ( inv !== retVal ) {
+ ret.push( elems[ i ] );
+ }
+ }
+
+ return ret;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var ret = [], value;
+
+ // Go through the array, translating each of the items to their
+ // new value (or values).
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret[ ret.length ] = value;
+ }
+ }
+
+ // Flatten any nested arrays
+ return ret.concat.apply( [], ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ proxy: function( fn, proxy, thisObject ) {
+ if ( arguments.length === 2 ) {
+ if ( typeof proxy === "string" ) {
+ thisObject = fn;
+ fn = thisObject[ proxy ];
+ proxy = undefined;
+
+ } else if ( proxy && !jQuery.isFunction( proxy ) ) {
+ thisObject = proxy;
+ proxy = undefined;
+ }
+ }
+
+ if ( !proxy && fn ) {
+ proxy = function() {
+ return fn.apply( thisObject || this, arguments );
+ };
+ }
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ if ( fn ) {
+ proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
+ }
+
+ // So proxy can be declared as an argument
+ return proxy;
+ },
+
+ // Mutifunctional method to get and set values to a collection
+ // The value/s can be optionally by executed if its a function
+ access: function( elems, key, value, exec, fn, pass ) {
+ var length = elems.length;
+
+ // Setting many attributes
+ if ( typeof key === "object" ) {
+ for ( var k in key ) {
+ jQuery.access( elems, k, key[k], exec, fn, value );
+ }
+ return elems;
+ }
+
+ // Setting one attribute
+ if ( value !== undefined ) {
+ // Optionally, function values get executed if exec is true
+ exec = !pass && exec && jQuery.isFunction(value);
+
+ for ( var i = 0; i < length; i++ ) {
+ fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
+ }
+
+ return elems;
+ }
+
+ // Getting an attribute
+ return length ? fn( elems[0], key ) : undefined;
+ },
+
+ now: function() {
+ return (new Date()).getTime();
+ },
+
+ // Create a simple deferred (one callbacks list)
+ _Deferred: function() {
+ var // callbacks list
+ callbacks = [],
+ // stored [ context , args ]
+ fired,
+ // to avoid firing when already doing so
+ firing,
+ // flag to know if the deferred has been cancelled
+ cancelled,
+ // the deferred itself
+ deferred = {
+
+ // done( f1, f2, ...)
+ done: function() {
+ if ( !cancelled ) {
+ var args = arguments,
+ i,
+ length,
+ elem,
+ type,
+ _fired;
+ if ( fired ) {
+ _fired = fired;
+ fired = 0;
+ }
+ for ( i = 0, length = args.length; i < length; i++ ) {
+ elem = args[ i ];
+ type = jQuery.type( elem );
+ if ( type === "array" ) {
+ deferred.done.apply( deferred, elem );
+ } else if ( type === "function" ) {
+ callbacks.push( elem );
+ }
+ }
+ if ( _fired ) {
+ deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
+ }
+ }
+ return this;
+ },
+
+ // resolve with given context and args
+ resolveWith: function( context, args ) {
+ if ( !cancelled && !fired && !firing ) {
+ firing = 1;
+ try {
+ while( callbacks[ 0 ] ) {
+ callbacks.shift().apply( context, args );
+ }
+ }
+ finally {
+ fired = [ context, args ];
+ firing = 0;
+ }
+ }
+ return this;
+ },
+
+ // resolve with this as context and given arguments
+ resolve: function() {
+ deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments );
+ return this;
+ },
+
+ // Has this deferred been resolved?
+ isResolved: function() {
+ return !!( firing || fired );
+ },
+
+ // Cancel
+ cancel: function() {
+ cancelled = 1;
+ callbacks = [];
+ return this;
+ }
+ };
+
+ return deferred;
+ },
+
+ // Full fledged deferred (two callbacks list)
+ Deferred: function( func ) {
+ var deferred = jQuery._Deferred(),
+ failDeferred = jQuery._Deferred(),
+ promise;
+ // Add errorDeferred methods, then and promise
+ jQuery.extend( deferred, {
+ then: function( doneCallbacks, failCallbacks ) {
+ deferred.done( doneCallbacks ).fail( failCallbacks );
+ return this;
+ },
+ fail: failDeferred.done,
+ rejectWith: failDeferred.resolveWith,
+ reject: failDeferred.resolve,
+ isRejected: failDeferred.isResolved,
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj , i /* internal */ ) {
+ if ( obj == null ) {
+ if ( promise ) {
+ return promise;
+ }
+ promise = obj = {};
+ }
+ i = promiseMethods.length;
+ while( i-- ) {
+ obj[ promiseMethods[ i ] ] = deferred[ promiseMethods[ i ] ];
+ }
+ return obj;
+ }
+ } );
+ // Make sure only one callback list will be used
+ deferred.then( failDeferred.cancel, deferred.cancel );
+ // Unexpose cancel
+ delete deferred.cancel;
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( object ) {
+ var args = arguments,
+ length = args.length,
+ deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ?
+ object :
+ jQuery.Deferred(),
+ promise = deferred.promise(),
+ resolveArray;
+
+ if ( length > 1 ) {
+ resolveArray = new Array( length );
+ jQuery.each( args, function( index, element ) {
+ jQuery.when( element ).then( function( value ) {
+ resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
+ if( ! --length ) {
+ deferred.resolveWith( promise, resolveArray );
+ }
+ }, deferred.reject );
+ } );
+ } else if ( deferred !== object ) {
+ deferred.resolve( object );
+ }
+ return promise;
+ },
+
+ // Use of jQuery.browser is frowned upon.
+ // More details: http://docs.jquery.com/Utilities/jQuery.browser
+ uaMatch: function( ua ) {
+ ua = ua.toLowerCase();
+
+ var match = rwebkit.exec( ua ) ||
+ ropera.exec( ua ) ||
+ rmsie.exec( ua ) ||
+ ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
+ [];
+
+ return { browser: match[1] || "", version: match[2] || "0" };
+ },
+
+ sub: function() {
+ function jQuerySubclass( selector, context ) {
+ return new jQuerySubclass.fn.init( selector, context );
+ }
+ jQuery.extend( true, jQuerySubclass, this );
+ jQuerySubclass.superclass = this;
+ jQuerySubclass.fn = jQuerySubclass.prototype = this();
+ jQuerySubclass.fn.constructor = jQuerySubclass;
+ jQuerySubclass.subclass = this.subclass;
+ jQuerySubclass.fn.init = function init( selector, context ) {
+ if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) {
+ context = jQuerySubclass(context);
+ }
+
+ return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass );
+ };
+ jQuerySubclass.fn.init.prototype = jQuerySubclass.fn;
+ var rootjQuerySubclass = jQuerySubclass(document);
+ return jQuerySubclass;
+ },
+
+ browser: {}
+});
+
+// Create readyList deferred
+readyList = jQuery._Deferred();
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+browserMatch = jQuery.uaMatch( userAgent );
+if ( browserMatch.browser ) {
+ jQuery.browser[ browserMatch.browser ] = true;
+ jQuery.browser.version = browserMatch.version;
+}
+
+// Deprecated, use jQuery.browser.webkit instead
+if ( jQuery.browser.webkit ) {
+ jQuery.browser.safari = true;
+}
+
+if ( indexOf ) {
+ jQuery.inArray = function( elem, array ) {
+ return indexOf.call( array, elem );
+ };
+}
+
+// IE doesn't match non-breaking spaces with \s
+if ( rnotwhite.test( "\xA0" ) ) {
+ trimLeft = /^[\s\xA0]+/;
+ trimRight = /[\s\xA0]+$/;
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+
+// Cleanup functions for the document ready method
+if ( document.addEventListener ) {
+ DOMContentLoaded = function() {
+ document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+ jQuery.ready();
+ };
+
+} else if ( document.attachEvent ) {
+ DOMContentLoaded = function() {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( document.readyState === "complete" ) {
+ document.detachEvent( "onreadystatechange", DOMContentLoaded );
+ jQuery.ready();
+ }
+ };
+}
+
+// The DOM ready check for Internet Explorer
+function doScrollCheck() {
+ if ( jQuery.isReady ) {
+ return;
+ }
+
+ try {
+ // If IE is used, use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ document.documentElement.doScroll("left");
+ } catch(e) {
+ setTimeout( doScrollCheck, 1 );
+ return;
+ }
+
+ // and execute any waiting functions
+ jQuery.ready();
+}
+
+// Expose jQuery to the global object
+return (window.jQuery = window.$ = jQuery);
+
+})();
+
+
+(function() {
+
+ jQuery.support = {};
+
+ var div = document.createElement("div");
+
+ div.style.display = "none";
+ div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
+
+ var all = div.getElementsByTagName("*"),
+ a = div.getElementsByTagName("a")[0],
+ select = document.createElement("select"),
+ opt = select.appendChild( document.createElement("option") );
+
+ // Can't get basic test support
+ if ( !all || !all.length || !a ) {
+ return;
+ }
+
+ jQuery.support = {
+ // IE strips leading whitespace when .innerHTML is used
+ leadingWhitespace: div.firstChild.nodeType === 3,
+
+ // Make sure that tbody elements aren't automatically inserted
+ // IE will insert them into empty tables
+ tbody: !div.getElementsByTagName("tbody").length,
+
+ // Make sure that link elements get serialized correctly by innerHTML
+ // This requires a wrapper element in IE
+ htmlSerialize: !!div.getElementsByTagName("link").length,
+
+ // Get the style information from getAttribute
+ // (IE uses .cssText insted)
+ style: /red/.test( a.getAttribute("style") ),
+
+ // Make sure that URLs aren't manipulated
+ // (IE normalizes it by default)
+ hrefNormalized: a.getAttribute("href") === "/a",
+
+ // Make sure that element opacity exists
+ // (IE uses filter instead)
+ // Use a regex to work around a WebKit issue. See #5145
+ opacity: /^0.55$/.test( a.style.opacity ),
+
+ // Verify style float existence
+ // (IE uses styleFloat instead of cssFloat)
+ cssFloat: !!a.style.cssFloat,
+
+ // Make sure that if no value is specified for a checkbox
+ // that it defaults to "on".
+ // (WebKit defaults to "" instead)
+ checkOn: div.getElementsByTagName("input")[0].value === "on",
+
+ // Make sure that a selected-by-default option has a working selected property.
+ // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+ optSelected: opt.selected,
+
+ // Will be defined later
+ deleteExpando: true,
+ optDisabled: false,
+ checkClone: false,
+ _scriptEval: null,
+ noCloneEvent: true,
+ boxModel: null,
+ inlineBlockNeedsLayout: false,
+ shrinkWrapBlocks: false,
+ reliableHiddenOffsets: true
+ };
+
+ // Make sure that the options inside disabled selects aren't marked as disabled
+ // (WebKit marks them as diabled)
+ select.disabled = true;
+ jQuery.support.optDisabled = !opt.disabled;
+
+ jQuery.support.scriptEval = function() {
+ if ( jQuery.support._scriptEval === null ) {
+ var root = document.documentElement,
+ script = document.createElement("script"),
+ id = "script" + jQuery.now();
+
+ script.type = "text/javascript";
+ try {
+ script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
+ } catch(e) {}
+
+ root.insertBefore( script, root.firstChild );
+
+ // Make sure that the execution of code works by injecting a script
+ // tag with appendChild/createTextNode
+ // (IE doesn't support this, fails, and uses .text instead)
+ if ( window[ id ] ) {
+ jQuery.support._scriptEval = true;
+ delete window[ id ];
+ } else {
+ jQuery.support._scriptEval = false;
+ }
+
+ root.removeChild( script );
+ // release memory in IE
+ root = script = id = null;
+ }
+
+ return jQuery.support._scriptEval;
+ };
+
+ // Test to see if it's possible to delete an expando from an element
+ // Fails in Internet Explorer
+ try {
+ delete div.test;
+
+ } catch(e) {
+ jQuery.support.deleteExpando = false;
+ }
+
+ if ( div.attachEvent && div.fireEvent ) {
+ div.attachEvent("onclick", function click() {
+ // Cloning a node shouldn't copy over any
+ // bound event handlers (IE does this)
+ jQuery.support.noCloneEvent = false;
+ div.detachEvent("onclick", click);
+ });
+ div.cloneNode(true).fireEvent("onclick");
+ }
+
+ div = document.createElement("div");
+ div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
+
+ var fragment = document.createDocumentFragment();
+ fragment.appendChild( div.firstChild );
+
+ // WebKit doesn't clone checked state correctly in fragments
+ jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
+
+ // Figure out if the W3C box model works as expected
+ // document.body must exist before we can do this
+ jQuery(function() {
+ var div = document.createElement("div"),
+ body = document.getElementsByTagName("body")[0];
+
+ // Frameset documents with no body should not run this code
+ if ( !body ) {
+ return;
+ }
+
+ div.style.width = div.style.paddingLeft = "1px";
+ body.appendChild( div );
+ jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
+
+ if ( "zoom" in div.style ) {
+ // Check if natively block-level elements act like inline-block
+ // elements when setting their display to 'inline' and giving
+ // them layout
+ // (IE < 8 does this)
+ div.style.display = "inline";
+ div.style.zoom = 1;
+ jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2;
+
+ // Check if elements with layout shrink-wrap their children
+ // (IE 6 does this)
+ div.style.display = "";
+ div.innerHTML = "<div style='width:4px;'></div>";
+ jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
+ }
+
+ div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
+ var tds = div.getElementsByTagName("td");
+
+ // Check if table cells still have offsetWidth/Height when they are set
+ // to display:none and there are still other visible table cells in a
+ // table row; if so, offsetWidth/Height are not reliable for use when
+ // determining if an element has been hidden directly using
+ // display:none (it is still safe to use offsets if a parent element is
+ // hidden; don safety goggles and see bug #4512 for more information).
+ // (only IE 8 fails this test)
+ jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0;
+
+ tds[0].style.display = "";
+ tds[1].style.display = "none";
+
+ // Check if empty table cells still have offsetWidth/Height
+ // (IE < 8 fail this test)
+ jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
+ div.innerHTML = "";
+
+ body.removeChild( div ).style.display = "none";
+ div = tds = null;
+ });
+
+ // Technique from Juriy Zaytsev
+ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
+ var eventSupported = function( eventName ) {
+ var el = document.createElement("div");
+ eventName = "on" + eventName;
+
+ // We only care about the case where non-standard event systems
+ // are used, namely in IE. Short-circuiting here helps us to
+ // avoid an eval call (in setAttribute) which can cause CSP
+ // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
+ if ( !el.attachEvent ) {
+ return true;
+ }
+
+ var isSupported = (eventName in el);
+ if ( !isSupported ) {
+ el.setAttribute(eventName, "return;");
+ isSupported = typeof el[eventName] === "function";
+ }
+ el = null;
+
+ return isSupported;
+ };
+
+ jQuery.support.submitBubbles = eventSupported("submit");
+ jQuery.support.changeBubbles = eventSupported("change");
+
+ // release memory in IE
+ div = all = a = null;
+})();
+
+
+
+var rbrace = /^(?:\{.*\}|\[.*\])$/;
+
+jQuery.extend({
+ cache: {},
+
+ // Please use with caution
+ uuid: 0,
+
+ // Unique for each copy of jQuery on the page
+ // Non-digits removed to match rinlinejQuery
+ expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
+
+ // The following elements throw uncatchable exceptions if you
+ // attempt to add expando properties to them.
+ noData: {
+ "embed": true,
+ // Ban all objects except for Flash (which handle expandos)
+ "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
+ "applet": true
+ },
+
+ hasData: function( elem ) {
+ elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+
+ return !!elem && !jQuery.isEmptyObject(elem);
+ },
+
+ data: function( elem, name, data, pvt /* Internal Use Only */ ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
+
+ // We have to handle DOM nodes and JS objects differently because IE6-7
+ // can't GC object references properly across the DOM-JS boundary
+ isNode = elem.nodeType,
+
+ // Only DOM nodes need the global jQuery cache; JS object data is
+ // attached directly to the object so GC can occur automatically
+ cache = isNode ? jQuery.cache : elem,
+
+ // Only defining an ID for JS objects if its cache already exists allows
+ // the code to shortcut on the same path as a DOM node with no cache
+ id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
+
+ // Avoid doing any more work than we need to when trying to get data on an
+ // object that has no data at all
+ if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
+ return;
+ }
+
+ if ( !id ) {
+ // Only DOM nodes need a new unique ID for each element since their data
+ // ends up in the global cache
+ if ( isNode ) {
+ elem[ jQuery.expando ] = id = ++jQuery.uuid;
+ } else {
+ id = jQuery.expando;
+ }
+ }
+
+ if ( !cache[ id ] ) {
+ cache[ id ] = {};
+ }
+
+ // An object can be passed to jQuery.data instead of a key/value pair; this gets
+ // shallow copied over onto the existing cache
+ if ( typeof name === "object" ) {
+ if ( pvt ) {
+ cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
+ } else {
+ cache[ id ] = jQuery.extend(cache[ id ], name);
+ }
+ }
+
+ thisCache = cache[ id ];
+
+ // Internal jQuery data is stored in a separate object inside the object's data
+ // cache in order to avoid key collisions between internal data and user-defined
+ // data
+ if ( pvt ) {
+ if ( !thisCache[ internalKey ] ) {
+ thisCache[ internalKey ] = {};
+ }
+
+ thisCache = thisCache[ internalKey ];
+ }
+
+ if ( data !== undefined ) {
+ thisCache[ name ] = data;
+ }
+
+ // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
+ // not attempt to inspect the internal events object using jQuery.data, as this
+ // internal data object is undocumented and subject to change.
+ if ( name === "events" && !thisCache[name] ) {
+ return thisCache[ internalKey ] && thisCache[ internalKey ].events;
+ }
+
+ return getByName ? thisCache[ name ] : thisCache;
+ },
+
+ removeData: function( elem, name, pvt /* Internal Use Only */ ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var internalKey = jQuery.expando, isNode = elem.nodeType,
+
+ // See jQuery.data for more information
+ cache = isNode ? jQuery.cache : elem,
+
+ // See jQuery.data for more information
+ id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+ // If there is already no cache entry for this object, there is no
+ // purpose in continuing
+ if ( !cache[ id ] ) {
+ return;
+ }
+
+ if ( name ) {
+ var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
+
+ if ( thisCache ) {
+ delete thisCache[ name ];
+
+ // If there is no data left in the cache, we want to continue
+ // and let the cache object itself get destroyed
+ if ( !jQuery.isEmptyObject(thisCache) ) {
+ return;
+ }
+ }
+ }
+
+ // See jQuery.data for more information
+ if ( pvt ) {
+ delete cache[ id ][ internalKey ];
+
+ // Don't destroy the parent cache unless the internal data object
+ // had been the only thing left in it
+ if ( !jQuery.isEmptyObject(cache[ id ]) ) {
+ return;
+ }
+ }
+
+ var internalCache = cache[ id ][ internalKey ];
+
+ // Browsers that fail expando deletion also refuse to delete expandos on
+ // the window, but it will allow it on all other JS objects; other browsers
+ // don't care
+ if ( jQuery.support.deleteExpando || cache != window ) {
+ delete cache[ id ];
+ } else {
+ cache[ id ] = null;
+ }
+
+ // We destroyed the entire user cache at once because it's faster than
+ // iterating through each key, but we need to continue to persist internal
+ // data if it existed
+ if ( internalCache ) {
+ cache[ id ] = {};
+ cache[ id ][ internalKey ] = internalCache;
+
+ // Otherwise, we need to eliminate the expando on the node to avoid
+ // false lookups in the cache for entries that no longer exist
+ } else if ( isNode ) {
+ // IE does not allow us to delete expando properties from nodes,
+ // nor does it have a removeAttribute function on Document nodes;
+ // we must handle all of these cases
+ if ( jQuery.support.deleteExpando ) {
+ delete elem[ jQuery.expando ];
+ } else if ( elem.removeAttribute ) {
+ elem.removeAttribute( jQuery.expando );
+ } else {
+ elem[ jQuery.expando ] = null;
+ }
+ }
+ },
+
+ // For internal use only.
+ _data: function( elem, name, data ) {
+ return jQuery.data( elem, name, data, true );
+ },
+
+ // A method for determining if a DOM node can handle the data expando
+ acceptData: function( elem ) {
+ if ( elem.nodeName ) {
+ var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
+
+ if ( match ) {
+ return !(match === true || elem.getAttribute("classid") !== match);
+ }
+ }
+
+ return true;
+ }
+});
+
+jQuery.fn.extend({
+ data: function( key, value ) {
+ var data = null;
+
+ if ( typeof key === "undefined" ) {
+ if ( this.length ) {
+ data = jQuery.data( this[0] );
+
+ if ( this[0].nodeType === 1 ) {
+ var attr = this[0].attributes, name;
+ for ( var i = 0, l = attr.length; i < l; i++ ) {
+ name = attr[i].name;
+
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = name.substr( 5 );
+ dataAttr( this[0], name, data[ name ] );
+ }
+ }
+ }
+ }
+
+ return data;
+
+ } else if ( typeof key === "object" ) {
+ return this.each(function() {
+ jQuery.data( this, key );
+ });
+ }
+
+ var parts = key.split(".");
+ parts[1] = parts[1] ? "." + parts[1] : "";
+
+ if ( value === undefined ) {
+ data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+ // Try to fetch any internally stored data first
+ if ( data === undefined && this.length ) {
+ data = jQuery.data( this[0], key );
+ data = dataAttr( this[0], key, data );
+ }
+
+ return data === undefined && parts[1] ?
+ this.data( parts[0] ) :
+ data;
+
+ } else {
+ return this.each(function() {
+ var $this = jQuery( this ),
+ args = [ parts[0], value ];
+
+ $this.triggerHandler( "setData" + parts[1] + "!", args );
+ jQuery.data( this, key, value );
+ $this.triggerHandler( "changeData" + parts[1] + "!", args );
+ });
+ }
+ },
+
+ removeData: function( key ) {
+ return this.each(function() {
+ jQuery.removeData( this, key );
+ });
+ }
+});
+
+function dataAttr( elem, key, data ) {
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+ data = elem.getAttribute( "data-" + key );
+
+ if ( typeof data === "string" ) {
+ try {
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null :
+ !jQuery.isNaN( data ) ? parseFloat( data ) :
+ rbrace.test( data ) ? jQuery.parseJSON( data ) :
+ data;
+ } catch( e ) {}
+
+ // Make sure we set the data so it isn't changed later
+ jQuery.data( elem, key, data );
+
+ } else {
+ data = undefined;
+ }
+ }
+
+ return data;
+}
+
+
+
+
+jQuery.extend({
+ queue: function( elem, type, data ) {
+ if ( !elem ) {
+ return;
+ }
+
+ type = (type || "fx") + "queue";
+ var q = jQuery._data( elem, type );
+
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( !data ) {
+ return q || [];
+ }
+
+ if ( !q || jQuery.isArray(data) ) {
+ q = jQuery._data( elem, type, jQuery.makeArray(data) );
+
+ } else {
+ q.push( data );
+ }
+
+ return q;
+ },
+
+ dequeue: function( elem, type ) {
+ type = type || "fx";
+
+ var queue = jQuery.queue( elem, type ),
+ fn = queue.shift();
+
+ // If the fx queue is dequeued, always remove the progress sentinel
+ if ( fn === "inprogress" ) {
+ fn = queue.shift();
+ }
+
+ if ( fn ) {
+ // Add a progress sentinel to prevent the fx queue from being
+ // automatically dequeued
+ if ( type === "fx" ) {
+ queue.unshift("inprogress");
+ }
+
+ fn.call(elem, function() {
+ jQuery.dequeue(elem, type);
+ });
+ }
+
+ if ( !queue.length ) {
+ jQuery.removeData( elem, type + "queue", true );
+ }
+ }
+});
+
+jQuery.fn.extend({
+ queue: function( type, data ) {
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ }
+
+ if ( data === undefined ) {
+ return jQuery.queue( this[0], type );
+ }
+ return this.each(function( i ) {
+ var queue = jQuery.queue( this, type, data );
+
+ if ( type === "fx" && queue[0] !== "inprogress" ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ dequeue: function( type ) {
+ return this.each(function() {
+ jQuery.dequeue( this, type );
+ });
+ },
+
+ // Based off of the plugin by Clint Helfers, with permission.
+ // http://blindsignals.com/index.php/2009/07/jquery-delay/
+ delay: function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function() {
+ var elem = this;
+ setTimeout(function() {
+ jQuery.dequeue( elem, type );
+ }, time );
+ });
+ },
+
+ clearQueue: function( type ) {
+ return this.queue( type || "fx", [] );
+ }
+});
+
+
+
+
+var rclass = /[\n\t\r]/g,
+ rspaces = /\s+/,
+ rreturn = /\r/g,
+ rspecialurl = /^(?:href|src|style)$/,
+ rtype = /^(?:button|input)$/i,
+ rfocusable = /^(?:button|input|object|select|textarea)$/i,
+ rclickable = /^a(?:rea)?$/i,
+ rradiocheck = /^(?:radio|checkbox)$/i;
+
+jQuery.props = {
+ "for": "htmlFor",
+ "class": "className",
+ readonly: "readOnly",
+ maxlength: "maxLength",
+ cellspacing: "cellSpacing",
+ rowspan: "rowSpan",
+ colspan: "colSpan",
+ tabindex: "tabIndex",
+ usemap: "useMap",
+ frameborder: "frameBorder"
+};
+
+jQuery.fn.extend({
+ attr: function( name, value ) {
+ return jQuery.access( this, name, value, true, jQuery.attr );
+ },
+
+ removeAttr: function( name, fn ) {
+ return this.each(function(){
+ jQuery.attr( this, name, "" );
+ if ( this.nodeType === 1 ) {
+ this.removeAttribute( name );
+ }
+ });
+ },
+
+ addClass: function( value ) {
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ self.addClass( value.call(this, i, self.attr("class")) );
+ });
+ }
+
+ if ( value && typeof value === "string" ) {
+ var classNames = (value || "").split( rspaces );
+
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ var elem = this[i];
+
+ if ( elem.nodeType === 1 ) {
+ if ( !elem.className ) {
+ elem.className = value;
+
+ } else {
+ var className = " " + elem.className + " ",
+ setClass = elem.className;
+
+ for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
+ if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
+ setClass += " " + classNames[c];
+ }
+ }
+ elem.className = jQuery.trim( setClass );
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ self.removeClass( value.call(this, i, self.attr("class")) );
+ });
+ }
+
+ if ( (value && typeof value === "string") || value === undefined ) {
+ var classNames = (value || "").split( rspaces );
+
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ var elem = this[i];
+
+ if ( elem.nodeType === 1 && elem.className ) {
+ if ( value ) {
+ var className = (" " + elem.className + " ").replace(rclass, " ");
+ for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
+ className = className.replace(" " + classNames[c] + " ", " ");
+ }
+ elem.className = jQuery.trim( className );
+
+ } else {
+ elem.className = "";
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value,
+ isBool = typeof stateVal === "boolean";
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
+ });
+ }
+
+ return this.each(function() {
+ if ( type === "string" ) {
+ // toggle individual class names
+ var className,
+ i = 0,
+ self = jQuery( this ),
+ state = stateVal,
+ classNames = value.split( rspaces );
+
+ while ( (className = classNames[ i++ ]) ) {
+ // check each className given, space seperated list
+ state = isBool ? state : !self.hasClass( className );
+ self[ state ? "addClass" : "removeClass" ]( className );
+ }
+
+ } else if ( type === "undefined" || type === "boolean" ) {
+ if ( this.className ) {
+ // store className if set
+ jQuery._data( this, "__className__", this.className );
+ }
+
+ // toggle whole className
+ this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
+ }
+ });
+ },
+
+ hasClass: function( selector ) {
+ var className = " " + selector + " ";
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ val: function( value ) {
+ if ( !arguments.length ) {
+ var elem = this[0];
+
+ if ( elem ) {
+ if ( jQuery.nodeName( elem, "option" ) ) {
+ // attributes.value is undefined in Blackberry 4.7 but
+ // uses .value. See #6932
+ var val = elem.attributes.value;
+ return !val || val.specified ? elem.value : elem.text;
+ }
+
+ // We need to handle select boxes special
+ if ( jQuery.nodeName( elem, "select" ) ) {
+ var index = elem.selectedIndex,
+ values = [],
+ options = elem.options,
+ one = elem.type === "select-one";
+
+ // Nothing was selected
+ if ( index < 0 ) {
+ return null;
+ }
+
+ // Loop through all the selected options
+ for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+ var option = options[ i ];
+
+ // Don't return options that are disabled or in a disabled optgroup
+ if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
+ (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
+
+ // Get the specific value for the option
+ value = jQuery(option).val();
+
+ // We don't need an array for one selects
+ if ( one ) {
+ return value;
+ }
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ return values;
+ }
+
+ // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
+ if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
+ return elem.getAttribute("value") === null ? "on" : elem.value;
+ }
+
+ // Everything else, we just grab the value
+ return (elem.value || "").replace(rreturn, "");
+
+ }
+
+ return undefined;
+ }
+
+ var isFunction = jQuery.isFunction(value);
+
+ return this.each(function(i) {
+ var self = jQuery(this), val = value;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call(this, i, self.val());
+ }
+
+ // Treat null/undefined as ""; convert numbers to string
+ if ( val == null ) {
+ val = "";
+ } else if ( typeof val === "number" ) {
+ val += "";
+ } else if ( jQuery.isArray(val) ) {
+ val = jQuery.map(val, function (value) {
+ return value == null ? "" : value + "";
+ });
+ }
+
+ if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
+ this.checked = jQuery.inArray( self.val(), val ) >= 0;
+
+ } else if ( jQuery.nodeName( this, "select" ) ) {
+ var values = jQuery.makeArray(val);
+
+ jQuery( "option", this ).each(function() {
+ this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
+ });
+
+ if ( !values.length ) {
+ this.selectedIndex = -1;
+ }
+
+ } else {
+ this.value = val;
+ }
+ });
+ }
+});
+
+jQuery.extend({
+ attrFn: {
+ val: true,
+ css: true,
+ html: true,
+ text: true,
+ data: true,
+ width: true,
+ height: true,
+ offset: true
+ },
+
+ attr: function( elem, name, value, pass ) {
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) {
+ return undefined;
+ }
+
+ if ( pass && name in jQuery.attrFn ) {
+ return jQuery(elem)[name](value);
+ }
+
+ var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
+ // Whether we are setting (or getting)
+ set = value !== undefined;
+
+ // Try to normalize/fix the name
+ name = notxml && jQuery.props[ name ] || name;
+
+ // Only do all the following if this is a node (faster for style)
+ if ( elem.nodeType === 1 ) {
+ // These attributes require special treatment
+ var special = rspecialurl.test( name );
+
+ // Safari mis-reports the default selected property of an option
+ // Accessing the parent's selectedIndex property fixes it
+ if ( name === "selected" && !jQuery.support.optSelected ) {
+ var parent = elem.parentNode;
+ if ( parent ) {
+ parent.selectedIndex;
+
+ // Make sure that it also works with optgroups, see #5701
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ }
+ }
+
+ // If applicable, access the attribute via the DOM 0 way
+ // 'in' checks fail in Blackberry 4.7 #6931
+ if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
+ if ( set ) {
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
+ jQuery.error( "type property can't be changed" );
+ }
+
+ if ( value === null ) {
+ if ( elem.nodeType === 1 ) {
+ elem.removeAttribute( name );
+ }
+
+ } else {
+ elem[ name ] = value;
+ }
+ }
+
+ // browsers index elements by id/name on forms, give priority to attributes.
+ if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
+ return elem.getAttributeNode( name ).nodeValue;
+ }
+
+ // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+ // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ if ( name === "tabIndex" ) {
+ var attributeNode = elem.getAttributeNode( "tabIndex" );
+
+ return attributeNode && attributeNode.specified ?
+ attributeNode.value :
+ rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+ 0 :
+ undefined;
+ }
+
+ return elem[ name ];
+ }
+
+ if ( !jQuery.support.style && notxml && name === "style" ) {
+ if ( set ) {
+ elem.style.cssText = "" + value;
+ }
+
+ return elem.style.cssText;
+ }
+
+ if ( set ) {
+ // convert the value to a string (all browsers do this but IE) see #1070
+ elem.setAttribute( name, "" + value );
+ }
+
+ // Ensure that missing attributes return undefined
+ // Blackberry 4.7 returns "" from getAttribute #6938
+ if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
+ return undefined;
+ }
+
+ var attr = !jQuery.support.hrefNormalized && notxml && special ?
+ // Some attributes require a special call on IE
+ elem.getAttribute( name, 2 ) :
+ elem.getAttribute( name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return attr === null ? undefined : attr;
+ }
+ // Handle everything which isn't a DOM element node
+ if ( set ) {
+ elem[ name ] = value;
+ }
+ return elem[ name ];
+ }
+});
+
+
+
+
+var rnamespaces = /\.(.*)$/,
+ rformElems = /^(?:textarea|input|select)$/i,
+ rperiod = /\./g,
+ rspace = / /g,
+ rescape = /[^\w\s.|`]/g,
+ fcleanup = function( nm ) {
+ return nm.replace(rescape, "\\$&");
+ },
+ eventKey = "events";
+
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code originated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+ // Bind an event to an element
+ // Original by Dean Edwards
+ add: function( elem, types, handler, data ) {
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // For whatever reason, IE has trouble passing the window object
+ // around, causing it to be cloned in the process
+ if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) {
+ elem = window;
+ }
+
+ if ( handler === false ) {
+ handler = returnFalse;
+ } else if ( !handler ) {
+ // Fixes bug #7229. Fix recommended by jdalton
+ return;
+ }
+
+ var handleObjIn, handleObj;
+
+ if ( handler.handler ) {
+ handleObjIn = handler;
+ handler = handleObjIn.handler;
+ }
+
+ // Make sure that the function being executed has a unique ID
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // Init the element's event structure
+ var elemData = jQuery._data( elem );
+
+ // If no elemData is found then we must be trying to bind to one of the
+ // banned noData elements
+ if ( !elemData ) {
+ return;
+ }
+
+ var events = elemData[ eventKey ],
+ eventHandle = elemData.handle;
+
+ if ( typeof events === "function" ) {
+ // On plain objects events is a fn that holds the data
+ // which prevents this data from being JSON serialized
+ // the function does not need to be called, it just contains the data
+ eventHandle = events.handle;
+ events = events.events;
+
+ } else if ( !events ) {
+ if ( !elem.nodeType ) {
+ // On plain objects, create a fn that acts as the holder
+ // of the values to avoid JSON serialization of event data
+ elemData[ eventKey ] = elemData = function(){};
+ }
+
+ elemData.events = events = {};
+ }
+
+ if ( !eventHandle ) {
+ elemData.handle = eventHandle = function() {
+ // Handle the second event of a trigger and when
+ // an event is called after a page has unloaded
+ return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
+ jQuery.event.handle.apply( eventHandle.elem, arguments ) :
+ undefined;
+ };
+ }
+
+ // Add elem as a property of the handle function
+ // This is to prevent a memory leak with non-native events in IE.
+ eventHandle.elem = elem;
+
+ // Handle multiple events separated by a space
+ // jQuery(...).bind("mouseover mouseout", fn);
+ types = types.split(" ");
+
+ var type, i = 0, namespaces;
+
+ while ( (type = types[ i++ ]) ) {
+ handleObj = handleObjIn ?
+ jQuery.extend({}, handleObjIn) :
+ { handler: handler, data: data };
+
+ // Namespaced event handlers
+ if ( type.indexOf(".") > -1 ) {
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ handleObj.namespace = namespaces.slice(0).sort().join(".");
+
+ } else {
+ namespaces = [];
+ handleObj.namespace = "";
+ }
+
+ handleObj.type = type;
+ if ( !handleObj.guid ) {
+ handleObj.guid = handler.guid;
+ }
+
+ // Get the current list of functions bound to this event
+ var handlers = events[ type ],
+ special = jQuery.event.special[ type ] || {};
+
+ // Init the event handler queue
+ if ( !handlers ) {
+ handlers = events[ type ] = [];
+
+ // Check for a special event handler
+ // Only use addEventListener/attachEvent if the special
+ // events handler returns false
+ if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+ // Bind the global event handler to the element
+ if ( elem.addEventListener ) {
+ elem.addEventListener( type, eventHandle, false );
+
+ } else if ( elem.attachEvent ) {
+ elem.attachEvent( "on" + type, eventHandle );
+ }
+ }
+ }
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
+
+ if ( !handleObj.handler.guid ) {
+ handleObj.handler.guid = handler.guid;
+ }
+ }
+
+ // Add the function to the element's handler list
+ handlers.push( handleObj );
+
+ // Keep track of which events have been used, for global triggering
+ jQuery.event.global[ type ] = true;
+ }
+
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
+ },
+
+ global: {},
+
+ // Detach an event or set of events from an element
+ remove: function( elem, types, handler, pos ) {
+ // don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ if ( handler === false ) {
+ handler = returnFalse;
+ }
+
+ var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
+ elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
+ events = elemData && elemData[ eventKey ];
+
+ if ( !elemData || !events ) {
+ return;
+ }
+
+ if ( typeof events === "function" ) {
+ elemData = events;
+ events = events.events;
+ }
+
+ // types is actually an event object here
+ if ( types && types.type ) {
+ handler = types.handler;
+ types = types.type;
+ }
+
+ // Unbind all events for the element
+ if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
+ types = types || "";
+
+ for ( type in events ) {
+ jQuery.event.remove( elem, type + types );
+ }
+
+ return;
+ }
+
+ // Handle multiple events separated by a space
+ // jQuery(...).unbind("mouseover mouseout", fn);
+ types = types.split(" ");
+
+ while ( (type = types[ i++ ]) ) {
+ origType = type;
+ handleObj = null;
+ all = type.indexOf(".") < 0;
+ namespaces = [];
+
+ if ( !all ) {
+ // Namespaced event handlers
+ namespaces = type.split(".");
+ type = namespaces.shift();
+
+ namespace = new RegExp("(^|\\.)" +
+ jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
+ }
+
+ eventType = events[ type ];
+
+ if ( !eventType ) {
+ continue;
+ }
+
+ if ( !handler ) {
+ for ( j = 0; j < eventType.length; j++ ) {
+ handleObj = eventType[ j ];
+
+ if ( all || namespace.test( handleObj.namespace ) ) {
+ jQuery.event.remove( elem, origType, handleObj.handler, j );
+ eventType.splice( j--, 1 );
+ }
+ }
+
+ continue;
+ }
+
+ special = jQuery.event.special[ type ] || {};
+
+ for ( j = pos || 0; j < eventType.length; j++ ) {
+ handleObj = eventType[ j ];
+
+ if ( handler.guid === handleObj.guid ) {
+ // remove the given handler for the given type
+ if ( all || namespace.test( handleObj.namespace ) ) {
+ if ( pos == null ) {
+ eventType.splice( j--, 1 );
+ }
+
+ if ( special.remove ) {
+ special.remove.call( elem, handleObj );
+ }
+ }
+
+ if ( pos != null ) {
+ break;
+ }
+ }
+ }
+
+ // remove generic event handler if no more handlers exist
+ if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
+ if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
+ jQuery.removeEvent( elem, type, elemData.handle );
+ }
+
+ ret = null;
+ delete events[ type ];
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ if ( jQuery.isEmptyObject( events ) ) {
+ var handle = elemData.handle;
+ if ( handle ) {
+ handle.elem = null;
+ }
+
+ delete elemData.events;
+ delete elemData.handle;
+
+ if ( typeof elemData === "function" ) {
+ jQuery.removeData( elem, eventKey, true );
+
+ } else if ( jQuery.isEmptyObject( elemData ) ) {
+ jQuery.removeData( elem, undefined, true );
+ }
+ }
+ },
+
+ // bubbling is internal
+ trigger: function( event, data, elem /*, bubbling */ ) {
+ // Event object or event type
+ var type = event.type || event,
+ bubbling = arguments[3];
+
+ if ( !bubbling ) {
+ event = typeof event === "object" ?
+ // jQuery.Event object
+ event[ jQuery.expando ] ? event :
+ // Object literal
+ jQuery.extend( jQuery.Event(type), event ) :
+ // Just the event type (string)
+ jQuery.Event(type);
+
+ if ( type.indexOf("!") >= 0 ) {
+ event.type = type = type.slice(0, -1);
+ event.exclusive = true;
+ }
+
+ // Handle a global trigger
+ if ( !elem ) {
+ // Don't bubble custom events when global (to avoid too much overhead)
+ event.stopPropagation();
+
+ // Only trigger if we've ever bound an event for it
+ if ( jQuery.event.global[ type ] ) {
+ // XXX This code smells terrible. event.js should not be directly
+ // inspecting the data cache
+ jQuery.each( jQuery.cache, function() {
+ // internalKey variable is just used to make it easier to find
+ // and potentially change this stuff later; currently it just
+ // points to jQuery.expando
+ var internalKey = jQuery.expando,
+ internalCache = this[ internalKey ];
+ if ( internalCache && internalCache.events && internalCache.events[type] ) {
+ jQuery.event.trigger( event, data, internalCache.handle.elem );
+ }
+ });
+ }
+ }
+
+ // Handle triggering a single element
+
+ // don't do events on text and comment nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return undefined;
+ }
+
+ // Clean up in case it is reused
+ event.result = undefined;
+ event.target = elem;
+
+ // Clone the incoming data, if any
+ data = jQuery.makeArray( data );
+ data.unshift( event );
+ }
+
+ event.currentTarget = elem;
+
+ // Trigger the event, it is assumed that "handle" is a function
+ var handle = elem.nodeType ?
+ jQuery._data( elem, "handle" ) :
+ (jQuery._data( elem, eventKey ) || {}).handle;
+
+ if ( handle ) {
+ handle.apply( elem, data );
+ }
+
+ var parent = elem.parentNode || elem.ownerDocument;
+
+ // Trigger an inline bound script
+ try {
+ if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
+ if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
+ event.result = false;
+ event.preventDefault();
+ }
+ }
+
+ // prevent IE from throwing an error for some elements with some event types, see #3533
+ } catch (inlineError) {}
+
+ if ( !event.isPropagationStopped() && parent ) {
+ jQuery.event.trigger( event, data, parent, true );
+
+ } else if ( !event.isDefaultPrevented() ) {
+ var old,
+ target = event.target,
+ targetType = type.replace( rnamespaces, "" ),
+ isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
+ special = jQuery.event.special[ targetType ] || {};
+
+ if ( (!special._default || special._default.call( elem, event ) === false) &&
+ !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
+
+ try {
+ if ( target[ targetType ] ) {
+ // Make sure that we don't accidentally re-trigger the onFOO events
+ old = target[ "on" + targetType ];
+
+ if ( old ) {
+ target[ "on" + targetType ] = null;
+ }
+
+ jQuery.event.triggered = true;
+ target[ targetType ]();
+ }
+
+ // prevent IE from throwing an error for some elements with some event types, see #3533
+ } catch (triggerError) {}
+
+ if ( old ) {
+ target[ "on" + targetType ] = old;
+ }
+
+ jQuery.event.triggered = false;
+ }
+ }
+ },
+
+ handle: function( event ) {
+ var all, handlers, namespaces, namespace_re, events,
+ namespace_sort = [],
+ args = jQuery.makeArray( arguments );
+
+ event = args[0] = jQuery.event.fix( event || window.event );
+ event.currentTarget = this;
+
+ // Namespaced event handlers
+ all = event.type.indexOf(".") < 0 && !event.exclusive;
+
+ if ( !all ) {
+ namespaces = event.type.split(".");
+ event.type = namespaces.shift();
+ namespace_sort = namespaces.slice(0).sort();
+ namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)");
+ }
+
+ event.namespace = event.namespace || namespace_sort.join(".");
+
+ events = jQuery._data(this, eventKey);
+
+ if ( typeof events === "function" ) {
+ events = events.events;
+ }
+
+ handlers = (events || {})[ event.type ];
+
+ if ( events && handlers ) {
+ // Clone the handlers to prevent manipulation
+ handlers = handlers.slice(0);
+
+ for ( var j = 0, l = handlers.length; j < l; j++ ) {
+ var handleObj = handlers[ j ];
+
+ // Filter the functions by class
+ if ( all || namespace_re.test( handleObj.namespace ) ) {
+ // Pass in a reference to the handler function itself
+ // So that we can later remove it
+ event.handler = handleObj.handler;
+ event.data = handleObj.data;
+ event.handleObj = handleObj;
+
+ var ret = handleObj.handler.apply( this, args );
+
+ if ( ret !== undefined ) {
+ event.result = ret;
+ if ( ret === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
+ }
+ }
+ }
+
+ return event.result;
+ },
+
+ props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+
+ fix: function( event ) {
+ if ( event[ jQuery.expando ] ) {
+ return event;
+ }
+
+ // store a copy of the original event object
+ // and "clone" to set read-only properties
+ var originalEvent = event;
+ event = jQuery.Event( originalEvent );
+
+ for ( var i = this.props.length, prop; i; ) {
+ prop = this.props[ --i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Fix target property, if necessary
+ if ( !event.target ) {
+ // Fixes #1925 where srcElement might not be defined either
+ event.target = event.srcElement || document;
+ }
+
+ // check if target is a textnode (safari)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && event.fromElement ) {
+ event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
+ }
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && event.clientX != null ) {
+ var doc = document.documentElement,
+ body = document.body;
+
+ event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
+ event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
+ }
+
+ // Add which for key events
+ if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
+ event.which = event.charCode != null ? event.charCode : event.keyCode;
+ }
+
+ // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+ if ( !event.metaKey && event.ctrlKey ) {
+ event.metaKey = event.ctrlKey;
+ }
+
+ // Add which for click: 1 === left; 2 === middle; 3 === right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && event.button !== undefined ) {
+ event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+ }
+
+ return event;
+ },
+
+ // Deprecated, use jQuery.guid instead
+ guid: 1E8,
+
+ // Deprecated, use jQuery.proxy instead
+ proxy: jQuery.proxy,
+
+ special: {
+ ready: {
+ // Make sure the ready event is setup
+ setup: jQuery.bindReady,
+ teardown: jQuery.noop
+ },
+
+ live: {
+ add: function( handleObj ) {
+ jQuery.event.add( this,
+ liveConvert( handleObj.origType, handleObj.selector ),
+ jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
+ },
+
+ remove: function( handleObj ) {
+ jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
+ }
+ },
+
+ beforeunload: {
+ setup: function( data, namespaces, eventHandle ) {
+ // We only want to do this special case on windows
+ if ( jQuery.isWindow( this ) ) {
+ this.onbeforeunload = eventHandle;
+ }
+ },
+
+ teardown: function( namespaces, eventHandle ) {
+ if ( this.onbeforeunload === eventHandle ) {
+ this.onbeforeunload = null;
+ }
+ }
+ }
+ }
+};
+
+jQuery.removeEvent = document.removeEventListener ?
+ function( elem, type, handle ) {
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, handle, false );
+ }
+ } :
+ function( elem, type, handle ) {
+ if ( elem.detachEvent ) {
+ elem.detachEvent( "on" + type, handle );
+ }
+ };
+
+jQuery.Event = function( src ) {
+ // Allow instantiation without the 'new' keyword
+ if ( !this.preventDefault ) {
+ return new jQuery.Event( src );
+ }
+
+ // Event object
+ if ( src && src.type ) {
+ this.originalEvent = src;
+ this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
+ src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // timeStamp is buggy for some events on Firefox(#3843)
+ // So we won't rely on the native value
+ this.timeStamp = jQuery.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+};
+
+function returnFalse() {
+ return false;
+}
+function returnTrue() {
+ return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ preventDefault: function() {
+ this.isDefaultPrevented = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+
+ // if preventDefault exists run it on the original event
+ if ( e.preventDefault ) {
+ e.preventDefault();
+
+ // otherwise set the returnValue property of the original event to false (IE)
+ } else {
+ e.returnValue = false;
+ }
+ },
+ stopPropagation: function() {
+ this.isPropagationStopped = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+ // if stopPropagation exists run it on the original event
+ if ( e.stopPropagation ) {
+ e.stopPropagation();
+ }
+ // otherwise set the cancelBubble property of the original event to true (IE)
+ e.cancelBubble = true;
+ },
+ stopImmediatePropagation: function() {
+ this.isImmediatePropagationStopped = returnTrue;
+ this.stopPropagation();
+ },
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse
+};
+
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function( event ) {
+ // Check if mouse(over|out) are still within the same parent element
+ var parent = event.relatedTarget;
+
+ // Firefox sometimes assigns relatedTarget a XUL element
+ // which we cannot access the parentNode property of
+ try {
+ // Traverse up the tree
+ while ( parent && parent !== this ) {
+ parent = parent.parentNode;
+ }
+
+ if ( parent !== this ) {
+ // set the correct event type
+ event.type = event.data;
+
+ // handle event if we actually just moused on to a non sub-element
+ jQuery.event.handle.apply( this, arguments );
+ }
+
+ // assuming we've left the element since we most likely mousedover a xul element
+ } catch(e) { }
+},
+
+// In case of event delegation, we only need to rename the event.type,
+// liveHandler will take care of the rest.
+delegate = function( event ) {
+ event.type = event.data;
+ jQuery.event.handle.apply( this, arguments );
+};
+
+// Create mouseenter and mouseleave events
+jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ setup: function( data ) {
+ jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
+ },
+ teardown: function( data ) {
+ jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
+ }
+ };
+});
+
+// submit delegation
+if ( !jQuery.support.submitBubbles ) {
+
+ jQuery.event.special.submit = {
+ setup: function( data, namespaces ) {
+ if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) {
+ jQuery.event.add(this, "click.specialSubmit", function( e ) {
+ var elem = e.target,
+ type = elem.type;
+
+ if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
+ e.liveFired = undefined;
+ return trigger( "submit", this, arguments );
+ }
+ });
+
+ jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
+ var elem = e.target,
+ type = elem.type;
+
+ if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
+ e.liveFired = undefined;
+ return trigger( "submit", this, arguments );
+ }
+ });
+
+ } else {
+ return false;
+ }
+ },
+
+ teardown: function( namespaces ) {
+ jQuery.event.remove( this, ".specialSubmit" );
+ }
+ };
+
+}
+
+// change delegation, happens here so we have bind.
+if ( !jQuery.support.changeBubbles ) {
+
+ var changeFilters,
+
+ getVal = function( elem ) {
+ var type = elem.type, val = elem.value;
+
+ if ( type === "radio" || type === "checkbox" ) {
+ val = elem.checked;
+
+ } else if ( type === "select-multiple" ) {
+ val = elem.selectedIndex > -1 ?
+ jQuery.map( elem.options, function( elem ) {
+ return elem.selected;
+ }).join("-") :
+ "";
+
+ } else if ( elem.nodeName.toLowerCase() === "select" ) {
+ val = elem.selectedIndex;
+ }
+
+ return val;
+ },
+
+ testChange = function testChange( e ) {
+ var elem = e.target, data, val;
+
+ if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
+ return;
+ }
+
+ data = jQuery._data( elem, "_change_data" );
+ val = getVal(elem);
+
+ // the current data will be also retrieved by beforeactivate
+ if ( e.type !== "focusout" || elem.type !== "radio" ) {
+ jQuery._data( elem, "_change_data", val );
+ }
+
+ if ( data === undefined || val === data ) {
+ return;
+ }
+
+ if ( data != null || val ) {
+ e.type = "change";
+ e.liveFired = undefined;
+ return jQuery.event.trigger( e, arguments[1], elem );
+ }
+ };
+
+ jQuery.event.special.change = {
+ filters: {
+ focusout: testChange,
+
+ beforedeactivate: testChange,
+
+ click: function( e ) {
+ var elem = e.target, type = elem.type;
+
+ if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
+ return testChange.call( this, e );
+ }
+ },
+
+ // Change has to be called before submit
+ // Keydown will be called before keypress, which is used in submit-event delegation
+ keydown: function( e ) {
+ var elem = e.target, type = elem.type;
+
+ if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
+ (e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
+ type === "select-multiple" ) {
+ return testChange.call( this, e );
+ }
+ },
+
+ // Beforeactivate happens also before the previous element is blurred
+ // with this event you can't trigger a change event, but you can store
+ // information
+ beforeactivate: function( e ) {
+ var elem = e.target;
+ jQuery._data( elem, "_change_data", getVal(elem) );
+ }
+ },
+
+ setup: function( data, namespaces ) {
+ if ( this.type === "file" ) {
+ return false;
+ }
+
+ for ( var type in changeFilters ) {
+ jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
+ }
+
+ return rformElems.test( this.nodeName );
+ },
+
+ teardown: function( namespaces ) {
+ jQuery.event.remove( this, ".specialChange" );
+
+ return rformElems.test( this.nodeName );
+ }
+ };
+
+ changeFilters = jQuery.event.special.change.filters;
+
+ // Handle when the input is .focus()'d
+ changeFilters.focus = changeFilters.beforeactivate;
+}
+
+function trigger( type, elem, args ) {
+ args[0].type = type;
+ return jQuery.event.handle.apply( elem, args );
+}
+
+// Create "bubbling" focus and blur events
+if ( document.addEventListener ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ this.addEventListener( orig, handler, true );
+ },
+ teardown: function() {
+ this.removeEventListener( orig, handler, true );
+ }
+ };
+
+ function handler( e ) {
+ e = jQuery.event.fix( e );
+ e.type = fix;
+ return jQuery.event.handle.call( this, e );
+ }
+ });
+}
+
+jQuery.each(["bind", "one"], function( i, name ) {
+ jQuery.fn[ name ] = function( type, data, fn ) {
+ // Handle object literals
+ if ( typeof type === "object" ) {
+ for ( var key in type ) {
+ this[ name ](key, data, type[key], fn);
+ }
+ return this;
+ }
+
+ if ( jQuery.isFunction( data ) || data === false ) {
+ fn = data;
+ data = undefined;
+ }
+
+ var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
+ jQuery( this ).unbind( event, handler );
+ return fn.apply( this, arguments );
+ }) : fn;
+
+ if ( type === "unload" && name !== "one" ) {
+ this.one( type, data, fn );
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ jQuery.event.add( this[i], type, handler, data );
+ }
+ }
+
+ return this;
+ };
+});
+
+jQuery.fn.extend({
+ unbind: function( type, fn ) {
+ // Handle object literals
+ if ( typeof type === "object" && !type.preventDefault ) {
+ for ( var key in type ) {
+ this.unbind(key, type[key]);
+ }
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ jQuery.event.remove( this[i], type, fn );
+ }
+ }
+
+ return this;
+ },
+
+ delegate: function( selector, types, data, fn ) {
+ return this.live( types, data, fn, selector );
+ },
+
+ undelegate: function( selector, types, fn ) {
+ if ( arguments.length === 0 ) {
+ return this.unbind( "live" );
+
+ } else {
+ return this.die( types, null, fn, selector );
+ }
+ },
+
+ trigger: function( type, data ) {
+ return this.each(function() {
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+
+ triggerHandler: function( type, data ) {
+ if ( this[0] ) {
+ var event = jQuery.Event( type );
+ event.preventDefault();
+ event.stopPropagation();
+ jQuery.event.trigger( event, data, this[0] );
+ return event.result;
+ }
+ },
+
+ toggle: function( fn ) {
+ // Save reference to arguments for access in closure
+ var args = arguments,
+ i = 1;
+
+ // link all the functions, so any of them can unbind this click handler
+ while ( i < args.length ) {
+ jQuery.proxy( fn, args[ i++ ] );
+ }
+
+ return this.click( jQuery.proxy( fn, function( event ) {
+ // Figure out which function to execute
+ var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
+ jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
+
+ // Make sure that clicks stop
+ event.preventDefault();
+
+ // and execute the function
+ return args[ lastToggle ].apply( this, arguments ) || false;
+ }));
+ },
+
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ }
+});
+
+var liveMap = {
+ focus: "focusin",
+ blur: "focusout",
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+};
+
+jQuery.each(["live", "die"], function( i, name ) {
+ jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
+ var type, i = 0, match, namespaces, preType,
+ selector = origSelector || this.selector,
+ context = origSelector ? this : jQuery( this.context );
+
+ if ( typeof types === "object" && !types.preventDefault ) {
+ for ( var key in types ) {
+ context[ name ]( key, data, types[key], selector );
+ }
+
+ return this;
+ }
+
+ if ( jQuery.isFunction( data ) ) {
+ fn = data;
+ data = undefined;
+ }
+
+ types = (types || "").split(" ");
+
+ while ( (type = types[ i++ ]) != null ) {
+ match = rnamespaces.exec( type );
+ namespaces = "";
+
+ if ( match ) {
+ namespaces = match[0];
+ type = type.replace( rnamespaces, "" );
+ }
+
+ if ( type === "hover" ) {
+ types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
+ continue;
+ }
+
+ preType = type;
+
+ if ( type === "focus" || type === "blur" ) {
+ types.push( liveMap[ type ] + namespaces );
+ type = type + namespaces;
+
+ } else {
+ type = (liveMap[ type ] || type) + namespaces;
+ }
+
+ if ( name === "live" ) {
+ // bind live handler
+ for ( var j = 0, l = context.length; j < l; j++ ) {
+ jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
+ { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
+ }
+
+ } else {
+ // unbind live handler
+ context.unbind( "live." + liveConvert( type, selector ), fn );
+ }
+ }
+
+ return this;
+ };
+});
+
+function liveHandler( event ) {
+ var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
+ elems = [],
+ selectors = [],
+ events = jQuery._data( this, eventKey );
+
+ if ( typeof events === "function" ) {
+ events = events.events;
+ }
+
+ // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
+ if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
+ return;
+ }
+
+ if ( event.namespace ) {
+ namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
+ }
+
+ event.liveFired = this;
+
+ var live = events.live.slice(0);
+
+ for ( j = 0; j < live.length; j++ ) {
+ handleObj = live[j];
+
+ if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
+ selectors.push( handleObj.selector );
+
+ } else {
+ live.splice( j--, 1 );
+ }
+ }
+
+ match = jQuery( event.target ).closest( selectors, event.currentTarget );
+
+ for ( i = 0, l = match.length; i < l; i++ ) {
+ close = match[i];
+
+ for ( j = 0; j < live.length; j++ ) {
+ handleObj = live[j];
+
+ if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) ) {
+ elem = close.elem;
+ related = null;
+
+ // Those two events require additional checking
+ if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
+ event.type = handleObj.preType;
+ related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
+ }
+
+ if ( !related || related !== elem ) {
+ elems.push({ elem: elem, handleObj: handleObj, level: close.level });
+ }
+ }
+ }
+ }
+
+ for ( i = 0, l = elems.length; i < l; i++ ) {
+ match = elems[i];
+
+ if ( maxLevel && match.level > maxLevel ) {
+ break;
+ }
+
+ event.currentTarget = match.elem;
+ event.data = match.handleObj.data;
+ event.handleObj = match.handleObj;
+
+ ret = match.handleObj.origHandler.apply( match.elem, arguments );
+
+ if ( ret === false || event.isPropagationStopped() ) {
+ maxLevel = match.level;
+
+ if ( ret === false ) {
+ stop = false;
+ }
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
+ }
+ }
+
+ return stop;
+}
+
+function liveConvert( type, selector ) {
+ return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&");
+}
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup error").split(" "), function( i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( data, fn ) {
+ if ( fn == null ) {
+ fn = data;
+ data = null;
+ }
+
+ return arguments.length > 0 ?
+ this.bind( name, data, fn ) :
+ this.trigger( name );
+ };
+
+ if ( jQuery.attrFn ) {
+ jQuery.attrFn[ name ] = true;
+ }
+});
+
+
+/*!
+ * Sizzle CSS Selector Engine
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){
+
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+ done = 0,
+ toString = Object.prototype.toString,
+ hasDuplicate = false,
+ baseHasDuplicate = true;
+
+// Here we check if the JavaScript engine is using some sort of
+// optimization where it does not always call our comparision
+// function. If that is the case, discard the hasDuplicate value.
+// Thus far that includes Google Chrome.
+[0, 0].sort(function() {
+ baseHasDuplicate = false;
+ return 0;
+});
+
+var Sizzle = function( selector, context, results, seed ) {
+ results = results || [];
+ context = context || document;
+
+ var origContext = context;
+
+ if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
+ return [];
+ }
+
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ var m, set, checkSet, extra, ret, cur, pop, i,
+ prune = true,
+ contextXML = Sizzle.isXML( context ),
+ parts = [],
+ soFar = selector;
+
+ // Reset the position of the chunker regexp (start from head)
+ do {
+ chunker.exec( "" );
+ m = chunker.exec( soFar );
+
+ if ( m ) {
+ soFar = m[3];
+
+ parts.push( m[1] );
+
+ if ( m[2] ) {
+ extra = m[3];
+ break;
+ }
+ }
+ } while ( m );
+
+ if ( parts.length > 1 && origPOS.exec( selector ) ) {
+
+ if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
+ set = posProcess( parts[0] + parts[1], context );
+
+ } else {
+ set = Expr.relative[ parts[0] ] ?
+ [ context ] :
+ Sizzle( parts.shift(), context );
+
+ while ( parts.length ) {
+ selector = parts.shift();
+
+ if ( Expr.relative[ selector ] ) {
+ selector += parts.shift();
+ }
+
+ set = posProcess( selector, set );
+ }
+ }
+
+ } else {
+ // Take a shortcut and set the context if the root selector is an ID
+ // (but not if it'll be faster if the inner selector is an ID)
+ if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
+ Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
+
+ ret = Sizzle.find( parts.shift(), context, contextXML );
+ context = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set )[0] :
+ ret.set[0];
+ }
+
+ if ( context ) {
+ ret = seed ?
+ { expr: parts.pop(), set: makeArray(seed) } :
+ Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
+
+ set = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set ) :
+ ret.set;
+
+ if ( parts.length > 0 ) {
+ checkSet = makeArray( set );
+
+ } else {
+ prune = false;
+ }
+
+ while ( parts.length ) {
+ cur = parts.pop();
+ pop = cur;
+
+ if ( !Expr.relative[ cur ] ) {
+ cur = "";
+ } else {
+ pop = parts.pop();
+ }
+
+ if ( pop == null ) {
+ pop = context;
+ }
+
+ Expr.relative[ cur ]( checkSet, pop, contextXML );
+ }
+
+ } else {
+ checkSet = parts = [];
+ }
+ }
+
+ if ( !checkSet ) {
+ checkSet = set;
+ }
+
+ if ( !checkSet ) {
+ Sizzle.error( cur || selector );
+ }
+
+ if ( toString.call(checkSet) === "[object Array]" ) {
+ if ( !prune ) {
+ results.push.apply( results, checkSet );
+
+ } else if ( context && context.nodeType === 1 ) {
+ for ( i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
+ results.push( set[i] );
+ }
+ }
+
+ } else {
+ for ( i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
+ results.push( set[i] );
+ }
+ }
+ }
+
+ } else {
+ makeArray( checkSet, results );
+ }
+
+ if ( extra ) {
+ Sizzle( extra, origContext, results, seed );
+ Sizzle.uniqueSort( results );
+ }
+
+ return results;
+};
+
+Sizzle.uniqueSort = function( results ) {
+ if ( sortOrder ) {
+ hasDuplicate = baseHasDuplicate;
+ results.sort( sortOrder );
+
+ if ( hasDuplicate ) {
+ for ( var i = 1; i < results.length; i++ ) {
+ if ( results[i] === results[ i - 1 ] ) {
+ results.splice( i--, 1 );
+ }
+ }
+ }
+ }
+
+ return results;
+};
+
+Sizzle.matches = function( expr, set ) {
+ return Sizzle( expr, null, null, set );
+};
+
+Sizzle.matchesSelector = function( node, expr ) {
+ return Sizzle( expr, null, null, [node] ).length > 0;
+};
+
+Sizzle.find = function( expr, context, isXML ) {
+ var set;
+
+ if ( !expr ) {
+ return [];
+ }
+
+ for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
+ var match,
+ type = Expr.order[i];
+
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
+ var left = match[1];
+ match.splice( 1, 1 );
+
+ if ( left.substr( left.length - 1 ) !== "\\" ) {
+ match[1] = (match[1] || "").replace(/\\/g, "");
+ set = Expr.find[ type ]( match, context, isXML );
+
+ if ( set != null ) {
+ expr = expr.replace( Expr.match[ type ], "" );
+ break;
+ }
+ }
+ }
+ }
+
+ if ( !set ) {
+ set = typeof context.getElementsByTagName !== "undefined" ?
+ context.getElementsByTagName( "*" ) :
+ [];
+ }
+
+ return { set: set, expr: expr };
+};
+
+Sizzle.filter = function( expr, set, inplace, not ) {
+ var match, anyFound,
+ old = expr,
+ result = [],
+ curLoop = set,
+ isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
+
+ while ( expr && set.length ) {
+ for ( var type in Expr.filter ) {
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
+ var found, item,
+ filter = Expr.filter[ type ],
+ left = match[1];
+
+ anyFound = false;
+
+ match.splice(1,1);
+
+ if ( left.substr( left.length - 1 ) === "\\" ) {
+ continue;
+ }
+
+ if ( curLoop === result ) {
+ result = [];
+ }
+
+ if ( Expr.preFilter[ type ] ) {
+ match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
+
+ if ( !match ) {
+ anyFound = found = true;
+
+ } else if ( match === true ) {
+ continue;
+ }
+ }
+
+ if ( match ) {
+ for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+ if ( item ) {
+ found = filter( item, match, i, curLoop );
+ var pass = not ^ !!found;
+
+ if ( inplace && found != null ) {
+ if ( pass ) {
+ anyFound = true;
+
+ } else {
+ curLoop[i] = false;
+ }
+
+ } else if ( pass ) {
+ result.push( item );
+ anyFound = true;
+ }
+ }
+ }
+ }
+
+ if ( found !== undefined ) {
+ if ( !inplace ) {
+ curLoop = result;
+ }
+
+ expr = expr.replace( Expr.match[ type ], "" );
+
+ if ( !anyFound ) {
+ return [];
+ }
+
+ break;
+ }
+ }
+ }
+
+ // Improper expression
+ if ( expr === old ) {
+ if ( anyFound == null ) {
+ Sizzle.error( expr );
+
+ } else {
+ break;
+ }
+ }
+
+ old = expr;
+ }
+
+ return curLoop;
+};
+
+Sizzle.error = function( msg ) {
+ throw "Syntax error, unrecognized expression: " + msg;
+};
+
+var Expr = Sizzle.selectors = {
+ order: [ "ID", "NAME", "TAG" ],
+
+ match: {
+ ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+ CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+ NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
+ ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
+ TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
+ CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
+ POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
+ PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
+ },
+
+ leftMatch: {},
+
+ attrMap: {
+ "class": "className",
+ "for": "htmlFor"
+ },
+
+ attrHandle: {
+ href: function( elem ) {
+ return elem.getAttribute( "href" );
+ }
+ },
+
+ relative: {
+ "+": function(checkSet, part){
+ var isPartStr = typeof part === "string",
+ isTag = isPartStr && !/\W/.test( part ),
+ isPartStrNotTag = isPartStr && !isTag;
+
+ if ( isTag ) {
+ part = part.toLowerCase();
+ }
+
+ for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
+ if ( (elem = checkSet[i]) ) {
+ while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
+
+ checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
+ elem || false :
+ elem === part;
+ }
+ }
+
+ if ( isPartStrNotTag ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ },
+
+ ">": function( checkSet, part ) {
+ var elem,
+ isPartStr = typeof part === "string",
+ i = 0,
+ l = checkSet.length;
+
+ if ( isPartStr && !/\W/.test( part ) ) {
+ part = part.toLowerCase();
+
+ for ( ; i < l; i++ ) {
+ elem = checkSet[i];
+
+ if ( elem ) {
+ var parent = elem.parentNode;
+ checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
+ }
+ }
+
+ } else {
+ for ( ; i < l; i++ ) {
+ elem = checkSet[i];
+
+ if ( elem ) {
+ checkSet[i] = isPartStr ?
+ elem.parentNode :
+ elem.parentNode === part;
+ }
+ }
+
+ if ( isPartStr ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ }
+ },
+
+ "": function(checkSet, part, isXML){
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
+
+ if ( typeof part === "string" && !/\W/.test(part) ) {
+ part = part.toLowerCase();
+ nodeCheck = part;
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
+ },
+
+ "~": function( checkSet, part, isXML ) {
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
+
+ if ( typeof part === "string" && !/\W/.test( part ) ) {
+ part = part.toLowerCase();
+ nodeCheck = part;
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
+ }
+ },
+
+ find: {
+ ID: function( match, context, isXML ) {
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ return m && m.parentNode ? [m] : [];
+ }
+ },
+
+ NAME: function( match, context ) {
+ if ( typeof context.getElementsByName !== "undefined" ) {
+ var ret = [],
+ results = context.getElementsByName( match[1] );
+
+ for ( var i = 0, l = results.length; i < l; i++ ) {
+ if ( results[i].getAttribute("name") === match[1] ) {
+ ret.push( results[i] );
+ }
+ }
+
+ return ret.length === 0 ? null : ret;
+ }
+ },
+
+ TAG: function( match, context ) {
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ return context.getElementsByTagName( match[1] );
+ }
+ }
+ },
+ preFilter: {
+ CLASS: function( match, curLoop, inplace, result, not, isXML ) {
+ match = " " + match[1].replace(/\\/g, "") + " ";
+
+ if ( isXML ) {
+ return match;
+ }
+
+ for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
+ if ( elem ) {
+ if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
+ if ( !inplace ) {
+ result.push( elem );
+ }
+
+ } else if ( inplace ) {
+ curLoop[i] = false;
+ }
+ }
+ }
+
+ return false;
+ },
+
+ ID: function( match ) {
+ return match[1].replace(/\\/g, "");
+ },
+
+ TAG: function( match, curLoop ) {
+ return match[1].toLowerCase();
+ },
+
+ CHILD: function( match ) {
+ if ( match[1] === "nth" ) {
+ if ( !match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ match[2] = match[2].replace(/^\+|\s*/g, '');
+
+ // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+ var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
+ match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
+ !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
+
+ // calculate the numbers (first)n+(last) including if they are negative
+ match[2] = (test[1] + (test[2] || 1)) - 0;
+ match[3] = test[3] - 0;
+ }
+ else if ( match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ // TODO: Move to normal caching system
+ match[0] = done++;
+
+ return match;
+ },
+
+ ATTR: function( match, curLoop, inplace, result, not, isXML ) {
+ var name = match[1] = match[1].replace(/\\/g, "");
+
+ if ( !isXML && Expr.attrMap[name] ) {
+ match[1] = Expr.attrMap[name];
+ }
+
+ // Handle if an un-quoted value was used
+ match[4] = ( match[4] || match[5] || "" ).replace(/\\/g, "");
+
+ if ( match[2] === "~=" ) {
+ match[4] = " " + match[4] + " ";
+ }
+
+ return match;
+ },
+
+ PSEUDO: function( match, curLoop, inplace, result, not ) {
+ if ( match[1] === "not" ) {
+ // If we're dealing with a complex expression, or a simple one
+ if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
+ match[3] = Sizzle(match[3], null, null, curLoop);
+
+ } else {
+ var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+
+ if ( !inplace ) {
+ result.push.apply( result, ret );
+ }
+
+ return false;
+ }
+
+ } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
+ return true;
+ }
+
+ return match;
+ },
+
+ POS: function( match ) {
+ match.unshift( true );
+
+ return match;
+ }
+ },
+
+ filters: {
+ enabled: function( elem ) {
+ return elem.disabled === false && elem.type !== "hidden";
+ },
+
+ disabled: function( elem ) {
+ return elem.disabled === true;
+ },
+
+ checked: function( elem ) {
+ return elem.checked === true;
+ },
+
+ selected: function( elem ) {
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ elem.parentNode.selectedIndex;
+
+ return elem.selected === true;
+ },
+
+ parent: function( elem ) {
+ return !!elem.firstChild;
+ },
+
+ empty: function( elem ) {
+ return !elem.firstChild;
+ },
+
+ has: function( elem, i, match ) {
+ return !!Sizzle( match[3], elem ).length;
+ },
+
+ header: function( elem ) {
+ return (/h\d/i).test( elem.nodeName );
+ },
+
+ text: function( elem ) {
+ return "text" === elem.type;
+ },
+ radio: function( elem ) {
+ return "radio" === elem.type;
+ },
+
+ checkbox: function( elem ) {
+ return "checkbox" === elem.type;
+ },
+
+ file: function( elem ) {
+ return "file" === elem.type;
+ },
+ password: function( elem ) {
+ return "password" === elem.type;
+ },
+
+ submit: function( elem ) {
+ return "submit" === elem.type;
+ },
+
+ image: function( elem ) {
+ return "image" === elem.type;
+ },
+
+ reset: function( elem ) {
+ return "reset" === elem.type;
+ },
+
+ button: function( elem ) {
+ return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
+ },
+
+ input: function( elem ) {
+ return (/input|select|textarea|button/i).test( elem.nodeName );
+ }
+ },
+ setFilters: {
+ first: function( elem, i ) {
+ return i === 0;
+ },
+
+ last: function( elem, i, match, array ) {
+ return i === array.length - 1;
+ },
+
+ even: function( elem, i ) {
+ return i % 2 === 0;
+ },
+
+ odd: function( elem, i ) {
+ return i % 2 === 1;
+ },
+
+ lt: function( elem, i, match ) {
+ return i < match[3] - 0;
+ },
+
+ gt: function( elem, i, match ) {
+ return i > match[3] - 0;
+ },
+
+ nth: function( elem, i, match ) {
+ return match[3] - 0 === i;
+ },
+
+ eq: function( elem, i, match ) {
+ return match[3] - 0 === i;
+ }
+ },
+ filter: {
+ PSEUDO: function( elem, match, i, array ) {
+ var name = match[1],
+ filter = Expr.filters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+
+ } else if ( name === "contains" ) {
+ return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
+
+ } else if ( name === "not" ) {
+ var not = match[3];
+
+ for ( var j = 0, l = not.length; j < l; j++ ) {
+ if ( not[j] === elem ) {
+ return false;
+ }
+ }
+
+ return true;
+
+ } else {
+ Sizzle.error( name );
+ }
+ },
+
+ CHILD: function( elem, match ) {
+ var type = match[1],
+ node = elem;
+
+ switch ( type ) {
+ case "only":
+ case "first":
+ while ( (node = node.previousSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+
+ if ( type === "first" ) {
+ return true;
+ }
+
+ node = elem;
+
+ case "last":
+ while ( (node = node.nextSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+
+ return true;
+
+ case "nth":
+ var first = match[2],
+ last = match[3];
+
+ if ( first === 1 && last === 0 ) {
+ return true;
+ }
+
+ var doneName = match[0],
+ parent = elem.parentNode;
+
+ if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
+ var count = 0;
+
+ for ( node = parent.firstChild; node; node = node.nextSibling ) {
+ if ( node.nodeType === 1 ) {
+ node.nodeIndex = ++count;
+ }
+ }
+
+ parent.sizcache = doneName;
+ }
+
+ var diff = elem.nodeIndex - last;
+
+ if ( first === 0 ) {
+ return diff === 0;
+
+ } else {
+ return ( diff % first === 0 && diff / first >= 0 );
+ }
+ }
+ },
+
+ ID: function( elem, match ) {
+ return elem.nodeType === 1 && elem.getAttribute("id") === match;
+ },
+
+ TAG: function( elem, match ) {
+ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
+ },
+
+ CLASS: function( elem, match ) {
+ return (" " + (elem.className || elem.getAttribute("class")) + " ")
+ .indexOf( match ) > -1;
+ },
+
+ ATTR: function( elem, match ) {
+ var name = match[1],
+ result = Expr.attrHandle[ name ] ?
+ Expr.attrHandle[ name ]( elem ) :
+ elem[ name ] != null ?
+ elem[ name ] :
+ elem.getAttribute( name ),
+ value = result + "",
+ type = match[2],
+ check = match[4];
+
+ return result == null ?
+ type === "!=" :
+ type === "=" ?
+ value === check :
+ type === "*=" ?
+ value.indexOf(check) >= 0 :
+ type === "~=" ?
+ (" " + value + " ").indexOf(check) >= 0 :
+ !check ?
+ value && result !== false :
+ type === "!=" ?
+ value !== check :
+ type === "^=" ?
+ value.indexOf(check) === 0 :
+ type === "$=" ?
+ value.substr(value.length - check.length) === check :
+ type === "|=" ?
+ value === check || value.substr(0, check.length + 1) === check + "-" :
+ false;
+ },
+
+ POS: function( elem, match, i, array ) {
+ var name = match[2],
+ filter = Expr.setFilters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+ }
+ }
+ }
+};
+
+var origPOS = Expr.match.POS,
+ fescape = function(all, num){
+ return "\\" + (num - 0 + 1);
+ };
+
+for ( var type in Expr.match ) {
+ Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
+ Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
+}
+
+var makeArray = function( array, results ) {
+ array = Array.prototype.slice.call( array, 0 );
+
+ if ( results ) {
+ results.push.apply( results, array );
+ return results;
+ }
+
+ return array;
+};
+
+// Perform a simple check to determine if the browser is capable of
+// converting a NodeList to an array using builtin methods.
+// Also verifies that the returned array holds DOM nodes
+// (which is not the case in the Blackberry browser)
+try {
+ Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
+
+// Provide a fallback method if it does not work
+} catch( e ) {
+ makeArray = function( array, results ) {
+ var i = 0,
+ ret = results || [];
+
+ if ( toString.call(array) === "[object Array]" ) {
+ Array.prototype.push.apply( ret, array );
+
+ } else {
+ if ( typeof array.length === "number" ) {
+ for ( var l = array.length; i < l; i++ ) {
+ ret.push( array[i] );
+ }
+
+ } else {
+ for ( ; array[i]; i++ ) {
+ ret.push( array[i] );
+ }
+ }
+ }
+
+ return ret;
+ };
+}
+
+var sortOrder, siblingCheck;
+
+if ( document.documentElement.compareDocumentPosition ) {
+ sortOrder = function( a, b ) {
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
+ return a.compareDocumentPosition ? -1 : 1;
+ }
+
+ return a.compareDocumentPosition(b) & 4 ? -1 : 1;
+ };
+
+} else {
+ sortOrder = function( a, b ) {
+ var al, bl,
+ ap = [],
+ bp = [],
+ aup = a.parentNode,
+ bup = b.parentNode,
+ cur = aup;
+
+ // The nodes are identical, we can exit early
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+
+ // If the nodes are siblings (or identical) we can do a quick check
+ } else if ( aup === bup ) {
+ return siblingCheck( a, b );
+
+ // If no parents were found then the nodes are disconnected
+ } else if ( !aup ) {
+ return -1;
+
+ } else if ( !bup ) {
+ return 1;
+ }
+
+ // Otherwise they're somewhere else in the tree so we need
+ // to build up a full list of the parentNodes for comparison
+ while ( cur ) {
+ ap.unshift( cur );
+ cur = cur.parentNode;
+ }
+
+ cur = bup;
+
+ while ( cur ) {
+ bp.unshift( cur );
+ cur = cur.parentNode;
+ }
+
+ al = ap.length;
+ bl = bp.length;
+
+ // Start walking down the tree looking for a discrepancy
+ for ( var i = 0; i < al && i < bl; i++ ) {
+ if ( ap[i] !== bp[i] ) {
+ return siblingCheck( ap[i], bp[i] );
+ }
+ }
+
+ // We ended someplace up the tree so do a sibling check
+ return i === al ?
+ siblingCheck( a, bp[i], -1 ) :
+ siblingCheck( ap[i], b, 1 );
+ };
+
+ siblingCheck = function( a, b, ret ) {
+ if ( a === b ) {
+ return ret;
+ }
+
+ var cur = a.nextSibling;
+
+ while ( cur ) {
+ if ( cur === b ) {
+ return -1;
+ }
+
+ cur = cur.nextSibling;
+ }
+
+ return 1;
+ };
+}
+
+// Utility function for retreiving the text value of an array of DOM nodes
+Sizzle.getText = function( elems ) {
+ var ret = "", elem;
+
+ for ( var i = 0; elems[i]; i++ ) {
+ elem = elems[i];
+
+ // Get the text from text nodes and CDATA nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
+ ret += elem.nodeValue;
+
+ // Traverse everything else, except comment nodes
+ } else if ( elem.nodeType !== 8 ) {
+ ret += Sizzle.getText( elem.childNodes );
+ }
+ }
+
+ return ret;
+};
+
+// Check to see if the browser returns elements by name when
+// querying by getElementById (and provide a workaround)
+(function(){
+ // We're going to inject a fake input element with a specified name
+ var form = document.createElement("div"),
+ id = "script" + (new Date()).getTime(),
+ root = document.documentElement;
+
+ form.innerHTML = "<a name='" + id + "'/>";
+
+ // Inject it into the root element, check its status, and remove it quickly
+ root.insertBefore( form, root.firstChild );
+
+ // The workaround has to do additional checks after a getElementById
+ // Which slows things down for other browsers (hence the branching)
+ if ( document.getElementById( id ) ) {
+ Expr.find.ID = function( match, context, isXML ) {
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+
+ return m ?
+ m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
+ [m] :
+ undefined :
+ [];
+ }
+ };
+
+ Expr.filter.ID = function( elem, match ) {
+ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+
+ return elem.nodeType === 1 && node && node.nodeValue === match;
+ };
+ }
+
+ root.removeChild( form );
+
+ // release memory in IE
+ root = form = null;
+})();
+
+(function(){
+ // Check to see if the browser returns only elements
+ // when doing getElementsByTagName("*")
+
+ // Create a fake element
+ var div = document.createElement("div");
+ div.appendChild( document.createComment("") );
+
+ // Make sure no comments are found
+ if ( div.getElementsByTagName("*").length > 0 ) {
+ Expr.find.TAG = function( match, context ) {
+ var results = context.getElementsByTagName( match[1] );
+
+ // Filter out possible comments
+ if ( match[1] === "*" ) {
+ var tmp = [];
+
+ for ( var i = 0; results[i]; i++ ) {
+ if ( results[i].nodeType === 1 ) {
+ tmp.push( results[i] );
+ }
+ }
+
+ results = tmp;
+ }
+
+ return results;
+ };
+ }
+
+ // Check to see if an attribute returns normalized href attributes
+ div.innerHTML = "<a href='#'></a>";
+
+ if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+ div.firstChild.getAttribute("href") !== "#" ) {
+
+ Expr.attrHandle.href = function( elem ) {
+ return elem.getAttribute( "href", 2 );
+ };
+ }
+
+ // release memory in IE
+ div = null;
+})();
+
+if ( document.querySelectorAll ) {
+ (function(){
+ var oldSizzle = Sizzle,
+ div = document.createElement("div"),
+ id = "__sizzle__";
+
+ div.innerHTML = "<p class='TEST'></p>";
+
+ // Safari can't handle uppercase or unicode characters when
+ // in quirks mode.
+ if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
+ return;
+ }
+
+ Sizzle = function( query, context, extra, seed ) {
+ context = context || document;
+
+ // Only use querySelectorAll on non-XML documents
+ // (ID selectors don't work in non-HTML documents)
+ if ( !seed && !Sizzle.isXML(context) ) {
+ // See if we find a selector to speed up
+ var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
+
+ if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
+ // Speed-up: Sizzle("TAG")
+ if ( match[1] ) {
+ return makeArray( context.getElementsByTagName( query ), extra );
+
+ // Speed-up: Sizzle(".CLASS")
+ } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
+ return makeArray( context.getElementsByClassName( match[2] ), extra );
+ }
+ }
+
+ if ( context.nodeType === 9 ) {
+ // Speed-up: Sizzle("body")
+ // The body element only exists once, optimize finding it
+ if ( query === "body" && context.body ) {
+ return makeArray( [ context.body ], extra );
+
+ // Speed-up: Sizzle("#ID")
+ } else if ( match && match[3] ) {
+ var elem = context.getElementById( match[3] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id === match[3] ) {
+ return makeArray( [ elem ], extra );
+ }
+
+ } else {
+ return makeArray( [], extra );
+ }
+ }
+
+ try {
+ return makeArray( context.querySelectorAll(query), extra );
+ } catch(qsaError) {}
+
+ // qSA works strangely on Element-rooted queries
+ // We can work around this by specifying an extra ID on the root
+ // and working up from there (Thanks to Andrew Dupont for the technique)
+ // IE 8 doesn't work on object elements
+ } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+ var old = context.getAttribute( "id" ),
+ nid = old || id,
+ hasParent = context.parentNode,
+ relativeHierarchySelector = /^\s*[+~]/.test( query );
+
+ if ( !old ) {
+ context.setAttribute( "id", nid );
+ } else {
+ nid = nid.replace( /'/g, "\\$&" );
+ }
+ if ( relativeHierarchySelector && hasParent ) {
+ context = context.parentNode;
+ }
+
+ try {
+ if ( !relativeHierarchySelector || hasParent ) {
+ return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
+ }
+
+ } catch(pseudoError) {
+ } finally {
+ if ( !old ) {
+ context.removeAttribute( "id" );
+ }
+ }
+ }
+ }
+
+ return oldSizzle(query, context, extra, seed);
+ };
+
+ for ( var prop in oldSizzle ) {
+ Sizzle[ prop ] = oldSizzle[ prop ];
+ }
+
+ // release memory in IE
+ div = null;
+ })();
+}
+
+(function(){
+ var html = document.documentElement,
+ matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector,
+ pseudoWorks = false;
+
+ try {
+ // This should fail with an exception
+ // Gecko does not error, returns false instead
+ matches.call( document.documentElement, "[test!='']:sizzle" );
+
+ } catch( pseudoError ) {
+ pseudoWorks = true;
+ }
+
+ if ( matches ) {
+ Sizzle.matchesSelector = function( node, expr ) {
+ // Make sure that attribute selectors are quoted
+ expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
+ if ( !Sizzle.isXML( node ) ) {
+ try {
+ if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
+ return matches.call( node, expr );
+ }
+ } catch(e) {}
+ }
+
+ return Sizzle(expr, null, null, [node]).length > 0;
+ };
+ }
+})();
+
+(function(){
+ var div = document.createElement("div");
+
+ div.innerHTML = "<div class='test e'></div><div class='test'></div>";
+
+ // Opera can't find a second classname (in 9.6)
+ // Also, make sure that getElementsByClassName actually exists
+ if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
+ return;
+ }
+
+ // Safari caches class attributes, doesn't catch changes (in 3.2)
+ div.lastChild.className = "e";
+
+ if ( div.getElementsByClassName("e").length === 1 ) {
+ return;
+ }
+
+ Expr.order.splice(1, 0, "CLASS");
+ Expr.find.CLASS = function( match, context, isXML ) {
+ if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
+ return context.getElementsByClassName(match[1]);
+ }
+ };
+
+ // release memory in IE
+ div = null;
+})();
+
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+
+ if ( elem ) {
+ var match = false;
+
+ elem = elem[dir];
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 && !isXML ){
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+
+ if ( elem.nodeName.toLowerCase() === cur ) {
+ match = elem;
+ break;
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+
+ if ( elem ) {
+ var match = false;
+
+ elem = elem[dir];
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 ) {
+ if ( !isXML ) {
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+
+ if ( typeof cur !== "string" ) {
+ if ( elem === cur ) {
+ match = true;
+ break;
+ }
+
+ } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
+ match = elem;
+ break;
+ }
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+if ( document.documentElement.contains ) {
+ Sizzle.contains = function( a, b ) {
+ return a !== b && (a.contains ? a.contains(b) : true);
+ };
+
+} else if ( document.documentElement.compareDocumentPosition ) {
+ Sizzle.contains = function( a, b ) {
+ return !!(a.compareDocumentPosition(b) & 16);
+ };
+
+} else {
+ Sizzle.contains = function() {
+ return false;
+ };
+}
+
+Sizzle.isXML = function( elem ) {
+ // documentElement is verified for cases where it doesn't yet exist
+ // (such as loading iframes in IE - #4833)
+ var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
+
+ return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+var posProcess = function( selector, context ) {
+ var match,
+ tmpSet = [],
+ later = "",
+ root = context.nodeType ? [context] : context;
+
+ // Position selectors must be done after the filter
+ // And so must :not(positional) so we move all PSEUDOs to the end
+ while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
+ later += match[0];
+ selector = selector.replace( Expr.match.PSEUDO, "" );
+ }
+
+ selector = Expr.relative[selector] ? selector + "*" : selector;
+
+ for ( var i = 0, l = root.length; i < l; i++ ) {
+ Sizzle( selector, root[i], tmpSet );
+ }
+
+ return Sizzle.filter( later, tmpSet );
+};
+
+// EXPOSE
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.filters;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+})();
+
+
+var runtil = /Until$/,
+ rparentsprev = /^(?:parents|prevUntil|prevAll)/,
+ // Note: This RegExp should be improved, or likely pulled from Sizzle
+ rmultiselector = /,/,
+ isSimple = /^.[^:#\[\.,]*$/,
+ slice = Array.prototype.slice,
+ POS = jQuery.expr.match.POS,
+ // methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+jQuery.fn.extend({
+ find: function( selector ) {
+ var ret = this.pushStack( "", "find", selector ),
+ length = 0;
+
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ length = ret.length;
+ jQuery.find( selector, this[i], ret );
+
+ if ( i > 0 ) {
+ // Make sure that the results are unique
+ for ( var n = length; n < ret.length; n++ ) {
+ for ( var r = 0; r < length; r++ ) {
+ if ( ret[r] === ret[n] ) {
+ ret.splice(n--, 1);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ has: function( target ) {
+ var targets = jQuery( target );
+ return this.filter(function() {
+ for ( var i = 0, l = targets.length; i < l; i++ ) {
+ if ( jQuery.contains( this, targets[i] ) ) {
+ return true;
+ }
+ }
+ });
+ },
+
+ not: function( selector ) {
+ return this.pushStack( winnow(this, selector, false), "not", selector);
+ },
+
+ filter: function( selector ) {
+ return this.pushStack( winnow(this, selector, true), "filter", selector );
+ },
+
+ is: function( selector ) {
+ return !!selector && jQuery.filter( selector, this ).length > 0;
+ },
+
+ closest: function( selectors, context ) {
+ var ret = [], i, l, cur = this[0];
+
+ if ( jQuery.isArray( selectors ) ) {
+ var match, selector,
+ matches = {},
+ level = 1;
+
+ if ( cur && selectors.length ) {
+ for ( i = 0, l = selectors.length; i < l; i++ ) {
+ selector = selectors[i];
+
+ if ( !matches[selector] ) {
+ matches[selector] = jQuery.expr.match.POS.test( selector ) ?
+ jQuery( selector, context || this.context ) :
+ selector;
+ }
+ }
+
+ while ( cur && cur.ownerDocument && cur !== context ) {
+ for ( selector in matches ) {
+ match = matches[selector];
+
+ if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
+ ret.push({ selector: selector, elem: cur, level: level });
+ }
+ }
+
+ cur = cur.parentNode;
+ level++;
+ }
+ }
+
+ return ret;
+ }
+
+ var pos = POS.test( selectors ) ?
+ jQuery( selectors, context || this.context ) : null;
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ cur = this[i];
+
+ while ( cur ) {
+ if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
+ ret.push( cur );
+ break;
+
+ } else {
+ cur = cur.parentNode;
+ if ( !cur || !cur.ownerDocument || cur === context ) {
+ break;
+ }
+ }
+ }
+ }
+
+ ret = ret.length > 1 ? jQuery.unique(ret) : ret;
+
+ return this.pushStack( ret, "closest", selectors );
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function( elem ) {
+ if ( !elem || typeof elem === "string" ) {
+ return jQuery.inArray( this[0],
+ // If it receives a string, the selector is used
+ // If it receives nothing, the siblings are used
+ elem ? jQuery( elem ) : this.parent().children() );
+ }
+ // Locate the position of the desired element
+ return jQuery.inArray(
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[0] : elem, this );
+ },
+
+ add: function( selector, context ) {
+ var set = typeof selector === "string" ?
+ jQuery( selector, context ) :
+ jQuery.makeArray( selector ),
+ all = jQuery.merge( this.get(), set );
+
+ return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
+ all :
+ jQuery.unique( all ) );
+ },
+
+ andSelf: function() {
+ return this.add( this.prevObject );
+ }
+});
+
+// A painfully simple check to see if an element is disconnected
+// from a document (should be improved, where feasible).
+function isDisconnected( node ) {
+ return !node || !node.parentNode || node.parentNode.nodeType === 11;
+}
+
+jQuery.each({
+ parent: function( elem ) {
+ var parent = elem.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+ parents: function( elem ) {
+ return jQuery.dir( elem, "parentNode" );
+ },
+ parentsUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "parentNode", until );
+ },
+ next: function( elem ) {
+ return jQuery.nth( elem, 2, "nextSibling" );
+ },
+ prev: function( elem ) {
+ return jQuery.nth( elem, 2, "previousSibling" );
+ },
+ nextAll: function( elem ) {
+ return jQuery.dir( elem, "nextSibling" );
+ },
+ prevAll: function( elem ) {
+ return jQuery.dir( elem, "previousSibling" );
+ },
+ nextUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "nextSibling", until );
+ },
+ prevUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "previousSibling", until );
+ },
+ siblings: function( elem ) {
+ return jQuery.sibling( elem.parentNode.firstChild, elem );
+ },
+ children: function( elem ) {
+ return jQuery.sibling( elem.firstChild );
+ },
+ contents: function( elem ) {
+ return jQuery.nodeName( elem, "iframe" ) ?
+ elem.contentDocument || elem.contentWindow.document :
+ jQuery.makeArray( elem.childNodes );
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function( until, selector ) {
+ var ret = jQuery.map( this, fn, until ),
+ // The variable 'args' was introduced in
+ // https://github.com/jquery/jquery/commit/52a0238
+ // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
+ // http://code.google.com/p/v8/issues/detail?id=1050
+ args = slice.call(arguments);
+
+ if ( !runtil.test( name ) ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ ret = jQuery.filter( selector, ret );
+ }
+
+ ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
+
+ if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
+ ret = ret.reverse();
+ }
+
+ return this.pushStack( ret, name, args.join(",") );
+ };
+});
+
+jQuery.extend({
+ filter: function( expr, elems, not ) {
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return elems.length === 1 ?
+ jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
+ jQuery.find.matches(expr, elems);
+ },
+
+ dir: function( elem, dir, until ) {
+ var matched = [],
+ cur = elem[ dir ];
+
+ while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
+ if ( cur.nodeType === 1 ) {
+ matched.push( cur );
+ }
+ cur = cur[dir];
+ }
+ return matched;
+ },
+
+ nth: function( cur, result, dir, elem ) {
+ result = result || 1;
+ var num = 0;
+
+ for ( ; cur; cur = cur[dir] ) {
+ if ( cur.nodeType === 1 && ++num === result ) {
+ break;
+ }
+ }
+
+ return cur;
+ },
+
+ sibling: function( n, elem ) {
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ r.push( n );
+ }
+ }
+
+ return r;
+ }
+});
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, keep ) {
+ if ( jQuery.isFunction( qualifier ) ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ var retVal = !!qualifier.call( elem, i, elem );
+ return retVal === keep;
+ });
+
+ } else if ( qualifier.nodeType ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ return (elem === qualifier) === keep;
+ });
+
+ } else if ( typeof qualifier === "string" ) {
+ var filtered = jQuery.grep(elements, function( elem ) {
+ return elem.nodeType === 1;
+ });
+
+ if ( isSimple.test( qualifier ) ) {
+ return jQuery.filter(qualifier, filtered, !keep);
+ } else {
+ qualifier = jQuery.filter( qualifier, filtered );
+ }
+ }
+
+ return jQuery.grep(elements, function( elem, i ) {
+ return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
+ });
+}
+
+
+
+
+var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
+ rleadingWhitespace = /^\s+/,
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
+ rtagName = /<([\w:]+)/,
+ rtbody = /<tbody/i,
+ rhtml = /<|&#?\w+;/,
+ rnocache = /<(?:script|object|embed|option|style)/i,
+ // checked="checked" or checked (html5)
+ rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+ wrapMap = {
+ option: [ 1, "<select multiple='multiple'>", "</select>" ],
+ legend: [ 1, "<fieldset>", "</fieldset>" ],
+ thead: [ 1, "<table>", "</table>" ],
+ tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+ td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+ col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
+ area: [ 1, "<map>", "</map>" ],
+ _default: [ 0, "", "" ]
+ };
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+// IE can't serialize <link> and <script> tags normally
+if ( !jQuery.support.htmlSerialize ) {
+ wrapMap._default = [ 1, "div<div>", "</div>" ];
+}
+
+jQuery.fn.extend({
+ text: function( text ) {
+ if ( jQuery.isFunction(text) ) {
+ return this.each(function(i) {
+ var self = jQuery( this );
+
+ self.text( text.call(this, i, self.text()) );
+ });
+ }
+
+ if ( typeof text !== "object" && text !== undefined ) {
+ return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
+ }
+
+ return jQuery.text( this );
+ },
+
+ wrapAll: function( html ) {
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function(i) {
+ jQuery(this).wrapAll( html.call(this, i) );
+ });
+ }
+
+ if ( this[0] ) {
+ // The elements to wrap the target around
+ var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
+
+ if ( this[0].parentNode ) {
+ wrap.insertBefore( this[0] );
+ }
+
+ wrap.map(function() {
+ var elem = this;
+
+ while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
+ elem = elem.firstChild;
+ }
+
+ return elem;
+ }).append(this);
+ }
+
+ return this;
+ },
+
+ wrapInner: function( html ) {
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function(i) {
+ jQuery(this).wrapInner( html.call(this, i) );
+ });
+ }
+
+ return this.each(function() {
+ var self = jQuery( this ),
+ contents = self.contents();
+
+ if ( contents.length ) {
+ contents.wrapAll( html );
+
+ } else {
+ self.append( html );
+ }
+ });
+ },
+
+ wrap: function( html ) {
+ return this.each(function() {
+ jQuery( this ).wrapAll( html );
+ });
+ },
+
+ unwrap: function() {
+ return this.parent().each(function() {
+ if ( !jQuery.nodeName( this, "body" ) ) {
+ jQuery( this ).replaceWith( this.childNodes );
+ }
+ }).end();
+ },
+
+ append: function() {
+ return this.domManip(arguments, true, function( elem ) {
+ if ( this.nodeType === 1 ) {
+ this.appendChild( elem );
+ }
+ });
+ },
+
+ prepend: function() {
+ return this.domManip(arguments, true, function( elem ) {
+ if ( this.nodeType === 1 ) {
+ this.insertBefore( elem, this.firstChild );
+ }
+ });
+ },
+
+ before: function() {
+ if ( this[0] && this[0].parentNode ) {
+ return this.domManip(arguments, false, function( elem ) {
+ this.parentNode.insertBefore( elem, this );
+ });
+ } else if ( arguments.length ) {
+ var set = jQuery(arguments[0]);
+ set.push.apply( set, this.toArray() );
+ return this.pushStack( set, "before", arguments );
+ }
+ },
+
+ after: function() {
+ if ( this[0] && this[0].parentNode ) {
+ return this.domManip(arguments, false, function( elem ) {
+ this.parentNode.insertBefore( elem, this.nextSibling );
+ });
+ } else if ( arguments.length ) {
+ var set = this.pushStack( this, "after", arguments );
+ set.push.apply( set, jQuery(arguments[0]).toArray() );
+ return set;
+ }
+ },
+
+ // keepData is for internal use only--do not document
+ remove: function( selector, keepData ) {
+ for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
+ if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
+ if ( !keepData && elem.nodeType === 1 ) {
+ jQuery.cleanData( elem.getElementsByTagName("*") );
+ jQuery.cleanData( [ elem ] );
+ }
+
+ if ( elem.parentNode ) {
+ elem.parentNode.removeChild( elem );
+ }
+ }
+ }
+
+ return this;
+ },
+
+ empty: function() {
+ for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
+ // Remove element nodes and prevent memory leaks
+ if ( elem.nodeType === 1 ) {
+ jQuery.cleanData( elem.getElementsByTagName("*") );
+ }
+
+ // Remove any remaining nodes
+ while ( elem.firstChild ) {
+ elem.removeChild( elem.firstChild );
+ }
+ }
+
+ return this;
+ },
+
+ clone: function( dataAndEvents, deepDataAndEvents ) {
+ dataAndEvents = dataAndEvents == null ? true : dataAndEvents;
+ deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
+
+ return this.map( function () {
+ return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+ });
+ },
+
+ html: function( value ) {
+ if ( value === undefined ) {
+ return this[0] && this[0].nodeType === 1 ?
+ this[0].innerHTML.replace(rinlinejQuery, "") :
+ null;
+
+ // See if we can take a shortcut and just use innerHTML
+ } else if ( typeof value === "string" && !rnocache.test( value ) &&
+ (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
+ !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
+
+ value = value.replace(rxhtmlTag, "<$1></$2>");
+
+ try {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ // Remove element nodes and prevent memory leaks
+ if ( this[i].nodeType === 1 ) {
+ jQuery.cleanData( this[i].getElementsByTagName("*") );
+ this[i].innerHTML = value;
+ }
+ }
+
+ // If using innerHTML throws an exception, use the fallback method
+ } catch(e) {
+ this.empty().append( value );
+ }
+
+ } else if ( jQuery.isFunction( value ) ) {
+ this.each(function(i){
+ var self = jQuery( this );
+
+ self.html( value.call(this, i, self.html()) );
+ });
+
+ } else {
+ this.empty().append( value );
+ }
+
+ return this;
+ },
+
+ replaceWith: function( value ) {
+ if ( this[0] && this[0].parentNode ) {
+ // Make sure that the elements are removed from the DOM before they are inserted
+ // this can help fix replacing a parent with child elements
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function(i) {
+ var self = jQuery(this), old = self.html();
+ self.replaceWith( value.call( this, i, old ) );
+ });
+ }
+
+ if ( typeof value !== "string" ) {
+ value = jQuery( value ).detach();
+ }
+
+ return this.each(function() {
+ var next = this.nextSibling,
+ parent = this.parentNode;
+
+ jQuery( this ).remove();
+
+ if ( next ) {
+ jQuery(next).before( value );
+ } else {
+ jQuery(parent).append( value );
+ }
+ });
+ } else {
+ return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
+ }
+ },
+
+ detach: function( selector ) {
+ return this.remove( selector, true );
+ },
+
+ domManip: function( args, table, callback ) {
+ var results, first, fragment, parent,
+ value = args[0],
+ scripts = [];
+
+ // We can't cloneNode fragments that contain checked, in WebKit
+ if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
+ return this.each(function() {
+ jQuery(this).domManip( args, table, callback, true );
+ });
+ }
+
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ args[0] = value.call(this, i, table ? self.html() : undefined);
+ self.domManip( args, table, callback );
+ });
+ }
+
+ if ( this[0] ) {
+ parent = value && value.parentNode;
+
+ // If we're in a fragment, just use that instead of building a new one
+ if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
+ results = { fragment: parent };
+
+ } else {
+ results = jQuery.buildFragment( args, this, scripts );
+ }
+
+ fragment = results.fragment;
+
+ if ( fragment.childNodes.length === 1 ) {
+ first = fragment = fragment.firstChild;
+ } else {
+ first = fragment.firstChild;
+ }
+
+ if ( first ) {
+ table = table && jQuery.nodeName( first, "tr" );
+
+ for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
+ callback.call(
+ table ?
+ root(this[i], first) :
+ this[i],
+ // Make sure that we do not leak memory by inadvertently discarding
+ // the original fragment (which might have attached data) instead of
+ // using it; in addition, use the original fragment object for the last
+ // item instead of first because it can end up being emptied incorrectly
+ // in certain situations (Bug #8070).
+ // Fragments from the fragment cache must always be cloned and never used
+ // in place.
+ results.cacheable || (l > 1 && i < lastIndex) ?
+ jQuery.clone( fragment, true, true ) :
+ fragment
+ );
+ }
+ }
+
+ if ( scripts.length ) {
+ jQuery.each( scripts, evalScript );
+ }
+ }
+
+ return this;
+ }
+});
+
+function root( elem, cur ) {
+ return jQuery.nodeName(elem, "table") ?
+ (elem.getElementsByTagName("tbody")[0] ||
+ elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
+ elem;
+}
+
+function cloneCopyEvent( src, dest ) {
+
+ if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
+ return;
+ }
+
+ var internalKey = jQuery.expando,
+ oldData = jQuery.data( src ),
+ curData = jQuery.data( dest, oldData );
+
+ // Switch to use the internal data object, if it exists, for the next
+ // stage of data copying
+ if ( (oldData = oldData[ internalKey ]) ) {
+ var events = oldData.events;
+ curData = curData[ internalKey ] = jQuery.extend({}, oldData);
+
+ if ( events ) {
+ delete curData.handle;
+ curData.events = {};
+
+ for ( var type in events ) {
+ for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
+ jQuery.event.add( dest, type, events[ type ][ i ], events[ type ][ i ].data );
+ }
+ }
+ }
+ }
+}
+
+function cloneFixAttributes(src, dest) {
+ // We do not need to do anything for non-Elements
+ if ( dest.nodeType !== 1 ) {
+ return;
+ }
+
+ var nodeName = dest.nodeName.toLowerCase();
+
+ // clearAttributes removes the attributes, which we don't want,
+ // but also removes the attachEvent events, which we *do* want
+ dest.clearAttributes();
+
+ // mergeAttributes, in contrast, only merges back on the
+ // original attributes, not the events
+ dest.mergeAttributes(src);
+
+ // IE6-8 fail to clone children inside object elements that use
+ // the proprietary classid attribute value (rather than the type
+ // attribute) to identify the type of content to display
+ if ( nodeName === "object" ) {
+ dest.outerHTML = src.outerHTML;
+
+ } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
+ // IE6-8 fails to persist the checked state of a cloned checkbox
+ // or radio button. Worse, IE6-7 fail to give the cloned element
+ // a checked appearance if the defaultChecked value isn't also set
+ if ( src.checked ) {
+ dest.defaultChecked = dest.checked = src.checked;
+ }
+
+ // IE6-7 get confused and end up setting the value of a cloned
+ // checkbox/radio button to an empty string instead of "on"
+ if ( dest.value !== src.value ) {
+ dest.value = src.value;
+ }
+
+ // IE6-8 fails to return the selected option to the default selected
+ // state when cloning options
+ } else if ( nodeName === "option" ) {
+ dest.selected = src.defaultSelected;
+
+ // IE6-8 fails to set the defaultValue to the correct value when
+ // cloning other types of input fields
+ } else if ( nodeName === "input" || nodeName === "textarea" ) {
+ dest.defaultValue = src.defaultValue;
+ }
+
+ // Event data gets referenced instead of copied if the expando
+ // gets copied too
+ dest.removeAttribute( jQuery.expando );
+}
+
+jQuery.buildFragment = function( args, nodes, scripts ) {
+ var fragment, cacheable, cacheresults,
+ doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
+
+ // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
+ // Cloning options loses the selected state, so don't cache them
+ // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
+ // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
+ if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
+ args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
+
+ cacheable = true;
+ cacheresults = jQuery.fragments[ args[0] ];
+ if ( cacheresults ) {
+ if ( cacheresults !== 1 ) {
+ fragment = cacheresults;
+ }
+ }
+ }
+
+ if ( !fragment ) {
+ fragment = doc.createDocumentFragment();
+ jQuery.clean( args, doc, fragment, scripts );
+ }
+
+ if ( cacheable ) {
+ jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
+ }
+
+ return { fragment: fragment, cacheable: cacheable };
+};
+
+jQuery.fragments = {};
+
+jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+}, function( name, original ) {
+ jQuery.fn[ name ] = function( selector ) {
+ var ret = [],
+ insert = jQuery( selector ),
+ parent = this.length === 1 && this[0].parentNode;
+
+ if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
+ insert[ original ]( this[0] );
+ return this;
+
+ } else {
+ for ( var i = 0, l = insert.length; i < l; i++ ) {
+ var elems = (i > 0 ? this.clone(true) : this).get();
+ jQuery( insert[i] )[ original ]( elems );
+ ret = ret.concat( elems );
+ }
+
+ return this.pushStack( ret, name, insert.selector );
+ }
+ };
+});
+
+jQuery.extend({
+ clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+ var clone = elem.cloneNode(true),
+ srcElements,
+ destElements,
+ i;
+
+ if ( !jQuery.support.noCloneEvent && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
+ // IE copies events bound via attachEvent when using cloneNode.
+ // Calling detachEvent on the clone will also remove the events
+ // from the original. In order to get around this, we use some
+ // proprietary methods to clear the events. Thanks to MooTools
+ // guys for this hotness.
+
+ // Using Sizzle here is crazy slow, so we use getElementsByTagName
+ // instead
+ srcElements = elem.getElementsByTagName("*");
+ destElements = clone.getElementsByTagName("*");
+
+ // Weird iteration because IE will replace the length property
+ // with an element if you are cloning the body and one of the
+ // elements on the page has a name or id of "length"
+ for ( i = 0; srcElements[i]; ++i ) {
+ cloneFixAttributes( srcElements[i], destElements[i] );
+ }
+
+ cloneFixAttributes( elem, clone );
+ }
+
+ // Copy the events from the original to the clone
+ if ( dataAndEvents ) {
+
+ cloneCopyEvent( elem, clone );
+
+ if ( deepDataAndEvents && "getElementsByTagName" in elem ) {
+
+ srcElements = elem.getElementsByTagName("*");
+ destElements = clone.getElementsByTagName("*");
+
+ if ( srcElements.length ) {
+ for ( i = 0; srcElements[i]; ++i ) {
+ cloneCopyEvent( srcElements[i], destElements[i] );
+ }
+ }
+ }
+ }
+ // Return the cloned set
+ return clone;
+ },
+ clean: function( elems, context, fragment, scripts ) {
+ context = context || document;
+
+ // !context.createElement fails in IE with an error but returns typeof 'object'
+ if ( typeof context.createElement === "undefined" ) {
+ context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+ }
+
+ var ret = [];
+
+ for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
+ if ( typeof elem === "number" ) {
+ elem += "";
+ }
+
+ if ( !elem ) {
+ continue;
+ }
+
+ // Convert html string into DOM nodes
+ if ( typeof elem === "string" && !rhtml.test( elem ) ) {
+ elem = context.createTextNode( elem );
+
+ } else if ( typeof elem === "string" ) {
+ // Fix "XHTML"-style tags in all browsers
+ elem = elem.replace(rxhtmlTag, "<$1></$2>");
+
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
+ wrap = wrapMap[ tag ] || wrapMap._default,
+ depth = wrap[0],
+ div = context.createElement("div");
+
+ // Go to html and back, then peel off extra wrappers
+ div.innerHTML = wrap[1] + elem + wrap[2];
+
+ // Move to the right depth
+ while ( depth-- ) {
+ div = div.lastChild;
+ }
+
+ // Remove IE's autoinserted <tbody> from table fragments
+ if ( !jQuery.support.tbody ) {
+
+ // String was a <table>, *may* have spurious <tbody>
+ var hasBody = rtbody.test(elem),
+ tbody = tag === "table" && !hasBody ?
+ div.firstChild && div.firstChild.childNodes :
+
+ // String was a bare <thead> or <tfoot>
+ wrap[1] === "<table>" && !hasBody ?
+ div.childNodes :
+ [];
+
+ for ( var j = tbody.length - 1; j >= 0 ; --j ) {
+ if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
+ tbody[ j ].parentNode.removeChild( tbody[ j ] );
+ }
+ }
+
+ }
+
+ // IE completely kills leading whitespace when innerHTML is used
+ if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
+ div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
+ }
+
+ elem = div.childNodes;
+ }
+
+ if ( elem.nodeType ) {
+ ret.push( elem );
+ } else {
+ ret = jQuery.merge( ret, elem );
+ }
+ }
+
+ if ( fragment ) {
+ for ( i = 0; ret[i]; i++ ) {
+ if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
+ scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
+
+ } else {
+ if ( ret[i].nodeType === 1 ) {
+ ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
+ }
+ fragment.appendChild( ret[i] );
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ cleanData: function( elems ) {
+ var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
+ deleteExpando = jQuery.support.deleteExpando;
+
+ for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
+ if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
+ continue;
+ }
+
+ id = elem[ jQuery.expando ];
+
+ if ( id ) {
+ data = cache[ id ] && cache[ id ][ internalKey ];
+
+ if ( data && data.events ) {
+ for ( var type in data.events ) {
+ if ( special[ type ] ) {
+ jQuery.event.remove( elem, type );
+
+ // This is a shortcut to avoid jQuery.event.remove's overhead
+ } else {
+ jQuery.removeEvent( elem, type, data.handle );
+ }
+ }
+
+ // Null the DOM reference to avoid IE6/7/8 leak (#7054)
+ if ( data.handle ) {
+ data.handle.elem = null;
+ }
+ }
+
+ if ( deleteExpando ) {
+ delete elem[ jQuery.expando ];
+
+ } else if ( elem.removeAttribute ) {
+ elem.removeAttribute( jQuery.expando );
+ }
+
+ delete cache[ id ];
+ }
+ }
+ }
+});
+
+function evalScript( i, elem ) {
+ if ( elem.src ) {
+ jQuery.ajax({
+ url: elem.src,
+ async: false,
+ dataType: "script"
+ });
+ } else {
+ jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
+ }
+
+ if ( elem.parentNode ) {
+ elem.parentNode.removeChild( elem );
+ }
+}
+
+
+
+
+var ralpha = /alpha\([^)]*\)/i,
+ ropacity = /opacity=([^)]*)/,
+ rdashAlpha = /-([a-z])/ig,
+ rupper = /([A-Z])/g,
+ rnumpx = /^-?\d+(?:px)?$/i,
+ rnum = /^-?\d/,
+
+ cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+ cssWidth = [ "Left", "Right" ],
+ cssHeight = [ "Top", "Bottom" ],
+ curCSS,
+
+ getComputedStyle,
+ currentStyle,
+
+ fcamelCase = function( all, letter ) {
+ return letter.toUpperCase();
+ };
+
+jQuery.fn.css = function( name, value ) {
+ // Setting 'undefined' is a no-op
+ if ( arguments.length === 2 && value === undefined ) {
+ return this;
+ }
+
+ return jQuery.access( this, name, value, true, function( elem, name, value ) {
+ return value !== undefined ?
+ jQuery.style( elem, name, value ) :
+ jQuery.css( elem, name );
+ });
+};
+
+jQuery.extend({
+ // Add in style property hooks for overriding the default
+ // behavior of getting and setting a style property
+ cssHooks: {
+ opacity: {
+ get: function( elem, computed ) {
+ if ( computed ) {
+ // We should always get a number back from opacity
+ var ret = curCSS( elem, "opacity", "opacity" );
+ return ret === "" ? "1" : ret;
+
+ } else {
+ return elem.style.opacity;
+ }
+ }
+ }
+ },
+
+ // Exclude the following css properties to add px
+ cssNumber: {
+ "zIndex": true,
+ "fontWeight": true,
+ "opacity": true,
+ "zoom": true,
+ "lineHeight": true
+ },
+
+ // Add in properties whose names you wish to fix before
+ // setting or getting the value
+ cssProps: {
+ // normalize float css property
+ "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
+ },
+
+ // Get and set the style property on a DOM Node
+ style: function( elem, name, value, extra ) {
+ // Don't set styles on text and comment nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
+ return;
+ }
+
+ // Make sure that we're working with the right name
+ var ret, origName = jQuery.camelCase( name ),
+ style = elem.style, hooks = jQuery.cssHooks[ origName ];
+
+ name = jQuery.cssProps[ origName ] || origName;
+
+ // Check if we're setting a value
+ if ( value !== undefined ) {
+ // Make sure that NaN and null values aren't set. See: #7116
+ if ( typeof value === "number" && isNaN( value ) || value == null ) {
+ return;
+ }
+
+ // If a number was passed in, add 'px' to the (except for certain CSS properties)
+ if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
+ value += "px";
+ }
+
+ // If a hook was provided, use that value, otherwise just set the specified value
+ if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
+ // Wrapped to prevent IE from throwing errors when 'invalid' values are provided
+ // Fixes bug #5509
+ try {
+ style[ name ] = value;
+ } catch(e) {}
+ }
+
+ } else {
+ // If a hook was provided get the non-computed value from there
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
+ return ret;
+ }
+
+ // Otherwise just get the value from the style object
+ return style[ name ];
+ }
+ },
+
+ css: function( elem, name, extra ) {
+ // Make sure that we're working with the right name
+ var ret, origName = jQuery.camelCase( name ),
+ hooks = jQuery.cssHooks[ origName ];
+
+ name = jQuery.cssProps[ origName ] || origName;
+
+ // If a hook was provided get the computed value from there
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
+ return ret;
+
+ // Otherwise, if a way to get the computed value exists, use that
+ } else if ( curCSS ) {
+ return curCSS( elem, name, origName );
+ }
+ },
+
+ // A method for quickly swapping in/out CSS properties to get correct calculations
+ swap: function( elem, options, callback ) {
+ var old = {};
+
+ // Remember the old values, and insert the new ones
+ for ( var name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ callback.call( elem );
+
+ // Revert the old values
+ for ( name in options ) {
+ elem.style[ name ] = old[ name ];
+ }
+ },
+
+ camelCase: function( string ) {
+ return string.replace( rdashAlpha, fcamelCase );
+ }
+});
+
+// DEPRECATED, Use jQuery.css() instead
+jQuery.curCSS = jQuery.css;
+
+jQuery.each(["height", "width"], function( i, name ) {
+ jQuery.cssHooks[ name ] = {
+ get: function( elem, computed, extra ) {
+ var val;
+
+ if ( computed ) {
+ if ( elem.offsetWidth !== 0 ) {
+ val = getWH( elem, name, extra );
+
+ } else {
+ jQuery.swap( elem, cssShow, function() {
+ val = getWH( elem, name, extra );
+ });
+ }
+
+ if ( val <= 0 ) {
+ val = curCSS( elem, name, name );
+
+ if ( val === "0px" && currentStyle ) {
+ val = currentStyle( elem, name, name );
+ }
+
+ if ( val != null ) {
+ // Should return "auto" instead of 0, use 0 for
+ // temporary backwards-compat
+ return val === "" || val === "auto" ? "0px" : val;
+ }
+ }
+
+ if ( val < 0 || val == null ) {
+ val = elem.style[ name ];
+
+ // Should return "auto" instead of 0, use 0 for
+ // temporary backwards-compat
+ return val === "" || val === "auto" ? "0px" : val;
+ }
+
+ return typeof val === "string" ? val : val + "px";
+ }
+ },
+
+ set: function( elem, value ) {
+ if ( rnumpx.test( value ) ) {
+ // ignore negative width and height values #1599
+ value = parseFloat(value);
+
+ if ( value >= 0 ) {
+ return value + "px";
+ }
+
+ } else {
+ return value;
+ }
+ }
+ };
+});
+
+if ( !jQuery.support.opacity ) {
+ jQuery.cssHooks.opacity = {
+ get: function( elem, computed ) {
+ // IE uses filters for opacity
+ return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
+ (parseFloat(RegExp.$1) / 100) + "" :
+ computed ? "1" : "";
+ },
+
+ set: function( elem, value ) {
+ var style = elem.style;
+
+ // IE has trouble with opacity if it does not have layout
+ // Force it by setting the zoom level
+ style.zoom = 1;
+
+ // Set the alpha filter to set the opacity
+ var opacity = jQuery.isNaN(value) ?
+ "" :
+ "alpha(opacity=" + value * 100 + ")",
+ filter = style.filter || "";
+
+ style.filter = ralpha.test(filter) ?
+ filter.replace(ralpha, opacity) :
+ style.filter + ' ' + opacity;
+ }
+ };
+}
+
+if ( document.defaultView && document.defaultView.getComputedStyle ) {
+ getComputedStyle = function( elem, newName, name ) {
+ var ret, defaultView, computedStyle;
+
+ name = name.replace( rupper, "-$1" ).toLowerCase();
+
+ if ( !(defaultView = elem.ownerDocument.defaultView) ) {
+ return undefined;
+ }
+
+ if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
+ ret = computedStyle.getPropertyValue( name );
+ if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
+ ret = jQuery.style( elem, name );
+ }
+ }
+
+ return ret;
+ };
+}
+
+if ( document.documentElement.currentStyle ) {
+ currentStyle = function( elem, name ) {
+ var left,
+ ret = elem.currentStyle && elem.currentStyle[ name ],
+ rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
+ style = elem.style;
+
+ // From the awesome hack by Dean Edwards
+ // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+ // If we're not dealing with a regular pixel number
+ // but a number that has a weird ending, we need to convert it to pixels
+ if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
+ // Remember the original values
+ left = style.left;
+
+ // Put in the new values to get a computed value out
+ if ( rsLeft ) {
+ elem.runtimeStyle.left = elem.currentStyle.left;
+ }
+ style.left = name === "fontSize" ? "1em" : (ret || 0);
+ ret = style.pixelLeft + "px";
+
+ // Revert the changed values
+ style.left = left;
+ if ( rsLeft ) {
+ elem.runtimeStyle.left = rsLeft;
+ }
+ }
+
+ return ret === "" ? "auto" : ret;
+ };
+}
+
+curCSS = getComputedStyle || currentStyle;
+
+function getWH( elem, name, extra ) {
+ var which = name === "width" ? cssWidth : cssHeight,
+ val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
+
+ if ( extra === "border" ) {
+ return val;
+ }
+
+ jQuery.each( which, function() {
+ if ( !extra ) {
+ val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
+ }
+
+ if ( extra === "margin" ) {
+ val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
+
+ } else {
+ val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
+ }
+ });
+
+ return val;
+}
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+ jQuery.expr.filters.hidden = function( elem ) {
+ var width = elem.offsetWidth,
+ height = elem.offsetHeight;
+
+ return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
+ };
+
+ jQuery.expr.filters.visible = function( elem ) {
+ return !jQuery.expr.filters.hidden( elem );
+ };
+}
+
+
+
+
+var r20 = /%20/g,
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rhash = /#.*$/,
+ rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
+ rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
+ rnoContent = /^(?:GET|HEAD)$/,
+ rprotocol = /^\/\//,
+ rquery = /\?/,
+ rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
+ rselectTextarea = /^(?:select|textarea)/i,
+ rspacesAjax = /\s+/,
+ rts = /([?&])_=[^&]*/,
+ rurl = /^(\w+:)\/\/([^\/?#:]+)(?::(\d+))?/,
+
+ // Keep a copy of the old load method
+ _load = jQuery.fn.load,
+
+ /* Prefilters
+ * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+ * 2) These are called:
+ * - BEFORE asking for a transport
+ * - AFTER param serialization (s.data is a string if s.processData is true)
+ * 3) key is the dataType
+ * 4) the catchall symbol "*" can be used
+ * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+ */
+ prefilters = {},
+
+ /* Transports bindings
+ * 1) key is the dataType
+ * 2) the catchall symbol "*" can be used
+ * 3) selection will start with transport dataType and THEN go to "*" if needed
+ */
+ transports = {};
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+ // dataTypeExpression is optional and defaults to "*"
+ return function( dataTypeExpression, func ) {
+
+ if ( typeof dataTypeExpression !== "string" ) {
+ func = dataTypeExpression;
+ dataTypeExpression = "*";
+ }
+
+ if ( jQuery.isFunction( func ) ) {
+ var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
+ i = 0,
+ length = dataTypes.length,
+ dataType,
+ list,
+ placeBefore;
+
+ // For each dataType in the dataTypeExpression
+ for(; i < length; i++ ) {
+ dataType = dataTypes[ i ];
+ // We control if we're asked to add before
+ // any existing element
+ placeBefore = /^\+/.test( dataType );
+ if ( placeBefore ) {
+ dataType = dataType.substr( 1 ) || "*";
+ }
+ list = structure[ dataType ] = structure[ dataType ] || [];
+ // then we add to the structure accordingly
+ list[ placeBefore ? "unshift" : "push" ]( func );
+ }
+ }
+ };
+}
+
+//Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jXHR,
+ dataType /* internal */, inspected /* internal */ ) {
+
+ dataType = dataType || options.dataTypes[ 0 ];
+ inspected = inspected || {};
+
+ inspected[ dataType ] = true;
+
+ var list = structure[ dataType ],
+ i = 0,
+ length = list ? list.length : 0,
+ executeOnly = ( structure === prefilters ),
+ selection;
+
+ for(; i < length && ( executeOnly || !selection ); i++ ) {
+ selection = list[ i ]( options, originalOptions, jXHR );
+ // If we got redirected to another dataType
+ // we try there if not done already
+ if ( typeof selection === "string" ) {
+ if ( inspected[ selection ] ) {
+ selection = undefined;
+ } else {
+ options.dataTypes.unshift( selection );
+ selection = inspectPrefiltersOrTransports(
+ structure, options, originalOptions, jXHR, selection, inspected );
+ }
+ }
+ }
+ // If we're only executing or nothing was selected
+ // we try the catchall dataType if not done already
+ if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
+ selection = inspectPrefiltersOrTransports(
+ structure, options, originalOptions, jXHR, "*", inspected );
+ }
+ // unnecessary when only executing (prefilters)
+ // but it'll be ignored by the caller in that case
+ return selection;
+}
+
+jQuery.fn.extend({
+ load: function( url, params, callback ) {
+ if ( typeof url !== "string" && _load ) {
+ return _load.apply( this, arguments );
+
+ // Don't do a request if no elements are being requested
+ } else if ( !this.length ) {
+ return this;
+ }
+
+ var off = url.indexOf( " " );
+ if ( off >= 0 ) {
+ var selector = url.slice( off, url.length );
+ url = url.slice( 0, off );
+ }
+
+ // Default to a GET request
+ var type = "GET";
+
+ // If the second parameter was provided
+ if ( params ) {
+ // If it's a function
+ if ( jQuery.isFunction( params ) ) {
+ // We assume that it's the callback
+ callback = params;
+ params = null;
+
+ // Otherwise, build a param string
+ } else if ( typeof params === "object" ) {
+ params = jQuery.param( params, jQuery.ajaxSettings.traditional );
+ type = "POST";
+ }
+ }
+
+ var self = this;
+
+ // Request the remote document
+ jQuery.ajax({
+ url: url,
+ type: type,
+ dataType: "html",
+ data: params,
+ // Complete callback (responseText is used internally)
+ complete: function( jXHR, status, responseText ) {
+ // Store the response as specified by the jXHR object
+ responseText = jXHR.responseText;
+ // If successful, inject the HTML into all the matched elements
+ if ( jXHR.isResolved() ) {
+ // #4825: Get the actual response in case
+ // a dataFilter is present in ajaxSettings
+ jXHR.done(function( r ) {
+ responseText = r;
+ });
+ // See if a selector was specified
+ self.html( selector ?
+ // Create a dummy div to hold the results
+ jQuery("<div>")
+ // inject the contents of the document in, removing the scripts
+ // to avoid any 'Permission Denied' errors in IE
+ .append(responseText.replace(rscript, ""))
+
+ // Locate the specified elements
+ .find(selector) :
+
+ // If not, just inject the full result
+ responseText );
+ }
+
+ if ( callback ) {
+ self.each( callback, [ responseText, status, jXHR ] );
+ }
+ }
+ });
+
+ return this;
+ },
+
+ serialize: function() {
+ return jQuery.param( this.serializeArray() );
+ },
+
+ serializeArray: function() {
+ return this.map(function(){
+ return this.elements ? jQuery.makeArray( this.elements ) : this;
+ })
+ .filter(function(){
+ return this.name && !this.disabled &&
+ ( this.checked || rselectTextarea.test( this.nodeName ) ||
+ rinput.test( this.type ) );
+ })
+ .map(function( i, elem ){
+ var val = jQuery( this ).val();
+
+ return val == null ?
+ null :
+ jQuery.isArray( val ) ?
+ jQuery.map( val, function( val, i ){
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }) :
+ { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }).get();
+ }
+});
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
+ jQuery.fn[ o ] = function( f ){
+ return this.bind( o, f );
+ };
+} );
+
+jQuery.each( [ "get", "post" ], function( i, method ) {
+ jQuery[ method ] = function( url, data, callback, type ) {
+ // shift arguments if data argument was omitted
+ if ( jQuery.isFunction( data ) ) {
+ type = type || callback;
+ callback = data;
+ data = null;
+ }
+
+ return jQuery.ajax({
+ type: method,
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type
+ });
+ };
+} );
+
+jQuery.extend({
+
+ getScript: function( url, callback ) {
+ return jQuery.get( url, null, callback, "script" );
+ },
+
+ getJSON: function( url, data, callback ) {
+ return jQuery.get( url, data, callback, "json" );
+ },
+
+ ajaxSetup: function( settings ) {
+ jQuery.extend( true, jQuery.ajaxSettings, settings );
+ if ( settings.context ) {
+ jQuery.ajaxSettings.context = settings.context;
+ }
+ },
+
+ ajaxSettings: {
+ url: location.href,
+ global: true,
+ type: "GET",
+ contentType: "application/x-www-form-urlencoded",
+ processData: true,
+ async: true,
+ /*
+ timeout: 0,
+ data: null,
+ dataType: null,
+ username: null,
+ password: null,
+ cache: null,
+ traditional: false,
+ headers: {},
+ crossDomain: null,
+ */
+
+ accepts: {
+ xml: "application/xml, text/xml",
+ html: "text/html",
+ text: "text/plain",
+ json: "application/json, text/javascript",
+ "*": "*/*"
+ },
+
+ contents: {
+ xml: /xml/,
+ html: /html/,
+ json: /json/
+ },
+
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText"
+ },
+
+ // List of data converters
+ // 1) key format is "source_type destination_type" (a single space in-between)
+ // 2) the catchall symbol "*" can be used for source_type
+ converters: {
+
+ // Convert anything to text
+ "* text": window.String,
+
+ // Text to html (true = no transformation)
+ "text html": true,
+
+ // Evaluate text as a json expression
+ "text json": jQuery.parseJSON,
+
+ // Parse text as xml
+ "text xml": jQuery.parseXML
+ }
+ },
+
+ ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+ ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+ // Main method
+ ajax: function( url, options ) {
+
+ // If options is not an object,
+ // we simulate pre-1.5 signature
+ if ( typeof options !== "object" ) {
+ options = url;
+ url = undefined;
+ }
+
+ // Force options to be an object
+ options = options || {};
+
+ var // Create the final options object
+ s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
+ // Callbacks contexts
+ // We force the original context if it exists
+ // or take it from jQuery.ajaxSettings otherwise
+ // (plain objects used as context get extended)
+ callbackContext =
+ ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
+ globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
+ // Deferreds
+ deferred = jQuery.Deferred(),
+ completeDeferred = jQuery._Deferred(),
+ // Status-dependent callbacks
+ statusCode = s.statusCode || {},
+ // Headers (they are sent all at once)
+ requestHeaders = {},
+ // Response headers
+ responseHeadersString,
+ responseHeaders,
+ // transport
+ transport,
+ // timeout handle
+ timeoutTimer,
+ // Cross-domain detection vars
+ loc = document.location,
+ protocol = loc.protocol || "http:",
+ parts,
+ // The jXHR state
+ state = 0,
+ // Loop variable
+ i,
+ // Fake xhr
+ jXHR = {
+
+ readyState: 0,
+
+ // Caches the header
+ setRequestHeader: function( name, value ) {
+ if ( state === 0 ) {
+ requestHeaders[ name.toLowerCase() ] = value;
+ }
+ return this;
+ },
+
+ // Raw string
+ getAllResponseHeaders: function() {
+ return state === 2 ? responseHeadersString : null;
+ },
+
+ // Builds headers hashtable if needed
+ getResponseHeader: function( key ) {
+ var match;
+ if ( state === 2 ) {
+ if ( !responseHeaders ) {
+ responseHeaders = {};
+ while( ( match = rheaders.exec( responseHeadersString ) ) ) {
+ responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+ }
+ }
+ match = responseHeaders[ key.toLowerCase() ];
+ }
+ return match || null;
+ },
+
+ // Cancel the request
+ abort: function( statusText ) {
+ statusText = statusText || "abort";
+ if ( transport ) {
+ transport.abort( statusText );
+ }
+ done( 0, statusText );
+ return this;
+ }
+ };
+
+ // Callback for when everything is done
+ // It is defined here because jslint complains if it is declared
+ // at the end of the function (which would be more logical and readable)
+ function done( status, statusText, responses, headers) {
+
+ // Called once
+ if ( state === 2 ) {
+ return;
+ }
+
+ // State is "done" now
+ state = 2;
+
+ // Clear timeout if it exists
+ if ( timeoutTimer ) {
+ clearTimeout( timeoutTimer );
+ }
+
+ // Dereference transport for early garbage collection
+ // (no matter how long the jXHR object will be used)
+ transport = undefined;
+
+ // Cache response headers
+ responseHeadersString = headers || "";
+
+ // Set readyState
+ jXHR.readyState = status ? 4 : 0;
+
+ var isSuccess,
+ success,
+ error,
+ response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
+ lastModified,
+ etag;
+
+ // If successful, handle type chaining
+ if ( status >= 200 && status < 300 || status === 304 ) {
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+
+ if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
+ jQuery.lastModified[ s.url ] = lastModified;
+ }
+ if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
+ jQuery.etag[ s.url ] = etag;
+ }
+ }
+
+ // If not modified
+ if ( status === 304 ) {
+
+ statusText = "notmodified";
+ isSuccess = true;
+
+ // If we have data
+ } else {
+
+ try {
+ success = ajaxConvert( s, response );
+ statusText = "success";
+ isSuccess = true;
+ } catch(e) {
+ // We have a parsererror
+ statusText = "parsererror";
+ error = e;
+ }
+ }
+ } else {
+ // We extract error from statusText
+ // then normalize statusText and status for non-aborts
+ error = statusText;
+ if( status ) {
+ statusText = "error";
+ if ( status < 0 ) {
+ status = 0;
+ }
+ }
+ }
+
+ // Set data for the fake xhr object
+ jXHR.status = status;
+ jXHR.statusText = statusText;
+
+ // Success/Error
+ if ( isSuccess ) {
+ deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
+ } else {
+ deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
+ }
+
+ // Status-dependent callbacks
+ jXHR.statusCode( statusCode );
+ statusCode = undefined;
+
+ if ( s.global ) {
+ globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
+ [ jXHR, s, isSuccess ? success : error ] );
+ }
+
+ // Complete
+ completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
+
+ if ( s.global ) {
+ globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
+ // Handle the global AJAX counter
+ if ( !( --jQuery.active ) ) {
+ jQuery.event.trigger( "ajaxStop" );
+ }
+ }
+ }
+
+ // Attach deferreds
+ deferred.promise( jXHR );
+ jXHR.success = jXHR.done;
+ jXHR.error = jXHR.fail;
+ jXHR.complete = completeDeferred.done;
+
+ // Status-dependent callbacks
+ jXHR.statusCode = function( map ) {
+ if ( map ) {
+ var tmp;
+ if ( state < 2 ) {
+ for( tmp in map ) {
+ statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
+ }
+ } else {
+ tmp = map[ jXHR.status ];
+ jXHR.then( tmp, tmp );
+ }
+ }
+ return this;
+ };
+
+ // Remove hash character (#7531: and string promotion)
+ // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+ // We also use the url parameter if available
+ s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" );
+
+ // Extract dataTypes list
+ s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
+
+ // Determine if a cross-domain request is in order
+ if ( !s.crossDomain ) {
+ parts = rurl.exec( s.url.toLowerCase() );
+ s.crossDomain = !!( parts &&
+ ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname ||
+ ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
+ ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
+ );
+ }
+
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
+ }
+
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jXHR );
+
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
+
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
+
+ // Watch for a new set of requests
+ if ( s.global && jQuery.active++ === 0 ) {
+ jQuery.event.trigger( "ajaxStart" );
+ }
+
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
+
+ // If data is available, append data to url
+ if ( s.data ) {
+ s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
+ }
+
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
+
+ var ts = jQuery.now(),
+ // try replacing _= if it is there
+ ret = s.url.replace( rts, "$1_=" + ts );
+
+ // if nothing was replaced, add timestamp to the end
+ s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
+ }
+ }
+
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ requestHeaders[ "content-type" ] = s.contentType;
+ }
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ s.url ] ) {
+ requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
+ }
+ if ( jQuery.etag[ s.url ] ) {
+ requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
+ }
+ }
+
+ // Set the Accepts header for the server, depending on the dataType
+ requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+ s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
+ s.accepts[ "*" ];
+
+ // Check for headers option
+ for ( i in s.headers ) {
+ requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
+ }
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
+ // Abort if not done already
+ done( 0, "abort" );
+ // Return false
+ jXHR = false;
+
+ } else {
+
+ // Install callbacks on deferreds
+ for ( i in { success: 1, error: 1, complete: 1 } ) {
+ jXHR[ i ]( s[ i ] );
+ }
+
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jXHR );
+
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ // Set state as sending
+ state = jXHR.readyState = 1;
+ // Send global event
+ if ( s.global ) {
+ globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
+ }
+ // Timeout
+ if ( s.async && s.timeout > 0 ) {
+ timeoutTimer = setTimeout( function(){
+ jXHR.abort( "timeout" );
+ }, s.timeout );
+ }
+
+ try {
+ transport.send( requestHeaders, done );
+ } catch (e) {
+ // Propagate exception as error if not done
+ if ( status < 2 ) {
+ done( -1, e );
+ // Simply rethrow otherwise
+ } else {
+ jQuery.error( e );
+ }
+ }
+ }
+ }
+ return jXHR;
+ },
+
+ // Serialize an array of form elements or a set of
+ // key/values into a query string
+ param: function( a, traditional ) {
+ var s = [],
+ add = function( key, value ) {
+ // If value is a function, invoke it and return its value
+ value = jQuery.isFunction( value ) ? value() : value;
+ s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
+ };
+
+ // Set traditional to true for jQuery <= 1.3.2 behavior.
+ if ( traditional === undefined ) {
+ traditional = jQuery.ajaxSettings.traditional;
+ }
+
+ // If an array was passed in, assume that it is an array of form elements.
+ if ( jQuery.isArray( a ) || a.jquery ) {
+ // Serialize the form elements
+ jQuery.each( a, function() {
+ add( this.name, this.value );
+ } );
+
+ } else {
+ // If traditional, encode the "old" way (the way 1.3.2 or older
+ // did it), otherwise encode params recursively.
+ for ( var prefix in a ) {
+ buildParams( prefix, a[ prefix ], traditional, add );
+ }
+ }
+
+ // Return the resulting serialization
+ return s.join( "&" ).replace( r20, "+" );
+ }
+});
+
+function buildParams( prefix, obj, traditional, add ) {
+ if ( jQuery.isArray( obj ) && obj.length ) {
+ // Serialize array item.
+ jQuery.each( obj, function( i, v ) {
+ if ( traditional || rbracket.test( prefix ) ) {
+ // Treat each array item as a scalar.
+ add( prefix, v );
+
+ } else {
+ // If array item is non-scalar (array or object), encode its
+ // numeric index to resolve deserialization ambiguity issues.
+ // Note that rack (as of 1.0.0) can't currently deserialize
+ // nested arrays properly, and attempting to do so may cause
+ // a server error. Possible fixes are to modify rack's
+ // deserialization algorithm or to provide an option or flag
+ // to force array serialization to be shallow.
+ buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
+ }
+ });
+
+ } else if ( !traditional && obj != null && typeof obj === "object" ) {
+ // If we see an array here, it is empty and should be treated as an empty
+ // object
+ if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
+ add( prefix, "" );
+
+ // Serialize object item.
+ } else {
+ jQuery.each( obj, function( k, v ) {
+ buildParams( prefix + "[" + k + "]", v, traditional, add );
+ });
+ }
+
+ } else {
+ // Serialize scalar item.
+ add( prefix, obj );
+ }
+}
+
+// This is still on the jQuery object... for now
+// Want to move this to jQuery.ajax some day
+jQuery.extend({
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ etag: {}
+
+});
+
+/* Handles responses to an ajax request:
+ * - sets all responseXXX fields accordingly
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jXHR, responses ) {
+
+ var contents = s.contents,
+ dataTypes = s.dataTypes,
+ responseFields = s.responseFields,
+ ct,
+ type,
+ finalDataType,
+ firstDataType;
+
+ // Fill responseXXX fields
+ for( type in responseFields ) {
+ if ( type in responses ) {
+ jXHR[ responseFields[type] ] = responses[ type ];
+ }
+ }
+
+ // Remove auto dataType and get content-type in the process
+ while( dataTypes[ 0 ] === "*" ) {
+ dataTypes.shift();
+ if ( ct === undefined ) {
+ ct = jXHR.getResponseHeader( "content-type" );
+ }
+ }
+
+ // Check if we're dealing with a known content-type
+ if ( ct ) {
+ for ( type in contents ) {
+ if ( contents[ type ] && contents[ type ].test( ct ) ) {
+ dataTypes.unshift( type );
+ break;
+ }
+ }
+ }
+
+ // Check to see if we have a response for the expected dataType
+ if ( dataTypes[ 0 ] in responses ) {
+ finalDataType = dataTypes[ 0 ];
+ } else {
+ // Try convertible dataTypes
+ for ( type in responses ) {
+ if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
+ finalDataType = type;
+ break;
+ }
+ if ( !firstDataType ) {
+ firstDataType = type;
+ }
+ }
+ // Or just use first one
+ finalDataType = finalDataType || firstDataType;
+ }
+
+ // If we found a dataType
+ // We add the dataType to the list if needed
+ // and return the corresponding response
+ if ( finalDataType ) {
+ if ( finalDataType !== dataTypes[ 0 ] ) {
+ dataTypes.unshift( finalDataType );
+ }
+ return responses[ finalDataType ];
+ }
+}
+
+// Chain conversions given the request and the original response
+function ajaxConvert( s, response ) {
+
+ // Apply the dataFilter if provided
+ if ( s.dataFilter ) {
+ response = s.dataFilter( response, s.dataType );
+ }
+
+ var dataTypes = s.dataTypes,
+ converters = s.converters,
+ i,
+ length = dataTypes.length,
+ tmp,
+ // Current and previous dataTypes
+ current = dataTypes[ 0 ],
+ prev,
+ // Conversion expression
+ conversion,
+ // Conversion function
+ conv,
+ // Conversion functions (transitive conversion)
+ conv1,
+ conv2;
+
+ // For each dataType in the chain
+ for( i = 1; i < length; i++ ) {
+
+ // Get the dataTypes
+ prev = current;
+ current = dataTypes[ i ];
+
+ // If current is auto dataType, update it to prev
+ if( current === "*" ) {
+ current = prev;
+ // If no auto and dataTypes are actually different
+ } else if ( prev !== "*" && prev !== current ) {
+
+ // Get the converter
+ conversion = prev + " " + current;
+ conv = converters[ conversion ] || converters[ "* " + current ];
+
+ // If there is no direct converter, search transitively
+ if ( !conv ) {
+ conv2 = undefined;
+ for( conv1 in converters ) {
+ tmp = conv1.split( " " );
+ if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
+ conv2 = converters[ tmp[1] + " " + current ];
+ if ( conv2 ) {
+ conv1 = converters[ conv1 ];
+ if ( conv1 === true ) {
+ conv = conv2;
+ } else if ( conv2 === true ) {
+ conv = conv1;
+ }
+ break;
+ }
+ }
+ }
+ }
+ // If we found no converter, dispatch an error
+ if ( !( conv || conv2 ) ) {
+ jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
+ }
+ // If found converter is not an equivalence
+ if ( conv !== true ) {
+ // Convert with 1 or 2 converters accordingly
+ response = conv ? conv( response ) : conv2( conv1(response) );
+ }
+ }
+ }
+ return response;
+}
+
+
+
+
+var jsc = jQuery.now(),
+ jsre = /(\=)\?(&|$)|()\?\?()/i;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+ jsonp: "callback",
+ jsonpCallback: function() {
+ return jQuery.expando + "_" + ( jsc++ );
+ }
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, dataIsString /* internal */ ) {
+
+ dataIsString = ( typeof s.data === "string" );
+
+ if ( s.dataTypes[ 0 ] === "jsonp" ||
+ originalSettings.jsonpCallback ||
+ originalSettings.jsonp != null ||
+ s.jsonp !== false && ( jsre.test( s.url ) ||
+ dataIsString && jsre.test( s.data ) ) ) {
+
+ var responseContainer,
+ jsonpCallback = s.jsonpCallback =
+ jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
+ previous = window[ jsonpCallback ],
+ url = s.url,
+ data = s.data,
+ replace = "$1" + jsonpCallback + "$2";
+
+ if ( s.jsonp !== false ) {
+ url = url.replace( jsre, replace );
+ if ( s.url === url ) {
+ if ( dataIsString ) {
+ data = data.replace( jsre, replace );
+ }
+ if ( s.data === data ) {
+ // Add callback manually
+ url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
+ }
+ }
+ }
+
+ s.url = url;
+ s.data = data;
+
+ window[ jsonpCallback ] = function( response ) {
+ responseContainer = [ response ];
+ };
+
+ s.complete = [ function() {
+
+ // Set callback back to previous value
+ window[ jsonpCallback ] = previous;
+
+ // Call if it was a function and we have a response
+ if ( previous) {
+ if ( responseContainer && jQuery.isFunction( previous ) ) {
+ window[ jsonpCallback ] ( responseContainer[ 0 ] );
+ }
+ } else {
+ // else, more memory leak avoidance
+ try{
+ delete window[ jsonpCallback ];
+ } catch( e ) {}
+ }
+
+ }, s.complete ];
+
+ // Use data converter to retrieve json after script execution
+ s.converters["script json"] = function() {
+ if ( ! responseContainer ) {
+ jQuery.error( jsonpCallback + " was not called" );
+ }
+ return responseContainer[ 0 ];
+ };
+
+ // force json dataType
+ s.dataTypes[ 0 ] = "json";
+
+ // Delegate to script
+ return "script";
+ }
+} );
+
+
+
+
+// Install script dataType
+jQuery.ajaxSetup({
+ accepts: {
+ script: "text/javascript, application/javascript"
+ },
+ contents: {
+ script: /javascript/
+ },
+ converters: {
+ "text script": function( text ) {
+ jQuery.globalEval( text );
+ return text;
+ }
+ }
+});
+
+// Handle cache's special case and global
+jQuery.ajaxPrefilter( "script", function( s ) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ s.global = false;
+ }
+} );
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function(s) {
+
+ // This transport only deals with cross domain requests
+ if ( s.crossDomain ) {
+
+ var script,
+ head = document.getElementsByTagName( "head" )[ 0 ] || document.documentElement;
+
+ return {
+
+ send: function( _, callback ) {
+
+ script = document.createElement( "script" );
+
+ script.async = "async";
+
+ if ( s.scriptCharset ) {
+ script.charset = s.scriptCharset;
+ }
+
+ script.src = s.url;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function( _, isAbort ) {
+
+ if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+
+ // Handle memory leak in IE
+ script.onload = script.onreadystatechange = null;
+
+ // Remove the script
+ if ( head && script.parentNode ) {
+ head.removeChild( script );
+ }
+
+ // Dereference the script
+ script = undefined;
+
+ // Callback if not abort
+ if ( !isAbort ) {
+ callback( 200, "success" );
+ }
+ }
+ };
+ // Use insertBefore instead of appendChild to circumvent an IE6 bug.
+ // This arises when a base node is used (#2709 and #4378).
+ head.insertBefore( script, head.firstChild );
+ },
+
+ abort: function() {
+ if ( script ) {
+ script.onload( 0, 1 );
+ }
+ }
+ };
+ }
+} );
+
+
+
+
+var // Next active xhr id
+ xhrId = jQuery.now(),
+
+ // active xhrs
+ xhrs = {},
+
+ // #5280: see below
+ xhrUnloadAbortInstalled,
+
+ // XHR used to determine supports properties
+ testXHR;
+
+// Create the request object
+// (This is still attached to ajaxSettings for backward compatibility)
+jQuery.ajaxSettings.xhr = window.ActiveXObject ?
+ /* Microsoft failed to properly
+ * implement the XMLHttpRequest in IE7 (can't request local files),
+ * so we use the ActiveXObject when it is available
+ * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
+ * we need a fallback.
+ */
+ function() {
+ if ( window.location.protocol !== "file:" ) {
+ try {
+ return new window.XMLHttpRequest();
+ } catch( xhrError ) {}
+ }
+
+ try {
+ return new window.ActiveXObject("Microsoft.XMLHTTP");
+ } catch( activeError ) {}
+ } :
+ // For all other browsers, use the standard XMLHttpRequest object
+ function() {
+ return new window.XMLHttpRequest();
+ };
+
+// Test if we can create an xhr object
+try {
+ testXHR = jQuery.ajaxSettings.xhr();
+} catch( xhrCreationException ) {}
+
+//Does this browser support XHR requests?
+jQuery.support.ajax = !!testXHR;
+
+// Does this browser support crossDomain XHR requests
+jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
+
+// No need for the temporary xhr anymore
+testXHR = undefined;
+
+// Create transport if the browser can provide an xhr
+if ( jQuery.support.ajax ) {
+
+ jQuery.ajaxTransport(function( s ) {
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( !s.crossDomain || jQuery.support.cors ) {
+
+ var callback;
+
+ return {
+ send: function( headers, complete ) {
+
+ // #5280: we need to abort on unload or IE will keep connections alive
+ if ( !xhrUnloadAbortInstalled ) {
+
+ xhrUnloadAbortInstalled = 1;
+
+ jQuery(window).bind( "unload", function() {
+
+ // Abort all pending requests
+ jQuery.each( xhrs, function( _, xhr ) {
+ if ( xhr.onreadystatechange ) {
+ xhr.onreadystatechange( 1 );
+ }
+ } );
+
+ } );
+ }
+
+ // Get a new xhr
+ var xhr = s.xhr(),
+ handle;
+
+ // Open the socket
+ // Passing null username, generates a login popup on Opera (#2865)
+ if ( s.username ) {
+ xhr.open( s.type, s.url, s.async, s.username, s.password );
+ } else {
+ xhr.open( s.type, s.url, s.async );
+ }
+
+ // Requested-With header
+ // Not set for crossDomain requests with no content
+ // (see why at http://trac.dojotoolkit.org/ticket/9486)
+ // Won't change header if already provided
+ if ( !( s.crossDomain && !s.hasContent ) && !headers["x-requested-with"] ) {
+ headers[ "x-requested-with" ] = "XMLHttpRequest";
+ }
+
+ // Need an extra try/catch for cross domain requests in Firefox 3
+ try {
+ jQuery.each( headers, function( key, value ) {
+ xhr.setRequestHeader( key, value );
+ } );
+ } catch( _ ) {}
+
+ // Do send the request
+ // This may raise an exception which is actually
+ // handled in jQuery.ajax (so no try/catch here)
+ xhr.send( ( s.hasContent && s.data ) || null );
+
+ // Listener
+ callback = function( _, isAbort ) {
+
+ // Was never called and is aborted or complete
+ if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
+
+ // Only called once
+ callback = 0;
+
+ // Do not keep as active anymore
+ if ( handle ) {
+ xhr.onreadystatechange = jQuery.noop;
+ delete xhrs[ handle ];
+ }
+
+ // If it's an abort
+ if ( isAbort ) {
+ // Abort it manually if needed
+ if ( xhr.readyState !== 4 ) {
+ xhr.abort();
+ }
+ } else {
+ // Get info
+ var status = xhr.status,
+ statusText,
+ responseHeaders = xhr.getAllResponseHeaders(),
+ responses = {},
+ xml = xhr.responseXML;
+
+ // Construct response list
+ if ( xml && xml.documentElement /* #4958 */ ) {
+ responses.xml = xml;
+ }
+ responses.text = xhr.responseText;
+
+ // Firefox throws an exception when accessing
+ // statusText for faulty cross-domain requests
+ try {
+ statusText = xhr.statusText;
+ } catch( e ) {
+ // We normalize with Webkit giving an empty statusText
+ statusText = "";
+ }
+
+ // Filter status for non standard behaviours
+ status =
+ // Opera returns 0 when it should be 304
+ // Webkit returns 0 for failing cross-domain no matter the real status
+ status === 0 ?
+ (
+ // Webkit, Firefox: filter out faulty cross-domain requests
+ !s.crossDomain || statusText ?
+ (
+ // Opera: filter out real aborts #6060
+ responseHeaders ?
+ 304 :
+ 0
+ ) :
+ // We assume 302 but could be anything cross-domain related
+ 302
+ ) :
+ (
+ // IE sometimes returns 1223 when it should be 204 (see #1450)
+ status == 1223 ?
+ 204 :
+ status
+ );
+
+ // Call complete
+ complete( status, statusText, responses, responseHeaders );
+ }
+ }
+ };
+
+ // if we're in sync mode or it's in cache
+ // and has been retrieved directly (IE6 & IE7)
+ // we need to manually fire the callback
+ if ( !s.async || xhr.readyState === 4 ) {
+ callback();
+ } else {
+ // Add to list of active xhrs
+ handle = xhrId++;
+ xhrs[ handle ] = xhr;
+ xhr.onreadystatechange = callback;
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback(0,1);
+ }
+ }
+ };
+ }
+ });
+}
+
+
+
+
+var elemdisplay = {},
+ rfxtypes = /^(?:toggle|show|hide)$/,
+ rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
+ timerId,
+ fxAttrs = [
+ // height animations
+ [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
+ // width animations
+ [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
+ // opacity animations
+ [ "opacity" ]
+ ];
+
+jQuery.fn.extend({
+ show: function( speed, easing, callback ) {
+ var elem, display;
+
+ if ( speed || speed === 0 ) {
+ return this.animate( genFx("show", 3), speed, easing, callback);
+
+ } else {
+ for ( var i = 0, j = this.length; i < j; i++ ) {
+ elem = this[i];
+ display = elem.style.display;
+
+ // Reset the inline display of this element to learn if it is
+ // being hidden by cascaded rules or not
+ if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
+ display = elem.style.display = "";
+ }
+
+ // Set elements which have been overridden with display: none
+ // in a stylesheet to whatever the default browser style is
+ // for such an element
+ if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
+ jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
+ }
+ }
+
+ // Set the display of most of the elements in a second loop
+ // to avoid the constant reflow
+ for ( i = 0; i < j; i++ ) {
+ elem = this[i];
+ display = elem.style.display;
+
+ if ( display === "" || display === "none" ) {
+ elem.style.display = jQuery._data(elem, "olddisplay") || "";
+ }
+ }
+
+ return this;
+ }
+ },
+
+ hide: function( speed, easing, callback ) {
+ if ( speed || speed === 0 ) {
+ return this.animate( genFx("hide", 3), speed, easing, callback);
+
+ } else {
+ for ( var i = 0, j = this.length; i < j; i++ ) {
+ var display = jQuery.css( this[i], "display" );
+
+ if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
+ jQuery._data( this[i], "olddisplay", display );
+ }
+ }
+
+ // Set the display of the elements in a second loop
+ // to avoid the constant reflow
+ for ( i = 0; i < j; i++ ) {
+ this[i].style.display = "none";
+ }
+
+ return this;
+ }
+ },
+
+ // Save the old toggle function
+ _toggle: jQuery.fn.toggle,
+
+ toggle: function( fn, fn2, callback ) {
+ var bool = typeof fn === "boolean";
+
+ if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
+ this._toggle.apply( this, arguments );
+
+ } else if ( fn == null || bool ) {
+ this.each(function() {
+ var state = bool ? fn : jQuery(this).is(":hidden");
+ jQuery(this)[ state ? "show" : "hide" ]();
+ });
+
+ } else {
+ this.animate(genFx("toggle", 3), fn, fn2, callback);
+ }
+
+ return this;
+ },
+
+ fadeTo: function( speed, to, easing, callback ) {
+ return this.filter(":hidden").css("opacity", 0).show().end()
+ .animate({opacity: to}, speed, easing, callback);
+ },
+
+ animate: function( prop, speed, easing, callback ) {
+ var optall = jQuery.speed(speed, easing, callback);
+
+ if ( jQuery.isEmptyObject( prop ) ) {
+ return this.each( optall.complete );
+ }
+
+ return this[ optall.queue === false ? "each" : "queue" ](function() {
+ // XXX 'this' does not always have a nodeName when running the
+ // test suite
+
+ var opt = jQuery.extend({}, optall), p,
+ isElement = this.nodeType === 1,
+ hidden = isElement && jQuery(this).is(":hidden"),
+ self = this;
+
+ for ( p in prop ) {
+ var name = jQuery.camelCase( p );
+
+ if ( p !== name ) {
+ prop[ name ] = prop[ p ];
+ delete prop[ p ];
+ p = name;
+ }
+
+ if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
+ return opt.complete.call(this);
+ }
+
+ if ( isElement && ( p === "height" || p === "width" ) ) {
+ // Make sure that nothing sneaks out
+ // Record all 3 overflow attributes because IE does not
+ // change the overflow attribute when overflowX and
+ // overflowY are set to the same value
+ opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
+
+ // Set display property to inline-block for height/width
+ // animations on inline elements that are having width/height
+ // animated
+ if ( jQuery.css( this, "display" ) === "inline" &&
+ jQuery.css( this, "float" ) === "none" ) {
+ if ( !jQuery.support.inlineBlockNeedsLayout ) {
+ this.style.display = "inline-block";
+
+ } else {
+ var display = defaultDisplay(this.nodeName);
+
+ // inline-level elements accept inline-block;
+ // block-level elements need to be inline with layout
+ if ( display === "inline" ) {
+ this.style.display = "inline-block";
+
+ } else {
+ this.style.display = "inline";
+ this.style.zoom = 1;
+ }
+ }
+ }
+ }
+
+ if ( jQuery.isArray( prop[p] ) ) {
+ // Create (if needed) and add to specialEasing
+ (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
+ prop[p] = prop[p][0];
+ }
+ }
+
+ if ( opt.overflow != null ) {
+ this.style.overflow = "hidden";
+ }
+
+ opt.curAnim = jQuery.extend({}, prop);
+
+ jQuery.each( prop, function( name, val ) {
+ var e = new jQuery.fx( self, opt, name );
+
+ if ( rfxtypes.test(val) ) {
+ e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
+
+ } else {
+ var parts = rfxnum.exec(val),
+ start = e.cur() || 0;
+
+ if ( parts ) {
+ var end = parseFloat( parts[2] ),
+ unit = parts[3] || "px";
+
+ // We need to compute starting value
+ if ( unit !== "px" ) {
+ jQuery.style( self, name, (end || 1) + unit);
+ start = ((end || 1) / e.cur()) * start;
+ jQuery.style( self, name, start + unit);
+ }
+
+ // If a +=/-= token was provided, we're doing a relative animation
+ if ( parts[1] ) {
+ end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
+ }
+
+ e.custom( start, end, unit );
+
+ } else {
+ e.custom( start, val, "" );
+ }
+ }
+ });
+
+ // For JS strict compliance
+ return true;
+ });
+ },
+
+ stop: function( clearQueue, gotoEnd ) {
+ var timers = jQuery.timers;
+
+ if ( clearQueue ) {
+ this.queue([]);
+ }
+
+ this.each(function() {
+ // go in reverse order so anything added to the queue during the loop is ignored
+ for ( var i = timers.length - 1; i >= 0; i-- ) {
+ if ( timers[i].elem === this ) {
+ if (gotoEnd) {
+ // force the next step to be the last
+ timers[i](true);
+ }
+
+ timers.splice(i, 1);
+ }
+ }
+ });
+
+ // start the next in the queue if the last step wasn't forced
+ if ( !gotoEnd ) {
+ this.dequeue();
+ }
+
+ return this;
+ }
+
+});
+
+function genFx( type, num ) {
+ var obj = {};
+
+ jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
+ obj[ this ] = type;
+ });
+
+ return obj;
+}
+
+// Generate shortcuts for custom animations
+jQuery.each({
+ slideDown: genFx("show", 1),
+ slideUp: genFx("hide", 1),
+ slideToggle: genFx("toggle", 1),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" },
+ fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return this.animate( props, speed, easing, callback );
+ };
+});
+
+jQuery.extend({
+ speed: function( speed, easing, fn ) {
+ var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
+ };
+
+ opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+ opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
+
+ // Queueing
+ opt.old = opt.complete;
+ opt.complete = function() {
+ if ( opt.queue !== false ) {
+ jQuery(this).dequeue();
+ }
+ if ( jQuery.isFunction( opt.old ) ) {
+ opt.old.call( this );
+ }
+ };
+
+ return opt;
+ },
+
+ easing: {
+ linear: function( p, n, firstNum, diff ) {
+ return firstNum + diff * p;
+ },
+ swing: function( p, n, firstNum, diff ) {
+ return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+ }
+ },
+
+ timers: [],
+
+ fx: function( elem, options, prop ) {
+ this.options = options;
+ this.elem = elem;
+ this.prop = prop;
+
+ if ( !options.orig ) {
+ options.orig = {};
+ }
+ }
+
+});
+
+jQuery.fx.prototype = {
+ // Simple function for setting a style value
+ update: function() {
+ if ( this.options.step ) {
+ this.options.step.call( this.elem, this.now, this );
+ }
+
+ (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
+ },
+
+ // Get the current size
+ cur: function() {
+ if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
+ return this.elem[ this.prop ];
+ }
+
+ var r = parseFloat( jQuery.css( this.elem, this.prop ) );
+ return r || 0;
+ },
+
+ // Start an animation from one number to another
+ custom: function( from, to, unit ) {
+ var self = this,
+ fx = jQuery.fx;
+
+ this.startTime = jQuery.now();
+ this.start = from;
+ this.end = to;
+ this.unit = unit || this.unit || "px";
+ this.now = this.start;
+ this.pos = this.state = 0;
+
+ function t( gotoEnd ) {
+ return self.step(gotoEnd);
+ }
+
+ t.elem = this.elem;
+
+ if ( t() && jQuery.timers.push(t) && !timerId ) {
+ timerId = setInterval(fx.tick, fx.interval);
+ }
+ },
+
+ // Simple 'show' function
+ show: function() {
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
+ this.options.show = true;
+
+ // Begin the animation
+ // Make sure that we start at a small width/height to avoid any
+ // flash of content
+ this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
+
+ // Start by showing the element
+ jQuery( this.elem ).show();
+ },
+
+ // Simple 'hide' function
+ hide: function() {
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
+ this.options.hide = true;
+
+ // Begin the animation
+ this.custom(this.cur(), 0);
+ },
+
+ // Each step of an animation
+ step: function( gotoEnd ) {
+ var t = jQuery.now(), done = true;
+
+ if ( gotoEnd || t >= this.options.duration + this.startTime ) {
+ this.now = this.end;
+ this.pos = this.state = 1;
+ this.update();
+
+ this.options.curAnim[ this.prop ] = true;
+
+ for ( var i in this.options.curAnim ) {
+ if ( this.options.curAnim[i] !== true ) {
+ done = false;
+ }
+ }
+
+ if ( done ) {
+ // Reset the overflow
+ if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
+ var elem = this.elem,
+ options = this.options;
+
+ jQuery.each( [ "", "X", "Y" ], function (index, value) {
+ elem.style[ "overflow" + value ] = options.overflow[index];
+ } );
+ }
+
+ // Hide the element if the "hide" operation was done
+ if ( this.options.hide ) {
+ jQuery(this.elem).hide();
+ }
+
+ // Reset the properties, if the item has been hidden or shown
+ if ( this.options.hide || this.options.show ) {
+ for ( var p in this.options.curAnim ) {
+ jQuery.style( this.elem, p, this.options.orig[p] );
+ }
+ }
+
+ // Execute the complete function
+ this.options.complete.call( this.elem );
+ }
+
+ return false;
+
+ } else {
+ var n = t - this.startTime;
+ this.state = n / this.options.duration;
+
+ // Perform the easing function, defaults to swing
+ var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
+ var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
+ this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
+ this.now = this.start + ((this.end - this.start) * this.pos);
+
+ // Perform the next step of the animation
+ this.update();
+ }
+
+ return true;
+ }
+};
+
+jQuery.extend( jQuery.fx, {
+ tick: function() {
+ var timers = jQuery.timers;
+
+ for ( var i = 0; i < timers.length; i++ ) {
+ if ( !timers[i]() ) {
+ timers.splice(i--, 1);
+ }
+ }
+
+ if ( !timers.length ) {
+ jQuery.fx.stop();
+ }
+ },
+
+ interval: 13,
+
+ stop: function() {
+ clearInterval( timerId );
+ timerId = null;
+ },
+
+ speeds: {
+ slow: 600,
+ fast: 200,
+ // Default speed
+ _default: 400
+ },
+
+ step: {
+ opacity: function( fx ) {
+ jQuery.style( fx.elem, "opacity", fx.now );
+ },
+
+ _default: function( fx ) {
+ if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
+ fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
+ } else {
+ fx.elem[ fx.prop ] = fx.now;
+ }
+ }
+ }
+});
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+ jQuery.expr.filters.animated = function( elem ) {
+ return jQuery.grep(jQuery.timers, function( fn ) {
+ return elem === fn.elem;
+ }).length;
+ };
+}
+
+function defaultDisplay( nodeName ) {
+ if ( !elemdisplay[ nodeName ] ) {
+ var elem = jQuery("<" + nodeName + ">").appendTo("body"),
+ display = elem.css("display");
+
+ elem.remove();
+
+ if ( display === "none" || display === "" ) {
+ display = "block";
+ }
+
+ elemdisplay[ nodeName ] = display;
+ }
+
+ return elemdisplay[ nodeName ];
+}
+
+
+
+
+var rtable = /^t(?:able|d|h)$/i,
+ rroot = /^(?:body|html)$/i;
+
+if ( "getBoundingClientRect" in document.documentElement ) {
+ jQuery.fn.offset = function( options ) {
+ var elem = this[0], box;
+
+ if ( options ) {
+ return this.each(function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ });
+ }
+
+ if ( !elem || !elem.ownerDocument ) {
+ return null;
+ }
+
+ if ( elem === elem.ownerDocument.body ) {
+ return jQuery.offset.bodyOffset( elem );
+ }
+
+ try {
+ box = elem.getBoundingClientRect();
+ } catch(e) {}
+
+ var doc = elem.ownerDocument,
+ docElem = doc.documentElement;
+
+ // Make sure we're not dealing with a disconnected DOM node
+ if ( !box || !jQuery.contains( docElem, elem ) ) {
+ return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
+ }
+
+ var body = doc.body,
+ win = getWindow(doc),
+ clientTop = docElem.clientTop || body.clientTop || 0,
+ clientLeft = docElem.clientLeft || body.clientLeft || 0,
+ scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
+ scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
+ top = box.top + scrollTop - clientTop,
+ left = box.left + scrollLeft - clientLeft;
+
+ return { top: top, left: left };
+ };
+
+} else {
+ jQuery.fn.offset = function( options ) {
+ var elem = this[0];
+
+ if ( options ) {
+ return this.each(function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ });
+ }
+
+ if ( !elem || !elem.ownerDocument ) {
+ return null;
+ }
+
+ if ( elem === elem.ownerDocument.body ) {
+ return jQuery.offset.bodyOffset( elem );
+ }
+
+ jQuery.offset.initialize();
+
+ var computedStyle,
+ offsetParent = elem.offsetParent,
+ prevOffsetParent = elem,
+ doc = elem.ownerDocument,
+ docElem = doc.documentElement,
+ body = doc.body,
+ defaultView = doc.defaultView,
+ prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
+ top = elem.offsetTop,
+ left = elem.offsetLeft;
+
+ while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
+ if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
+ break;
+ }
+
+ computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
+ top -= elem.scrollTop;
+ left -= elem.scrollLeft;
+
+ if ( elem === offsetParent ) {
+ top += elem.offsetTop;
+ left += elem.offsetLeft;
+
+ if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
+ top += parseFloat( computedStyle.borderTopWidth ) || 0;
+ left += parseFloat( computedStyle.borderLeftWidth ) || 0;
+ }
+
+ prevOffsetParent = offsetParent;
+ offsetParent = elem.offsetParent;
+ }
+
+ if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
+ top += parseFloat( computedStyle.borderTopWidth ) || 0;
+ left += parseFloat( computedStyle.borderLeftWidth ) || 0;
+ }
+
+ prevComputedStyle = computedStyle;
+ }
+
+ if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
+ top += body.offsetTop;
+ left += body.offsetLeft;
+ }
+
+ if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
+ top += Math.max( docElem.scrollTop, body.scrollTop );
+ left += Math.max( docElem.scrollLeft, body.scrollLeft );
+ }
+
+ return { top: top, left: left };
+ };
+}
+
+jQuery.offset = {
+ initialize: function() {
+ var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
+ html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
+
+ jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
+
+ container.innerHTML = html;
+ body.insertBefore( container, body.firstChild );
+ innerDiv = container.firstChild;
+ checkDiv = innerDiv.firstChild;
+ td = innerDiv.nextSibling.firstChild.firstChild;
+
+ this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
+ this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
+
+ checkDiv.style.position = "fixed";
+ checkDiv.style.top = "20px";
+
+ // safari subtracts parent border width here which is 5px
+ this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
+ checkDiv.style.position = checkDiv.style.top = "";
+
+ innerDiv.style.overflow = "hidden";
+ innerDiv.style.position = "relative";
+
+ this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
+
+ this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
+
+ body.removeChild( container );
+ body = container = innerDiv = checkDiv = table = td = null;
+ jQuery.offset.initialize = jQuery.noop;
+ },
+
+ bodyOffset: function( body ) {
+ var top = body.offsetTop,
+ left = body.offsetLeft;
+
+ jQuery.offset.initialize();
+
+ if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
+ top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
+ left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
+ }
+
+ return { top: top, left: left };
+ },
+
+ setOffset: function( elem, options, i ) {
+ var position = jQuery.css( elem, "position" );
+
+ // set position first, in-case top/left are set even on static elem
+ if ( position === "static" ) {
+ elem.style.position = "relative";
+ }
+
+ var curElem = jQuery( elem ),
+ curOffset = curElem.offset(),
+ curCSSTop = jQuery.css( elem, "top" ),
+ curCSSLeft = jQuery.css( elem, "left" ),
+ calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1),
+ props = {}, curPosition = {}, curTop, curLeft;
+
+ // need to be able to calculate position if either top or left is auto and position is absolute
+ if ( calculatePosition ) {
+ curPosition = curElem.position();
+ }
+
+ curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0;
+ curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0;
+
+ if ( jQuery.isFunction( options ) ) {
+ options = options.call( elem, i, curOffset );
+ }
+
+ if (options.top != null) {
+ props.top = (options.top - curOffset.top) + curTop;
+ }
+ if (options.left != null) {
+ props.left = (options.left - curOffset.left) + curLeft;
+ }
+
+ if ( "using" in options ) {
+ options.using.call( elem, props );
+ } else {
+ curElem.css( props );
+ }
+ }
+};
+
+
+jQuery.fn.extend({
+ position: function() {
+ if ( !this[0] ) {
+ return null;
+ }
+
+ var elem = this[0],
+
+ // Get *real* offsetParent
+ offsetParent = this.offsetParent(),
+
+ // Get correct offsets
+ offset = this.offset(),
+ parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+ // Subtract element margins
+ // note: when an element has margin: auto the offsetLeft and marginLeft
+ // are the same in Safari causing offset.left to incorrectly be 0
+ offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
+ offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
+
+ // Add offsetParent borders
+ parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
+ parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
+
+ // Subtract the two offsets
+ return {
+ top: offset.top - parentOffset.top,
+ left: offset.left - parentOffset.left
+ };
+ },
+
+ offsetParent: function() {
+ return this.map(function() {
+ var offsetParent = this.offsetParent || document.body;
+ while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+ return offsetParent;
+ });
+ }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( ["Left", "Top"], function( i, name ) {
+ var method = "scroll" + name;
+
+ jQuery.fn[ method ] = function(val) {
+ var elem = this[0], win;
+
+ if ( !elem ) {
+ return null;
+ }
+
+ if ( val !== undefined ) {
+ // Set the scroll offset
+ return this.each(function() {
+ win = getWindow( this );
+
+ if ( win ) {
+ win.scrollTo(
+ !i ? val : jQuery(win).scrollLeft(),
+ i ? val : jQuery(win).scrollTop()
+ );
+
+ } else {
+ this[ method ] = val;
+ }
+ });
+ } else {
+ win = getWindow( elem );
+
+ // Return the scroll offset
+ return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
+ jQuery.support.boxModel && win.document.documentElement[ method ] ||
+ win.document.body[ method ] :
+ elem[ method ];
+ }
+ };
+});
+
+function getWindow( elem ) {
+ return jQuery.isWindow( elem ) ?
+ elem :
+ elem.nodeType === 9 ?
+ elem.defaultView || elem.parentWindow :
+ false;
+}
+
+
+
+
+// Create innerHeight, innerWidth, outerHeight and outerWidth methods
+jQuery.each([ "Height", "Width" ], function( i, name ) {
+
+ var type = name.toLowerCase();
+
+ // innerHeight and innerWidth
+ jQuery.fn["inner" + name] = function() {
+ return this[0] ?
+ parseFloat( jQuery.css( this[0], type, "padding" ) ) :
+ null;
+ };
+
+ // outerHeight and outerWidth
+ jQuery.fn["outer" + name] = function( margin ) {
+ return this[0] ?
+ parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
+ null;
+ };
+
+ jQuery.fn[ type ] = function( size ) {
+ // Get window width or height
+ var elem = this[0];
+ if ( !elem ) {
+ return size == null ? null : this;
+ }
+
+ if ( jQuery.isFunction( size ) ) {
+ return this.each(function( i ) {
+ var self = jQuery( this );
+ self[ type ]( size.call( this, i, self[ type ]() ) );
+ });
+ }
+
+ if ( jQuery.isWindow( elem ) ) {
+ // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+ // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
+ var docElemProp = elem.document.documentElement[ "client" + name ];
+ return elem.document.compatMode === "CSS1Compat" && docElemProp ||
+ elem.document.body[ "client" + name ] || docElemProp;
+
+ // Get document width or height
+ } else if ( elem.nodeType === 9 ) {
+ // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+ return Math.max(
+ elem.documentElement["client" + name],
+ elem.body["scroll" + name], elem.documentElement["scroll" + name],
+ elem.body["offset" + name], elem.documentElement["offset" + name]
+ );
+
+ // Get or set width or height on the element
+ } else if ( size === undefined ) {
+ var orig = jQuery.css( elem, type ),
+ ret = parseFloat( orig );
+
+ return jQuery.isNaN( ret ) ? orig : ret;
+
+ // Set the width or height on the element (default to pixels if value is unitless)
+ } else {
+ return this.css( type, typeof size === "string" ? size : size + "px" );
+ }
+ };
+
+});
+
+
+})(window);
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
new file mode 100644
index 0000000000..4dcb3779a2
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
@@ -0,0 +1,148 @@
+/**
+ * Unobtrusive scripting adapter for jQuery
+ *
+ * Requires jQuery 1.4.3 or later.
+ * https://github.com/rails/jquery-ujs
+ */
+
+(function($) {
+ // Triggers an event on an element and returns the event result
+ function fire(obj, name, data) {
+ var event = new $.Event(name);
+ obj.trigger(event, data);
+ return event.result !== false;
+ }
+
+ // Submits "remote" forms and links with ajax
+ function handleRemote(element) {
+ var method, url, data,
+ dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
+
+ if (element.is('form')) {
+ method = element.attr('method');
+ url = element.attr('action');
+ data = element.serializeArray();
+ // memoized value from clicked submit button
+ var button = element.data('ujs:submit-button');
+ if (button) {
+ data.push(button);
+ element.data('ujs:submit-button', null);
+ }
+ } else {
+ method = element.attr('data-method');
+ url = element.attr('href');
+ data = null;
+ }
+
+ $.ajax({
+ url: url, type: method || 'GET', data: data, dataType: dataType,
+ // stopping the "ajax:beforeSend" event will cancel the ajax request
+ beforeSend: function(xhr, settings) {
+ if (settings.dataType === undefined) {
+ xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
+ }
+ return fire(element, 'ajax:beforeSend', [xhr, settings]);
+ },
+ success: function(data, status, xhr) {
+ element.trigger('ajax:success', [data, status, xhr]);
+ },
+ complete: function(xhr, status) {
+ element.trigger('ajax:complete', [xhr, status]);
+ },
+ error: function(xhr, status, error) {
+ element.trigger('ajax:error', [xhr, status, error]);
+ }
+ });
+ }
+
+ // Handles "data-method" on links such as:
+ // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
+ function handleMethod(link) {
+ var href = link.attr('href'),
+ method = link.attr('data-method'),
+ csrf_token = $('meta[name=csrf-token]').attr('content'),
+ csrf_param = $('meta[name=csrf-param]').attr('content'),
+ form = $('<form method="post" action="' + href + '"></form>'),
+ metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';
+
+ if (csrf_param !== undefined && csrf_token !== undefined) {
+ metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
+ }
+
+ form.hide().append(metadata_input).appendTo('body');
+ form.submit();
+ }
+
+ function disableFormElements(form) {
+ form.find('input[data-disable-with]').each(function() {
+ var input = $(this);
+ input.data('ujs:enable-with', input.val())
+ .val(input.attr('data-disable-with'))
+ .attr('disabled', 'disabled');
+ });
+ }
+
+ function enableFormElements(form) {
+ form.find('input[data-disable-with]').each(function() {
+ var input = $(this);
+ input.val(input.data('ujs:enable-with')).removeAttr('disabled');
+ });
+ }
+
+ function allowAction(element) {
+ var message = element.attr('data-confirm');
+ return !message || (fire(element, 'confirm') && confirm(message));
+ }
+
+ function requiredValuesMissing(form) {
+ var missing = false;
+ form.find('input[name][required]').each(function() {
+ if (!$(this).val()) missing = true;
+ });
+ return missing;
+ }
+
+ $('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
+ var link = $(this);
+ if (!allowAction(link)) return false;
+
+ if (link.attr('data-remote') != undefined) {
+ handleRemote(link);
+ return false;
+ } else if (link.attr('data-method')) {
+ handleMethod(link);
+ return false;
+ }
+ });
+
+ $('form').live('submit.rails', function(e) {
+ var form = $(this), remote = form.attr('data-remote') != undefined;
+ if (!allowAction(form)) return false;
+
+ // skip other logic when required values are missing
+ if (requiredValuesMissing(form)) return !remote;
+
+ if (remote) {
+ handleRemote(form);
+ return false;
+ } else {
+ disableFormElements(form);
+ }
+ });
+
+ $('form input[type=submit], form button[type=submit], form button:not([type])').live('click.rails', function() {
+ var button = $(this);
+ if (!allowAction(button)) return false;
+ // register the pressed submit button
+ var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null;
+ button.closest('form').data('ujs:submit-button', data);
+ });
+
+ $('form').live('ajax:beforeSend.rails', function(event) {
+ if (this == event.target) disableFormElements($(this));
+ });
+
+ $('form').live('ajax:complete.rails', function(event) {
+ if (this == event.target) enableFormElements($(this));
+ });
+})( jQuery );
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js
index 06249a6ae3..474b2231bb 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js
@@ -1,4 +1,4 @@
-/* Prototype JavaScript framework, version 1.7_rc2
+/* Prototype JavaScript framework, version 1.7
* (c) 2005-2010 Sam Stephenson
*
* Prototype is freely distributable under the terms of an MIT-style license.
@@ -8,7 +8,7 @@
var Prototype = {
- Version: '1.7_rc2',
+ Version: '1.7',
Browser: (function(){
var ua = navigator.userAgent;
@@ -166,10 +166,12 @@ var Class = (function() {
NUMBER_TYPE = 'Number',
STRING_TYPE = 'String',
OBJECT_TYPE = 'Object',
+ FUNCTION_CLASS = '[object Function]',
BOOLEAN_CLASS = '[object Boolean]',
NUMBER_CLASS = '[object Number]',
STRING_CLASS = '[object String]',
ARRAY_CLASS = '[object Array]',
+ DATE_CLASS = '[object Date]',
NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON &&
typeof JSON.stringify === 'function' &&
JSON.stringify(0) === '0' &&
@@ -322,7 +324,7 @@ var Class = (function() {
}
function isFunction(object) {
- return typeof object === "function";
+ return _toString.call(object) === FUNCTION_CLASS;
}
function isString(object) {
@@ -333,6 +335,10 @@ var Class = (function() {
return _toString.call(object) === NUMBER_CLASS;
}
+ function isDate(object) {
+ return _toString.call(object) === DATE_CLASS;
+ }
+
function isUndefined(object) {
return typeof object === "undefined";
}
@@ -352,6 +358,7 @@ var Class = (function() {
isFunction: isFunction,
isString: isString,
isNumber: isNumber,
+ isDate: isDate,
isUndefined: isUndefined
});
})();
@@ -1079,9 +1086,10 @@ Array.from = $A;
slice = arrayProto.slice,
_each = arrayProto.forEach; // use native browser JS 1.6 implementation if available
- function each(iterator) {
- for (var i = 0, length = this.length; i < length; i++)
- iterator(this[i]);
+ function each(iterator, context) {
+ for (var i = 0, length = this.length >>> 0; i < length; i++) {
+ if (i in this) iterator.call(context, this[i], i, this);
+ }
}
if (!_each) _each = each;
@@ -1287,8 +1295,14 @@ var Hash = Class.create(Enumerable, (function() {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
- if (Object.isArray(values))
- return results.concat(values.map(toQueryPair.curry(key)));
+ if (Object.isArray(values)) {
+ var queryValues = [];
+ for (var i = 0, len = values.length, value; i < len; i++) {
+ value = values[i];
+ queryValues.push(toQueryPair(key, value));
+ }
+ return results.concat(queryValues);
+ }
} else results.push(toQueryPair(key, values));
return results;
}).join('&');
@@ -1468,9 +1482,7 @@ Ajax.Base = Class.create({
this.options.method = this.options.method.toLowerCase();
- if (Object.isString(this.options.parameters))
- this.options.parameters = this.options.parameters.toQueryParams();
- else if (Object.isHash(this.options.parameters))
+ if (Object.isHash(this.options.parameters))
this.options.parameters = this.options.parameters.toObject();
}
});
@@ -1486,22 +1498,21 @@ Ajax.Request = Class.create(Ajax.Base, {
request: function(url) {
this.url = url;
this.method = this.options.method;
- var params = Object.clone(this.options.parameters);
+ var params = Object.isString(this.options.parameters) ?
+ this.options.parameters :
+ Object.toQueryString(this.options.parameters);
if (!['get', 'post'].include(this.method)) {
- params['_method'] = this.method;
+ params += (params ? '&' : '') + "_method=" + this.method;
this.method = 'post';
}
- this.parameters = params;
-
- if (params = Object.toQueryString(params)) {
- if (this.method == 'get')
- this.url += (this.url.include('?') ? '&' : '?') + params;
- else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
- params += '&_=';
+ if (params && this.method === 'get') {
+ this.url += (this.url.include('?') ? '&' : '?') + params;
}
+ this.parameters = params.toQueryParams();
+
try {
var response = new Ajax.Response(this);
if (this.options.onCreate) this.options.onCreate(response);
@@ -1570,11 +1581,12 @@ Ajax.Request = Class.create(Ajax.Base, {
success: function() {
var status = this.getStatus();
- return !status || (status >= 200 && status < 300);
+ return !status || (status >= 200 && status < 300) || status == 304;
},
getStatus: function() {
try {
+ if (this.transport.status === 1223) return 204;
return this.transport.status || 0;
} catch (e) { return 0 }
},
@@ -1849,6 +1861,11 @@ if (!Node.ELEMENT_NODE) {
(function(global) {
+ function shouldUseCache(tagName, attributes) {
+ if (tagName === 'select') return false;
+ if ('type' in attributes) return false;
+ return true;
+ }
var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){
try {
@@ -1866,13 +1883,19 @@ if (!Node.ELEMENT_NODE) {
attributes = attributes || { };
tagName = tagName.toLowerCase();
var cache = Element.cache;
+
if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
return Element.writeAttribute(document.createElement(tagName), attributes);
}
+
if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
- return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
+
+ var node = shouldUseCache(tagName, attributes) ?
+ cache[tagName].cloneNode(false) : document.createElement(tagName);
+
+ return Element.writeAttribute(node, attributes);
};
Object.extend(global.Element, element || { });
@@ -1883,7 +1906,7 @@ if (!Node.ELEMENT_NODE) {
Element.idCounter = 1;
Element.cache = { };
-function purgeElement(element) {
+Element._purgeElement = function(element) {
var uid = element._prototypeUID;
if (uid) {
Element.stopObserving(element);
@@ -1948,6 +1971,21 @@ Element.Methods = {
}
})();
+ var LINK_ELEMENT_INNERHTML_BUGGY = (function() {
+ try {
+ var el = document.createElement('div');
+ el.innerHTML = "<link>";
+ var isBuggy = (el.childNodes.length === 0);
+ el = null;
+ return isBuggy;
+ } catch(e) {
+ return true;
+ }
+ })();
+
+ var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY ||
+ TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY;
+
var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () {
var s = document.createElement("script"),
isBuggy = false;
@@ -1962,8 +2000,10 @@ Element.Methods = {
return isBuggy;
})();
+
function update(element, content) {
element = $(element);
+ var purgeElement = Element._purgeElement;
var descendants = element.getElementsByTagName('*'),
i = descendants.length;
@@ -1984,7 +2024,7 @@ Element.Methods = {
return element;
}
- if (SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY) {
+ if (ANY_INNERHTML_BUGGY) {
if (tagName in Element._insertionTranslations.tags) {
while (element.firstChild) {
element.removeChild(element.firstChild);
@@ -1993,6 +2033,12 @@ Element.Methods = {
.each(function(node) {
element.appendChild(node)
});
+ } else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf('<link') > -1) {
+ while (element.firstChild) {
+ element.removeChild(element.firstChild);
+ }
+ var nodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts(), true);
+ nodes.each(function(node) { element.appendChild(node) });
}
else {
element.innerHTML = content.stripScripts();
@@ -2402,117 +2448,6 @@ Element.Methods = {
return element;
},
- cumulativeOffset: function(element) {
- var valueT = 0, valueL = 0;
- if (element.parentNode) {
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- } while (element);
- }
- return Element._returnOffset(valueL, valueT);
- },
-
- positionedOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- if (element) {
- if (element.tagName.toUpperCase() == 'BODY') break;
- var p = Element.getStyle(element, 'position');
- if (p !== 'static') break;
- }
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- absolutize: function(element) {
- element = $(element);
- if (Element.getStyle(element, 'position') == 'absolute') return element;
-
- var offsets = Element.positionedOffset(element),
- top = offsets[1],
- left = offsets[0],
- width = element.clientWidth,
- height = element.clientHeight;
-
- element._originalLeft = left - parseFloat(element.style.left || 0);
- element._originalTop = top - parseFloat(element.style.top || 0);
- element._originalWidth = element.style.width;
- element._originalHeight = element.style.height;
-
- element.style.position = 'absolute';
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.width = width + 'px';
- element.style.height = height + 'px';
- return element;
- },
-
- relativize: function(element) {
- element = $(element);
- if (Element.getStyle(element, 'position') == 'relative') return element;
-
- element.style.position = 'relative';
- var top = parseFloat(element.style.top || 0) - (element._originalTop || 0),
- left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
-
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.height = element._originalHeight;
- element.style.width = element._originalWidth;
- return element;
- },
-
- cumulativeScrollOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.scrollTop || 0;
- valueL += element.scrollLeft || 0;
- element = element.parentNode;
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- getOffsetParent: function(element) {
- if (element.offsetParent) return $(element.offsetParent);
- if (element == document.body) return $(element);
-
- while ((element = element.parentNode) && element != document.body)
- if (Element.getStyle(element, 'position') != 'static')
- return $(element);
-
- return $(document.body);
- },
-
- viewportOffset: function(forElement) {
- var valueT = 0,
- valueL = 0,
- element = forElement;
-
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
-
- if (element.offsetParent == document.body &&
- Element.getStyle(element, 'position') == 'absolute') break;
-
- } while (element = element.offsetParent);
-
- element = forElement;
- do {
- if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
- valueT -= element.scrollTop || 0;
- valueL -= element.scrollLeft || 0;
- }
- } while (element = element.parentNode);
-
- return Element._returnOffset(valueL, valueT);
- },
-
clonePosition: function(element, source) {
var options = Object.extend({
setLeft: true,
@@ -2566,8 +2501,6 @@ if (Prototype.Browser.Opera) {
Element.Methods.getStyle = Element.Methods.getStyle.wrap(
function(proceed, element, style) {
switch (style) {
- case 'left': case 'top': case 'right': case 'bottom':
- if (proceed(element, 'position') === 'static') return null;
case 'height': case 'width':
if (!Element.visible(element)) return null;
@@ -2603,37 +2536,6 @@ if (Prototype.Browser.Opera) {
}
else if (Prototype.Browser.IE) {
- Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
- function(proceed, element) {
- element = $(element);
- if (!element.parentNode) return $(document.body);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
-
- $w('positionedOffset viewportOffset').each(function(method) {
- Element.Methods[method] = Element.Methods[method].wrap(
- function(proceed, element) {
- element = $(element);
- if (!element.parentNode) return Element._returnOffset(0, 0);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- var offsetParent = element.getOffsetParent();
- if (offsetParent && offsetParent.getStyle('position') === 'fixed')
- offsetParent.setStyle({ zoom: 1 });
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
- });
-
Element.Methods.getStyle = function(element, style) {
element = $(element);
style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
@@ -2862,20 +2764,6 @@ else if (Prototype.Browser.WebKit) {
return element;
};
-
- Element.Methods.cumulativeOffset = function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- if (element.offsetParent == document.body)
- if (Element.getStyle(element, 'position') == 'absolute') break;
-
- element = element.offsetParent;
- } while (element);
-
- return Element._returnOffset(valueL, valueT);
- };
}
if ('outerHTML' in document.documentElement) {
@@ -2914,11 +2802,20 @@ Element._returnOffset = function(l, t) {
return result;
};
-Element._getContentFromAnonymousElement = function(tagName, html) {
+Element._getContentFromAnonymousElement = function(tagName, html, force) {
var div = new Element('div'),
t = Element._insertionTranslations.tags[tagName];
- if (t) {
- div.innerHTML = t[0] + html + t[1];
+
+ var workaround = false;
+ if (t) workaround = true;
+ else if (force) {
+ workaround = true;
+ t = ['', '', 0];
+ }
+
+ if (workaround) {
+ div.innerHTML = '&nbsp;' + t[0] + html + t[1];
+ div.removeChild(div.firstChild);
for (var i = t[2]; i--; ) {
div = div.firstChild;
}
@@ -3077,7 +2974,8 @@ Element.addMethods = function(methods) {
"FORM": Object.clone(Form.Methods),
"INPUT": Object.clone(Form.Element.Methods),
"SELECT": Object.clone(Form.Element.Methods),
- "TEXTAREA": Object.clone(Form.Element.Methods)
+ "TEXTAREA": Object.clone(Form.Element.Methods),
+ "BUTTON": Object.clone(Form.Element.Methods)
});
}
@@ -3264,6 +3162,8 @@ Element.addMethods({
purge: function(element) {
if (!(element = $(element))) return;
+ var purgeElement = Element._purgeElement;
+
purgeElement(element);
var descendants = element.getElementsByTagName('*'),
@@ -3283,11 +3183,13 @@ Element.addMethods({
return (Number(match[1]) / 100);
}
- function getPixelValue(value, property) {
+ function getPixelValue(value, property, context) {
+ var element = null;
if (Object.isElement(value)) {
element = value;
value = element.getStyle(property);
}
+
if (value === null) {
return null;
}
@@ -3296,7 +3198,9 @@ Element.addMethods({
return window.parseFloat(value);
}
- if (/\d/.test(value) && element.runtimeStyle) {
+ var isPercentage = value.include('%'), isViewport = (context === document.viewport);
+
+ if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) {
var style = element.style.left, rStyle = element.runtimeStyle.left;
element.runtimeStyle.left = element.currentStyle.left;
element.style.left = value || 0;
@@ -3307,18 +3211,33 @@ Element.addMethods({
return value;
}
- if (value.include('%')) {
+ if (element && isPercentage) {
+ context = context || element.parentNode;
var decimal = toDecimal(value);
- var whole;
- if (property.include('left') || property.include('right') ||
- property.include('width')) {
- whole = $(element.parentNode).measure('width');
- } else if (property.include('top') || property.include('bottom') ||
- property.include('height')) {
- whole = $(element.parentNode).measure('height');
+ var whole = null;
+ var position = element.getStyle('position');
+
+ var isHorizontal = property.include('left') || property.include('right') ||
+ property.include('width');
+
+ var isVertical = property.include('top') || property.include('bottom') ||
+ property.include('height');
+
+ if (context === document.viewport) {
+ if (isHorizontal) {
+ whole = document.viewport.getWidth();
+ } else if (isVertical) {
+ whole = document.viewport.getHeight();
+ }
+ } else {
+ if (isHorizontal) {
+ whole = $(context).measure('width');
+ } else if (isVertical) {
+ whole = $(context).measure('height');
+ }
}
- return whole * decimal;
+ return (whole === null) ? 0 : whole * decimal;
}
return 0;
@@ -3410,6 +3329,14 @@ Element.addMethods({
var position = element.getStyle('position'),
width = element.getStyle('width');
+ if (width === "0px" || width === null) {
+ element.style.display = 'block';
+ width = element.getStyle('width');
+ }
+
+ var context = (position === 'fixed') ? document.viewport :
+ element.parentNode;
+
element.setStyle({
position: 'absolute',
visibility: 'hidden',
@@ -3420,9 +3347,9 @@ Element.addMethods({
var newWidth;
if (width && (positionedWidth === width)) {
- newWidth = getPixelValue(width);
- } else if (width && (position === 'absolute' || position === 'fixed')) {
- newWidth = getPixelValue(width);
+ newWidth = getPixelValue(element, 'width', context);
+ } else if (position === 'absolute' || position === 'fixed') {
+ newWidth = getPixelValue(element, 'width', context);
} else {
var parent = element.parentNode, pLayout = $(parent).getLayout();
@@ -3453,6 +3380,7 @@ Element.addMethods({
if (!(property in COMPUTATIONS)) {
throw "Property not found.";
}
+
return this._set(property, COMPUTATIONS[property].call(this, this.element));
},
@@ -3505,7 +3433,10 @@ Element.addMethods({
if (!this._preComputing) this._begin();
var bHeight = this.get('border-box-height');
- if (bHeight <= 0) return 0;
+ if (bHeight <= 0) {
+ if (!this._preComputing) this._end();
+ return 0;
+ }
var bTop = this.get('border-top'),
bBottom = this.get('border-bottom');
@@ -3522,7 +3453,10 @@ Element.addMethods({
if (!this._preComputing) this._begin();
var bWidth = this.get('border-box-width');
- if (bWidth <= 0) return 0;
+ if (bWidth <= 0) {
+ if (!this._preComputing) this._end();
+ return 0;
+ }
var bLeft = this.get('border-left'),
bRight = this.get('border-right');
@@ -3552,11 +3486,17 @@ Element.addMethods({
},
'border-box-height': function(element) {
- return element.offsetHeight;
+ if (!this._preComputing) this._begin();
+ var height = element.offsetHeight;
+ if (!this._preComputing) this._end();
+ return height;
},
'border-box-width': function(element) {
- return element.offsetWidth;
+ if (!this._preComputing) this._begin();
+ var width = element.offsetWidth;
+ if (!this._preComputing) this._end();
+ return width;
},
'margin-box-height': function(element) {
@@ -3626,23 +3566,19 @@ Element.addMethods({
},
'border-top': function(element) {
- return Object.isNumber(element.clientTop) ? element.clientTop :
- getPixelValue(element, 'borderTopWidth');
+ return getPixelValue(element, 'borderTopWidth');
},
'border-bottom': function(element) {
- return Object.isNumber(element.clientBottom) ? element.clientBottom :
- getPixelValue(element, 'borderBottomWidth');
+ return getPixelValue(element, 'borderBottomWidth');
},
'border-left': function(element) {
- return Object.isNumber(element.clientLeft) ? element.clientLeft :
- getPixelValue(element, 'borderLeftWidth');
+ return getPixelValue(element, 'borderLeftWidth');
},
'border-right': function(element) {
- return Object.isNumber(element.clientRight) ? element.clientRight :
- getPixelValue(element, 'borderRightWidth');
+ return getPixelValue(element, 'borderRightWidth');
},
'margin-top': function(element) {
@@ -3721,23 +3657,52 @@ Element.addMethods({
}
function getDimensions(element) {
- var layout = $(element).getLayout();
- return {
- width: layout.get('width'),
- height: layout.get('height')
+ element = $(element);
+ var display = Element.getStyle(element, 'display');
+
+ if (display && display !== 'none') {
+ return { width: element.offsetWidth, height: element.offsetHeight };
+ }
+
+ var style = element.style;
+ var originalStyles = {
+ visibility: style.visibility,
+ position: style.position,
+ display: style.display
+ };
+
+ var newStyles = {
+ visibility: 'hidden',
+ display: 'block'
};
+
+ if (originalStyles.position !== 'fixed')
+ newStyles.position = 'absolute';
+
+ Element.setStyle(element, newStyles);
+
+ var dimensions = {
+ width: element.offsetWidth,
+ height: element.offsetHeight
+ };
+
+ Element.setStyle(element, originalStyles);
+
+ return dimensions;
}
function getOffsetParent(element) {
- if (isDetached(element)) return $(document.body);
+ element = $(element);
+
+ if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element))
+ return $(document.body);
var isInline = (Element.getStyle(element, 'display') === 'inline');
if (!isInline && element.offsetParent) return $(element.offsetParent);
- if (element === document.body) return $(element);
while ((element = element.parentNode) && element !== document.body) {
if (Element.getStyle(element, 'position') !== 'static') {
- return (element.nodeName === 'HTML') ? $(document.body) : $(element);
+ return isHtml(element) ? $(document.body) : $(element);
}
}
@@ -3746,16 +3711,21 @@ Element.addMethods({
function cumulativeOffset(element) {
+ element = $(element);
var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- } while (element);
+ if (element.parentNode) {
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ element = element.offsetParent;
+ } while (element);
+ }
return new Element.Offset(valueL, valueT);
}
function positionedOffset(element) {
+ element = $(element);
+
var layout = element.getLayout();
var valueT = 0, valueL = 0;
@@ -3787,6 +3757,7 @@ Element.addMethods({
}
function viewportOffset(forElement) {
+ element = $(element);
var valueT = 0, valueL = 0, docBody = document.body;
var element = forElement;
@@ -3852,6 +3823,57 @@ Element.addMethods({
return element;
}
+ if (Prototype.Browser.IE) {
+ getOffsetParent = getOffsetParent.wrap(
+ function(proceed, element) {
+ element = $(element);
+
+ if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element))
+ return $(document.body);
+
+ var position = element.getStyle('position');
+ if (position !== 'static') return proceed(element);
+
+ element.setStyle({ position: 'relative' });
+ var value = proceed(element);
+ element.setStyle({ position: position });
+ return value;
+ }
+ );
+
+ positionedOffset = positionedOffset.wrap(function(proceed, element) {
+ element = $(element);
+ if (!element.parentNode) return new Element.Offset(0, 0);
+ var position = element.getStyle('position');
+ if (position !== 'static') return proceed(element);
+
+ var offsetParent = element.getOffsetParent();
+ if (offsetParent && offsetParent.getStyle('position') === 'fixed')
+ hasLayout(offsetParent);
+
+ element.setStyle({ position: 'relative' });
+ var value = proceed(element);
+ element.setStyle({ position: position });
+ return value;
+ });
+ } else if (Prototype.Browser.Webkit) {
+ cumulativeOffset = function(element) {
+ element = $(element);
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ if (element.offsetParent == document.body)
+ if (Element.getStyle(element, 'position') == 'absolute') break;
+
+ element = element.offsetParent;
+ } while (element);
+
+ return new Element.Offset(valueL, valueT);
+ };
+ }
+
+
Element.addMethods({
getLayout: getLayout,
measure: measure,
@@ -3869,6 +3891,14 @@ Element.addMethods({
return element.nodeName.toUpperCase() === 'BODY';
}
+ function isHtml(element) {
+ return element.nodeName.toUpperCase() === 'HTML';
+ }
+
+ function isDocument(element) {
+ return element.nodeType === Node.DOCUMENT_NODE;
+ }
+
function isDetached(element) {
return element !== document.body &&
!Element.descendantOf(element, document.body);
@@ -3880,32 +3910,10 @@ Element.addMethods({
element = $(element);
if (isDetached(element)) return new Element.Offset(0, 0);
- var rect = element.getBoundingClientRect(),
+ var rect = element.getBoundingClientRect(),
docEl = document.documentElement;
return new Element.Offset(rect.left - docEl.clientLeft,
rect.top - docEl.clientTop);
- },
-
- positionedOffset: function(element) {
- element = $(element);
- var parent = element.getOffsetParent();
- if (isDetached(element)) return new Element.Offset(0, 0);
-
- if (element.offsetParent &&
- element.offsetParent.nodeName.toUpperCase() === 'HTML') {
- return positionedOffset(element);
- }
-
- var eOffset = element.viewportOffset(),
- pOffset = isBody(parent) ? viewportOffset(parent) :
- parent.viewportOffset();
- var retOffset = eOffset.relativeTo(pOffset);
-
- var layout = element.getLayout();
- var top = retOffset.top - layout.get('margin-top');
- var left = retOffset.left - layout.get('margin-left');
-
- return new Element.Offset(left, top);
}
});
}
@@ -4962,24 +4970,34 @@ var Form = {
serializeElements: function(elements, options) {
if (typeof options != 'object') options = { hash: !!options };
else if (Object.isUndefined(options.hash)) options.hash = true;
- var key, value, submitted = false, submit = options.submit;
+ var key, value, submitted = false, submit = options.submit, accumulator, initial;
+
+ if (options.hash) {
+ initial = {};
+ accumulator = function(result, key, value) {
+ if (key in result) {
+ if (!Object.isArray(result[key])) result[key] = [result[key]];
+ result[key].push(value);
+ } else result[key] = value;
+ return result;
+ };
+ } else {
+ initial = '';
+ accumulator = function(result, key, value) {
+ return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
+ }
+ }
- var data = elements.inject({ }, function(result, element) {
+ return elements.inject(initial, function(result, element) {
if (!element.disabled && element.name) {
key = element.name; value = $(element).getValue();
if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
submit !== false && (!submit || key == submit) && (submitted = true)))) {
- if (key in result) {
- if (!Object.isArray(result[key])) result[key] = [result[key]];
- result[key].push(value);
- }
- else result[key] = value;
+ result = accumulator(result, key, value);
}
}
return result;
});
-
- return options.hash ? data : Object.toQueryString(data);
}
};
@@ -5046,7 +5064,8 @@ Form.Methods = {
focusFirstElement: function(form) {
form = $(form);
- form.findFirstElement().activate();
+ var element = form.findFirstElement();
+ if (element) element.activate();
return form;
},
@@ -5153,67 +5172,77 @@ var $F = Form.Element.Methods.getValue;
/*--------------------------------------------------------------------------*/
-Form.Element.Serializers = {
- input: function(element, value) {
+Form.Element.Serializers = (function() {
+ function input(element, value) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
- return Form.Element.Serializers.inputSelector(element, value);
+ return inputSelector(element, value);
default:
- return Form.Element.Serializers.textarea(element, value);
+ return valueSelector(element, value);
}
- },
+ }
- inputSelector: function(element, value) {
- if (Object.isUndefined(value)) return element.checked ? element.value : null;
+ function inputSelector(element, value) {
+ if (Object.isUndefined(value))
+ return element.checked ? element.value : null;
else element.checked = !!value;
- },
+ }
- textarea: function(element, value) {
+ function valueSelector(element, value) {
if (Object.isUndefined(value)) return element.value;
else element.value = value;
- },
+ }
- select: function(element, value) {
+ function select(element, value) {
if (Object.isUndefined(value))
- return this[element.type == 'select-one' ?
- 'selectOne' : 'selectMany'](element);
- else {
- var opt, currentValue, single = !Object.isArray(value);
- for (var i = 0, length = element.length; i < length; i++) {
- opt = element.options[i];
- currentValue = this.optionValue(opt);
- if (single) {
- if (currentValue == value) {
- opt.selected = true;
- return;
- }
+ return (element.type === 'select-one' ? selectOne : selectMany)(element);
+
+ var opt, currentValue, single = !Object.isArray(value);
+ for (var i = 0, length = element.length; i < length; i++) {
+ opt = element.options[i];
+ currentValue = this.optionValue(opt);
+ if (single) {
+ if (currentValue == value) {
+ opt.selected = true;
+ return;
}
- else opt.selected = value.include(currentValue);
}
+ else opt.selected = value.include(currentValue);
}
- },
+ }
- selectOne: function(element) {
+ function selectOne(element) {
var index = element.selectedIndex;
- return index >= 0 ? this.optionValue(element.options[index]) : null;
- },
+ return index >= 0 ? optionValue(element.options[index]) : null;
+ }
- selectMany: function(element) {
+ function selectMany(element) {
var values, length = element.length;
if (!length) return null;
for (var i = 0, values = []; i < length; i++) {
var opt = element.options[i];
- if (opt.selected) values.push(this.optionValue(opt));
+ if (opt.selected) values.push(optionValue(opt));
}
return values;
- },
+ }
- optionValue: function(opt) {
- return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
+ function optionValue(opt) {
+ return Element.hasAttribute(opt, 'value') ? opt.value : opt.text;
}
-};
+
+ return {
+ input: input,
+ inputSelector: inputSelector,
+ textarea: valueSelector,
+ select: select,
+ selectOne: selectOne,
+ selectMany: selectMany,
+ optionValue: optionValue,
+ button: valueSelector
+ };
+})();
/*--------------------------------------------------------------------------*/
@@ -5324,24 +5353,53 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl
&& 'onmouseleave' in docEl;
+
+
+ var isIELegacyEvent = function(event) { return false; };
+
+ if (window.attachEvent) {
+ if (window.addEventListener) {
+ isIELegacyEvent = function(event) {
+ return !(event instanceof window.Event);
+ };
+ } else {
+ isIELegacyEvent = function(event) { return true; };
+ }
+ }
+
var _isButton;
- if (Prototype.Browser.IE) {
- var buttonMap = { 0: 1, 1: 4, 2: 2 };
- _isButton = function(event, code) {
- return event.button === buttonMap[code];
- };
- } else if (Prototype.Browser.WebKit) {
- _isButton = function(event, code) {
- switch (code) {
- case 0: return event.which == 1 && !event.metaKey;
- case 1: return event.which == 1 && event.metaKey;
- default: return false;
+
+ function _isButtonForDOMEvents(event, code) {
+ return event.which ? (event.which === code + 1) : (event.button === code);
+ }
+
+ var legacyButtonMap = { 0: 1, 1: 4, 2: 2 };
+ function _isButtonForLegacyEvents(event, code) {
+ return event.button === legacyButtonMap[code];
+ }
+
+ function _isButtonForWebKit(event, code) {
+ switch (code) {
+ case 0: return event.which == 1 && !event.metaKey;
+ case 1: return event.which == 2 || (event.which == 1 && event.metaKey);
+ case 2: return event.which == 3;
+ default: return false;
+ }
+ }
+
+ if (window.attachEvent) {
+ if (!window.addEventListener) {
+ _isButton = _isButtonForLegacyEvents;
+ } else {
+ _isButton = function(event, code) {
+ return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) :
+ _isButtonForDOMEvents(event, code);
}
- };
+ }
+ } else if (Prototype.Browser.WebKit) {
+ _isButton = _isButtonForWebKit;
} else {
- _isButton = function(event, code) {
- return event.which ? (event.which === code + 1) : (event.button === code);
- };
+ _isButton = _isButtonForDOMEvents;
}
function isLeftClick(event) { return _isButton(event, 0) }
@@ -5371,6 +5429,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
function findElement(event, expression) {
var element = Event.element(event);
+
if (!expression) return element;
while (element) {
if (Object.isElement(element) && Prototype.Selector.match(element, expression)) {
@@ -5411,49 +5470,59 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
event.stopped = true;
}
+
Event.Methods = {
- isLeftClick: isLeftClick,
+ isLeftClick: isLeftClick,
isMiddleClick: isMiddleClick,
- isRightClick: isRightClick,
+ isRightClick: isRightClick,
- element: element,
+ element: element,
findElement: findElement,
- pointer: pointer,
+ pointer: pointer,
pointerX: pointerX,
pointerY: pointerY,
stop: stop
};
-
var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
m[name] = Event.Methods[name].methodize();
return m;
});
- if (Prototype.Browser.IE) {
+ if (window.attachEvent) {
function _relatedTarget(event) {
var element;
switch (event.type) {
- case 'mouseover': element = event.fromElement; break;
- case 'mouseout': element = event.toElement; break;
- default: return null;
+ case 'mouseover':
+ case 'mouseenter':
+ element = event.fromElement;
+ break;
+ case 'mouseout':
+ case 'mouseleave':
+ element = event.toElement;
+ break;
+ default:
+ return null;
}
return Element.extend(element);
}
- Object.extend(methods, {
+ var additionalMethods = {
stopPropagation: function() { this.cancelBubble = true },
preventDefault: function() { this.returnValue = false },
inspect: function() { return '[object Event]' }
- });
+ };
Event.extend = function(event, element) {
if (!event) return false;
- if (event._extendedByPrototype) return event;
+ if (!isIELegacyEvent(event)) return event;
+
+ if (event._extendedByPrototype) return event;
event._extendedByPrototype = Prototype.emptyFunction;
+
var pointer = Event.pointer(event);
Object.extend(event, {
@@ -5463,12 +5532,18 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
pageY: pointer.y
});
- return Object.extend(event, methods);
+ Object.extend(event, methods);
+ Object.extend(event, additionalMethods);
+
+ return event;
};
} else {
+ Event.extend = Prototype.K;
+ }
+
+ if (window.addEventListener) {
Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__;
Object.extend(Event.prototype, methods);
- Event.extend = Prototype.K;
}
function _createResponder(element, eventName, handler) {
@@ -5567,7 +5642,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
element.addEventListener("dataavailable", responder, false);
else {
element.attachEvent("ondataavailable", responder);
- element.attachEvent("onfilterchange", responder);
+ element.attachEvent("onlosecapture", responder);
}
} else {
var actualEventName = _getDOMEventName(eventName);
@@ -5605,7 +5680,13 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
return element;
}
- var responder = responders.find( function(r) { return r.handler === handler; });
+ var i = responders.length, responder;
+ while (i--) {
+ if (responders[i].handler === handler) {
+ responder = responders[i];
+ break;
+ }
+ }
if (!responder) return element;
if (eventName.include(':')) {
@@ -5613,7 +5694,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
element.removeEventListener("dataavailable", responder, false);
else {
element.detachEvent("ondataavailable", responder);
- element.detachEvent("onfilterchange", responder);
+ element.detachEvent("onlosecapture", responder);
}
} else {
var actualEventName = _getDOMEventName(eventName);
@@ -5640,10 +5721,10 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
var event;
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
- event.initEvent('dataavailable', true, true);
+ event.initEvent('dataavailable', bubble, true);
} else {
event = document.createEventObject();
- event.eventType = bubble ? 'ondataavailable' : 'onfilterchange';
+ event.eventType = bubble ? 'ondataavailable' : 'onlosecapture';
}
event.eventName = eventName;
@@ -5677,7 +5758,7 @@ Form.EventObserver = Class.create(Abstract.EventObserver, {
},
handleEvent: function(event) {
- var element = event.findElement(this.selector);
+ var element = Event.findElement(event, this.selector);
if (element) this.callback.call(this.element, event, element);
}
});
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
new file mode 100644
index 0000000000..2cd1220786
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
@@ -0,0 +1,208 @@
+(function() {
+ // Technique from Juriy Zaytsev
+ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
+ function isEventSupported(eventName) {
+ var el = document.createElement('div');
+ eventName = 'on' + eventName;
+ var isSupported = (eventName in el);
+ if (!isSupported) {
+ el.setAttribute(eventName, 'return;');
+ isSupported = typeof el[eventName] == 'function';
+ }
+ el = null;
+ return isSupported;
+ }
+
+ function isForm(element) {
+ return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM';
+ }
+
+ function isInput(element) {
+ if (Object.isElement(element)) {
+ var name = element.nodeName.toUpperCase();
+ return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA';
+ }
+ else return false;
+ }
+
+ var submitBubbles = isEventSupported('submit'),
+ changeBubbles = isEventSupported('change');
+
+ if (!submitBubbles || !changeBubbles) {
+ // augment the Event.Handler class to observe custom events when needed
+ Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
+ function(init, element, eventName, selector, callback) {
+ init(element, eventName, selector, callback);
+ // is the handler being attached to an element that doesn't support this event?
+ if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
+ (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
+ // "submit" => "emulated:submit"
+ this.eventName = 'emulated:' + this.eventName;
+ }
+ }
+ );
+ }
+
+ if (!submitBubbles) {
+ // discover forms on the page by observing focus events which always bubble
+ document.on('focusin', 'form', function(focusEvent, form) {
+ // special handler for the real "submit" event (one-time operation)
+ if (!form.retrieve('emulated:submit')) {
+ form.on('submit', function(submitEvent) {
+ var emulated = form.fire('emulated:submit', submitEvent, true);
+ // if custom event received preventDefault, cancel the real one too
+ if (emulated.returnValue === false) submitEvent.preventDefault();
+ });
+ form.store('emulated:submit', true);
+ }
+ });
+ }
+
+ if (!changeBubbles) {
+ // discover form inputs on the page
+ document.on('focusin', 'input, select, textarea', function(focusEvent, input) {
+ // special handler for real "change" events
+ if (!input.retrieve('emulated:change')) {
+ input.on('change', function(changeEvent) {
+ input.fire('emulated:change', changeEvent, true);
+ });
+ input.store('emulated:change', true);
+ }
+ });
+ }
+
+ function handleRemote(element) {
+ var method, url, params;
+
+ var event = element.fire("ajax:before");
+ if (event.stopped) return false;
+
+ if (element.tagName.toLowerCase() === 'form') {
+ method = element.readAttribute('method') || 'post';
+ url = element.readAttribute('action');
+ // serialize the form with respect to the submit button that was pressed
+ params = element.serialize({ submit: element.retrieve('rails:submit-button') });
+ // clear the pressed submit button information
+ element.store('rails:submit-button', null);
+ } else {
+ method = element.readAttribute('data-method') || 'get';
+ url = element.readAttribute('href');
+ params = {};
+ }
+
+ new Ajax.Request(url, {
+ method: method,
+ parameters: params,
+ evalScripts: true,
+
+ onCreate: function(response) { element.fire("ajax:create", response); },
+ onComplete: function(response) { element.fire("ajax:complete", response); },
+ onSuccess: function(response) { element.fire("ajax:success", response); },
+ onFailure: function(response) { element.fire("ajax:failure", response); }
+ });
+
+ element.fire("ajax:after");
+ }
+
+ function insertHiddenField(form, name, value) {
+ form.insert(new Element('input', { type: 'hidden', name: name, value: value }));
+ }
+
+ function handleMethod(element) {
+ var method = element.readAttribute('data-method'),
+ url = element.readAttribute('href'),
+ csrf_param = $$('meta[name=csrf-param]')[0],
+ csrf_token = $$('meta[name=csrf-token]')[0];
+
+ var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
+ $(element.parentNode).insert(form);
+
+ if (method !== 'post') {
+ insertHiddenField(form, '_method', method);
+ }
+
+ if (csrf_param) {
+ insertHiddenField(form, csrf_param.readAttribute('content'), csrf_token.readAttribute('content'));
+ }
+
+ form.submit();
+ }
+
+ function disableFormElements(form) {
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
+ input.store('rails:original-value', input.getValue());
+ input.setValue(input.readAttribute('data-disable-with')).disable();
+ });
+ }
+
+ function enableFormElements(form) {
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
+ input.setValue(input.retrieve('rails:original-value')).enable();
+ });
+ }
+
+ function allowAction(element) {
+ var message = element.readAttribute('data-confirm');
+ return !message || confirm(message);
+ }
+
+ document.on('click', 'a[data-confirm], a[data-remote], a[data-method]', function(event, link) {
+ if (!allowAction(link)) {
+ event.stop();
+ return false;
+ }
+
+ if (link.readAttribute('data-remote')) {
+ handleRemote(link);
+ event.stop();
+ } else if (link.readAttribute('data-method')) {
+ handleMethod(link);
+ event.stop();
+ }
+ });
+
+ document.on("click", "form input[type=submit], form button[type=submit], form button:not([type])", function(event, button) {
+ // register the pressed submit button
+ event.findElement('form').store('rails:submit-button', button.name || false);
+ });
+
+ document.on("submit", function(event) {
+ var form = event.findElement();
+
+ if (!allowAction(form)) {
+ event.stop();
+ return false;
+ }
+
+ if (form.readAttribute('data-remote')) {
+ handleRemote(form);
+ event.stop();
+ } else {
+ disableFormElements(form);
+ }
+ });
+
+ document.on('ajax:create', 'form', function(event, form) {
+ if (form == event.findElement()) disableFormElements(form);
+ });
+
+ document.on('ajax:complete', 'form', function(event, form) {
+ if (form == event.findElement()) enableFormElements(form);
+ });
+
+ Ajax.Responders.register({
+ onCreate: function(request) {
+ var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
+
+ if (csrf_meta_tag) {
+ var header = 'X-CSRF-Token',
+ token = csrf_meta_tag.readAttribute('content');
+
+ if (!request.options.requestHeaders) {
+ request.options.requestHeaders = {};
+ }
+ request.options.requestHeaders[header] = token;
+ }
+ }
+ });
+})();
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js
deleted file mode 100644
index 4283ed8982..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js
+++ /dev/null
@@ -1,175 +0,0 @@
-(function() {
- // Technique from Juriy Zaytsev
- // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
- function isEventSupported(eventName) {
- var el = document.createElement('div');
- eventName = 'on' + eventName;
- var isSupported = (eventName in el);
- if (!isSupported) {
- el.setAttribute(eventName, 'return;');
- isSupported = typeof el[eventName] == 'function';
- }
- el = null;
- return isSupported;
- }
-
- function isForm(element) {
- return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM'
- }
-
- function isInput(element) {
- if (Object.isElement(element)) {
- var name = element.nodeName.toUpperCase()
- return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA'
- }
- else return false
- }
-
- var submitBubbles = isEventSupported('submit'),
- changeBubbles = isEventSupported('change')
-
- if (!submitBubbles || !changeBubbles) {
- // augment the Event.Handler class to observe custom events when needed
- Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
- function(init, element, eventName, selector, callback) {
- init(element, eventName, selector, callback)
- // is the handler being attached to an element that doesn't support this event?
- if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
- (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
- // "submit" => "emulated:submit"
- this.eventName = 'emulated:' + this.eventName
- }
- }
- )
- }
-
- if (!submitBubbles) {
- // discover forms on the page by observing focus events which always bubble
- document.on('focusin', 'form', function(focusEvent, form) {
- // special handler for the real "submit" event (one-time operation)
- if (!form.retrieve('emulated:submit')) {
- form.on('submit', function(submitEvent) {
- var emulated = form.fire('emulated:submit', submitEvent, true)
- // if custom event received preventDefault, cancel the real one too
- if (emulated.returnValue === false) submitEvent.preventDefault()
- })
- form.store('emulated:submit', true)
- }
- })
- }
-
- if (!changeBubbles) {
- // discover form inputs on the page
- document.on('focusin', 'input, select, texarea', function(focusEvent, input) {
- // special handler for real "change" events
- if (!input.retrieve('emulated:change')) {
- input.on('change', function(changeEvent) {
- input.fire('emulated:change', changeEvent, true)
- })
- input.store('emulated:change', true)
- }
- })
- }
-
- function handleRemote(element) {
- var method, url, params;
-
- var event = element.fire("ajax:before");
- if (event.stopped) return false;
-
- if (element.tagName.toLowerCase() === 'form') {
- method = element.readAttribute('method') || 'post';
- url = element.readAttribute('action');
- params = element.serialize();
- } else {
- method = element.readAttribute('data-method') || 'get';
- url = element.readAttribute('href');
- params = {};
- }
-
- new Ajax.Request(url, {
- method: method,
- parameters: params,
- evalScripts: true,
-
- onComplete: function(request) { element.fire("ajax:complete", request); },
- onSuccess: function(request) { element.fire("ajax:success", request); },
- onFailure: function(request) { element.fire("ajax:failure", request); }
- });
-
- element.fire("ajax:after");
- }
-
- function handleMethod(element) {
- var method = element.readAttribute('data-method'),
- url = element.readAttribute('href'),
- csrf_param = $$('meta[name=csrf-param]')[0],
- csrf_token = $$('meta[name=csrf-token]')[0];
-
- var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
- element.parentNode.insert(form);
-
- if (method !== 'post') {
- var field = new Element('input', { type: 'hidden', name: '_method', value: method });
- form.insert(field);
- }
-
- if (csrf_param) {
- var param = csrf_param.readAttribute('content'),
- token = csrf_token.readAttribute('content'),
- field = new Element('input', { type: 'hidden', name: param, value: token });
- form.insert(field);
- }
-
- form.submit();
- }
-
-
- document.on("click", "*[data-confirm]", function(event, element) {
- var message = element.readAttribute('data-confirm');
- if (!confirm(message)) event.stop();
- });
-
- document.on("click", "a[data-remote]", function(event, element) {
- if (event.stopped) return;
- handleRemote(element);
- event.stop();
- });
-
- document.on("click", "a[data-method]", function(event, element) {
- if (event.stopped) return;
- handleMethod(element);
- event.stop();
- });
-
- document.on("submit", function(event) {
- var element = event.findElement(),
- message = element.readAttribute('data-confirm');
- if (message && !confirm(message)) {
- event.stop();
- return false;
- }
-
- var inputs = element.select("input[type=submit][data-disable-with]");
- inputs.each(function(input) {
- input.disabled = true;
- input.writeAttribute('data-original-value', input.value);
- input.value = input.readAttribute('data-disable-with');
- });
-
- var element = event.findElement("form[data-remote]");
- if (element) {
- handleRemote(element);
- event.stop();
- }
- });
-
- document.on("ajax:after", "form", function(event, element) {
- var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
- inputs.each(function(input) {
- input.value = input.readAttribute('data-original-value');
- input.removeAttribute('data-original-value');
- input.disabled = false;
- });
- });
-})();
diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb
index cda2659e69..c61ea4b510 100644
--- a/railties/lib/rails/generators/rails/controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb
@@ -1,3 +1,4 @@
+<% module_namespacing do -%>
class <%= class_name %>Controller < ApplicationController
<% for action in actions -%>
def <%= action %>
@@ -5,3 +6,4 @@ class <%= class_name %>Controller < ApplicationController
<% end -%>
end
+<% end -%>
diff --git a/railties/lib/rails/generators/rails/generator/USAGE b/railties/lib/rails/generators/rails/generator/USAGE
index d8c3f7f634..d28eb3d7d8 100644
--- a/railties/lib/rails/generators/rails/generator/USAGE
+++ b/railties/lib/rails/generators/rails/generator/USAGE
@@ -1,6 +1,6 @@
Description:
- Stubs out a new generator at lib/generators. Pass the generator name, either
- CamelCased or under_scored, as an argument.
+ 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`
@@ -8,4 +8,5 @@ Example:
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
index 5b5d1884bc..3e0a442bda 100644
--- a/railties/lib/rails/generators/rails/generator/generator_generator.rb
+++ b/railties/lib/rails/generators/rails/generator/generator_generator.rb
@@ -14,9 +14,9 @@ module Rails
def generator_dir
if options[:namespace]
- File.join("lib", "generators", file_name)
+ File.join("lib", "generators", regular_class_path, file_name)
else
- File.join("lib", "generators")
+ File.join("lib", "generators", regular_class_path)
end
end
diff --git a/railties/lib/rails/generators/rails/helper/templates/helper.rb b/railties/lib/rails/generators/rails/helper/templates/helper.rb
index 3fe2ecdc74..b4173151b4 100644
--- a/railties/lib/rails/generators/rails/helper/templates/helper.rb
+++ b/railties/lib/rails/generators/rails/helper/templates/helper.rb
@@ -1,2 +1,4 @@
+<% module_namespacing do -%>
module <%= class_name %>Helper
end
+<% end -%>
diff --git a/railties/lib/rails/generators/rails/migration/USAGE b/railties/lib/rails/generators/rails/migration/USAGE
index d21c81b760..af74963b01 100644
--- a/railties/lib/rails/generators/rails/migration/USAGE
+++ b/railties/lib/rails/generators/rails/migration/USAGE
@@ -18,12 +18,12 @@ Example:
This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with
this in the Up migration:
- add_column :posts, :title, :string
- add_column :posts, :body, :text
+ add_column :posts, :title, :string
+ add_column :posts, :body, :text
add_column :posts, :published, :boolean
And this in the Down migration:
- remove_column :posts, :published
- remove_column :posts, :body
+ remove_column :posts, :published
+ remove_column :posts, :body
remove_column :posts, :title
diff --git a/railties/lib/rails/generators/rails/plugin/USAGE b/railties/lib/rails/generators/rails/plugin/USAGE
index 00a429c585..1bcfcf190d 100644
--- a/railties/lib/rails/generators/rails/plugin/USAGE
+++ b/railties/lib/rails/generators/rails/plugin/USAGE
@@ -1,6 +1,6 @@
Description:
Stubs out a new plugin at vendor/plugins. Pass the plugin name, either
- CamelCased or under_scored, as an argument.
+ CamelCased or under_scored, as an argument.
Example:
`rails generate plugin BrowserFilters`
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index 40ed2062d3..97f681d826 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -1,3 +1,4 @@
+
require 'rails/generators/rails/generator/generator_generator'
module Rails
@@ -5,6 +6,12 @@ module Rails
class PluginGenerator < NamedBase
class_option :tasks, :desc => "When supplied creates tasks base files."
+ def show_deprecation
+ return unless behavior == :invoke
+ message = "Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure."
+ ActiveSupport::Deprecation.warn message
+ end
+
check_class_collision
def create_root_files
diff --git a/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt b/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt
index 733e321c94..77149ae351 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt
+++ b/railties/lib/rails/generators/rails/plugin/templates/Rakefile.tt
@@ -1,4 +1,4 @@
-require 'rake'
+#!/usr/bin/env rake
require 'rake/testtask'
require 'rake/rdoctask'
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 0000000000..9a7bf9f396
--- /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 0000000000..3cf8410d1e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
@@ -0,0 +1,290 @@
+require 'active_support/core_ext/hash/slice'
+require "rails/generators/rails/app/app_generator"
+require 'date'
+
+module Rails
+ class PluginBuilder
+ def rakefile
+ template "Rakefile"
+ end
+
+ def app
+ if options[:mountable]
+ directory "app"
+ template "#{app_templates_dir}/app/views/layouts/application.html.erb.tt",
+ "app/views/layouts/#{name}/application.html.erb"
+ end
+ end
+
+ def readme
+ template "README.rdoc"
+ end
+
+ def gemfile
+ template "Gemfile"
+ end
+
+ def license
+ template "MIT-LICENSE"
+ end
+
+ def gemspec
+ template "%name%.gemspec"
+ end
+
+ def gitignore
+ copy_file "gitignore", ".gitignore"
+ end
+
+ def lib
+ template "lib/%name%.rb"
+ template "lib/tasks/%name%_tasks.rake"
+ if full?
+ template "lib/%name%/engine.rb"
+ end
+ end
+
+ def config
+ template "config/routes.rb" if full?
+ 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 full?
+ template "test/integration/navigation_test.rb"
+ end
+ end
+
+ def generate_test_dummy(force = false)
+ opts = (options || {}).slice(:skip_active_record, :skip_javascript, :database, :javascript, :quiet, :pretend, :force, :skip)
+ opts[:force] = force
+
+ 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_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/images/rails.png"
+ remove_file "public/index.html"
+ remove_file "public/robots.txt"
+ remove_file "README"
+ remove_file "test"
+ remove_file "vendor"
+ end
+ end
+
+ def stylesheets
+ empty_directory_with_gitkeep "public/stylesheets" if options[:mountable]
+ end
+
+ def javascripts
+ return unless options[:mountable]
+
+ empty_directory "#{app_templates_dir}/public/javascripts"
+
+ unless options[:skip_javascript]
+ copy_file "#{app_templates_dir}/public/javascripts/#{options[:javascript]}.js", "public/javascripts/#{options[:javascript]}.js"
+ copy_file "#{app_templates_dir}/public/javascripts/#{options[:javascript]}_ujs.js", "public/javascripts/rails.js"
+
+ if options[:javascript] == "prototype"
+ copy_file "#{app_templates_dir}/public/javascripts/controls.js", "public/javascripts/controls.js"
+ copy_file "#{app_templates_dir}/public/javascripts/dragdrop.js", "public/javascripts/dragdrop.js"
+ copy_file "#{app_templates_dir}/public/javascripts/effects.js", "public/javascripts/effects.js"
+ end
+ end
+
+ copy_file "#{app_templates_dir}/public/javascripts/application.js", "public/javascripts/application.js"
+ end
+
+ def script(force = false)
+ directory "script", :force => force do |content|
+ "#{shebang}\n" + content
+ end
+ chmod "script", 0755, :verbose => false
+ end
+ end
+
+ module Generators
+ class PluginNewGenerator < AppBase
+ 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 rails engine with integration tests"
+
+ class_option :mountable, :type => :boolean, :default => false,
+ :desc => "Generate mountable isolated application"
+
+ class_option :skip_gemspec, :type => :boolean, :default => false,
+ :desc => "Skip gemspec file"
+
+ def initialize(*args)
+ raise Error, "Options should be given after the plugin name. For details run: rails plugin --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_script_files
+ build(:script)
+ end
+
+ def create_test_files
+ build(:test) unless options[:skip_test_unit]
+ end
+
+ def create_test_dummy_files
+ return if options[:skip_test_unit]
+ create_dummy_app
+ end
+
+ def finish_template
+ build(:leftovers)
+ end
+
+ public_task :apply_rails_template, :bundle_if_dev_or_edge
+
+ protected
+ def app_templates_dir
+ "../../app/templates"
+ end
+
+ def create_dummy_app(path = nil)
+ dummy_path(path) if path
+
+ say_status :vendor_app, dummy_path
+ mute do
+ build(:generate_test_dummy)
+ store_application_definition!
+ build(:test_dummy_config)
+ build(:test_dummy_clean)
+ # ensure that script/rails has proper dummy_path
+ build(:script, true)
+ end
+ end
+
+ def full?
+ options[:full] || options[:mountable]
+ end
+
+ def mountable?
+ options[:mountable]
+ end
+
+ def self.banner
+ "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]"
+ end
+
+ def name
+ @name ||= File.basename(destination_root)
+ end
+
+ def camelized
+ @camelized ||= name.gsub(/\W/, '_').squeeze('_').camelize
+ end
+
+ def valid_const?
+ if camelized =~ /^\d/
+ raise Error, "Invalid plugin name #{name}. Please give a name which does not start with numbers."
+ elsif RESERVED_NAMES.include?(name)
+ raise Error, "Invalid plugin name #{name}. Please give a name which does not match one of the reserved rails words."
+ elsif Object.const_defined?(camelized)
+ raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another application 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 Dummy"))..-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
+ 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 0000000000..3d9bfb22c7
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
@@ -0,0 +1,9 @@
+# Provide a simple gemspec so you can easily use your
+# project in your rails apps through git.
+Gem::Specification.new do |s|
+ s.name = "<%= name %>"
+ s.summary = "Insert <%= camelized %> summary."
+ s.description = "Insert <%= camelized %> description."
+ s.files = Dir["lib/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
+ s.version = "0.0.1"
+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 0000000000..29900c93dc
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
@@ -0,0 +1,11 @@
+source "http://rubygems.org"
+
+<%= rails_gemfile_entry -%>
+
+<% if full? -%>
+<%= database_gemfile_entry -%>
+<% end -%>
+
+if RUBY_VERSION < '1.9'
+ gem "ruby-debug", ">= 0.10.3"
+end
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 0000000000..d7a9109894
--- /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 0000000000..301d647731
--- /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 100755
index 0000000000..5704e75a29
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
@@ -0,0 +1,21 @@
+#!/usr/bin/env rake
+begin
+ require 'bundler/setup'
+rescue LoadError
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
+end
+
+require 'rake/rdoctask'
+
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = '<%= camelized %>'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+<% if full? && !options[:skip_active_record] -%>
+APP_RAKEFILE = File.expand_path("../<%= dummy_path -%>/Rakefile", __FILE__)
+load 'rails/tasks/engine.rake'
+<% end %>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/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 0000000000..448ad7f989
--- /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 0000000000..40ae9f52c2
--- /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/config/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
new file mode 100644
index 0000000000..8e158d5831
--- /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 0000000000..1463de6dfb
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
@@ -0,0 +1,6 @@
+.bundle/
+log/*.log
+pkg/
+test/dummy/db/*.sqlite3
+test/dummy/log/*.log
+test/dummy/tmp/ \ 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 0000000000..2d3bdc510c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb
@@ -0,0 +1,6 @@
+<% if full? -%>
+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 0000000000..aa8ea77bae
--- /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/tasks/%name%_tasks.rake b/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake
new file mode 100644
index 0000000000..7121f5ae23
--- /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 0000000000..8b68280a5e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
@@ -0,0 +1,16 @@
+require File.expand_path('../boot', __FILE__)
+
+<% unless options[:skip_active_record] -%>
+require 'rails/all'
+<% else -%>
+# require "active_record/railtie"
+require "action_controller/railtie"
+require "action_mailer/railtie"
+require "active_resource/railtie"
+require "rails/test_unit/railtie"
+<% end -%>
+
+Bundler.require
+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 0000000000..eba0681370
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
@@ -0,0 +1,10 @@
+require 'rubygems'
+gemfile = File.expand_path('../../../../Gemfile', __FILE__)
+
+if File.exist?(gemfile)
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+end
+
+$:.unshift File.expand_path('../../../../lib', __FILE__) \ No newline at end of file
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 0000000000..730ee31c3d
--- /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/script/rails.tt b/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt
new file mode 100644
index 0000000000..ebd5a77dd5
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt
@@ -0,0 +1,5 @@
+#!/usr/bin/env ruby
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+ENGINE_PATH = File.expand_path('../..', __FILE__)
+load File.expand_path('../../<%= dummy_path %>/script/rails', __FILE__)
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 0000000000..0a8bbd4aaf
--- /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 0000000000..dd4d2da4eb
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
@@ -0,0 +1,13 @@
+require 'test_helper'
+
+class NavigationTest < ActionDispatch::IntegrationTest
+<% unless options[:skip_active_record] -%>
+ fixtures :all
+<% end -%>
+
+ # Replace this with your real tests.
+ 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 0000000000..dcd3b276e3
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
@@ -0,0 +1,10 @@
+# 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 }
diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb
index fc070026d6..c7345f3cfb 100644
--- a/railties/lib/rails/generators/rails/resource/resource_generator.rb
+++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb
@@ -16,9 +16,9 @@ module Rails
def add_resource_route
return if options[:actions].present?
- route_config = class_path.collect{|namespace| "namespace :#{namespace} do " }.join(" ")
+ route_config = regular_class_path.collect{|namespace| "namespace :#{namespace} do " }.join(" ")
route_config << "resources :#{file_name.pluralize}"
- route_config << " end" * class_path.size
+ route_config << " end" * regular_class_path.size
route route_config
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
index b21340f755..b5317a055b 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -1,3 +1,4 @@
+<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
# GET <%= route_url %>
# GET <%= route_url %>.xml
@@ -81,3 +82,4 @@ class <%= controller_class_name %>Controller < ApplicationController
end
end
end
+<% end -%>
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
index 829f4b200a..de01c858dd 100644
--- a/railties/lib/rails/generators/resource_helpers.rb
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -17,7 +17,7 @@ module Rails
def initialize(*args) #:nodoc:
super
- if name == name.pluralize && !options[:force_plural]
+ 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
@@ -34,7 +34,7 @@ module Rails
attr_reader :controller_name
def controller_class_path
- @class_path
+ class_path
end
def controller_file_name
@@ -46,14 +46,14 @@ module Rails
end
def controller_class_name
- @controller_class_name ||= (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
+ (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
end
def controller_i18n_scope
@controller_i18n_scope ||= controller_file_path.gsub('/', '.')
end
- # Loads the ORM::Generators::ActiveModel class. This class is responsable
+ # 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
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
index 3376b422cb..ee85b70bb5 100644
--- a/railties/lib/rails/generators/test_case.rb
+++ b/railties/lib/rails/generators/test_case.rb
@@ -1,6 +1,7 @@
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 'rails/generators'
require 'fileutils'
@@ -65,25 +66,6 @@ module Rails
self.destination_root = path
end
- # Captures the given stream and returns it:
- #
- # stream = capture(:stdout){ puts "Cool" }
- # stream # => "Cool\n"
- #
- def capture(stream)
- begin
- stream = stream.to_s
- eval "$#{stream} = StringIO.new"
- yield
- result = eval("$#{stream}").string
- ensure
- eval("$#{stream} = #{stream.upcase}")
- end
-
- result
- end
- alias :silence :capture
-
# Asserts a given file exists. You need to supply an absolute path or a path relative
# to the configured destination:
#
@@ -132,7 +114,7 @@ module Rails
end
alias :assert_no_directory :assert_no_file
- # Asserts a given file does not exist. You need to supply an absolute path or a
+ # Asserts a given migration exists. You need to supply an absolute path or a
# path relative to the configured destination:
#
# assert_migration "db/migrate/create_products.rb"
diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
index 0d4185846d..11a73ebad7 100644
--- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
@@ -1,5 +1,6 @@
require 'test_helper'
+<% module_namespacing do -%>
class <%= class_name %>ControllerTest < ActionController::TestCase
<% if actions.empty? -%>
# Replace this with your real tests.
@@ -16,3 +17,4 @@ class <%= class_name %>ControllerTest < ActionController::TestCase
<% 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
index 591e40900e..7d37bda0f9 100644
--- a/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb
+++ b/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb
@@ -1,4 +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/mailer/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
index 80ac7f0feb..b62c7fd279 100644
--- a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
@@ -1,5 +1,6 @@
require 'test_helper'
+<% module_namespacing do -%>
class <%= class_name %>Test < ActionMailer::TestCase
<% for action in actions -%>
test "<%= action %>" do
@@ -18,3 +19,4 @@ class <%= class_name %>Test < ActionMailer::TestCase
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
index a30132bc99..6465a6a6e2 100644
--- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
+++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
@@ -1,4 +1,4 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
<% unless attributes.empty? -%>
one:
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
index 3e0bc29d3a..6f79879838 100644
--- a/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
+++ b/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
@@ -1,8 +1,10 @@
require 'test_helper'
+<% module_namespacing do -%>
class <%= class_name %>Test < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
+<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb b/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb
index 03f6d5666e..cd116f5ce9 100644
--- a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb
+++ b/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb
@@ -1,8 +1,10 @@
require 'test_helper'
+<% module_namespacing do -%>
class <%= class_name %>ObserverTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
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
index f23e495450..964d59d84c 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
@@ -1,5 +1,6 @@
require 'test_helper'
+<% module_namespacing do -%>
class <%= controller_class_name %>ControllerTest < ActionController::TestCase
setup do
@<%= singular_table_name %> = <%= table_name %>(:one)
@@ -47,3 +48,4 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase
assert_redirected_to <%= index_helper %>_path
end
end
+<% end -%>
diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb
index 6cbd1f21c0..d05e031f56 100644
--- a/railties/lib/rails/info.rb
+++ b/railties/lib/rails/info.rb
@@ -1,5 +1,4 @@
require "cgi"
-require "active_support/core_ext/cgi"
module Rails
module Info
diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb
index 196eeb4a6c..6b4bdb2921 100644
--- a/railties/lib/rails/info_controller.rb
+++ b/railties/lib/rails/info_controller.rb
@@ -1,6 +1,6 @@
class Rails::InfoController < ActionController::Base
def properties
- if consider_all_requests_local? || local_request?
+ if consider_all_requests_local? || request.local?
render :inline => Rails::Info.to_html
else
render :text => '<p>For security purposes, this information is only available to local requests.</p>', :status => :forbidden
diff --git a/railties/lib/rails/info_routes.rb b/railties/lib/rails/info_routes.rb
deleted file mode 100644
index b5c4e4c1e0..0000000000
--- a/railties/lib/rails/info_routes.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-Rails.application.routes.draw do
- match '/rails/info/properties' => "rails/info#properties"
-end
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index d303212f52..d15887f561 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -2,15 +2,17 @@ require 'set'
module Rails
module Paths
- module PathParent
- attr_reader :children
-
+ module PathParent #:nodoc:
def method_missing(id, *args)
- name = id.to_s
+ match = id.to_s.match(/^(.*)=$/)
+ full = [@current, $1 || id].compact.join("/")
+
+ ActiveSupport::Deprecation.warn 'config.paths.app.controller API is deprecated in ' <<
+ 'favor of config.paths["app/controller"] API.'
- if name =~ /^(.*)=$/ || args.any?
- @children[$1 || name] = Path.new(@root, *args)
- elsif path = @children[name]
+ if match || args.any?
+ @root[full] = Path.new(@root, full, *args)
+ elsif path = @root[full]
path
else
super
@@ -18,22 +20,72 @@ module Rails
end
end
- class Root
+ # This object is an extended hash that behaves as root of the Rails::Paths 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
+ # 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 Path 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 array and allows you to easily add extra paths:
+ #
+ # path.is_a?(Array) #=> true
+ # path.inspect #=> ["app/controllers"]
+ #
+ # path << "lib/controllers"
+ # path.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"]
+ #
+ # #add also accepts the following options as argument: eager_load, autoload,
+ # autoload_once and glob.
+ #
+ # Finally, the Path object also provides a few helpers:
+ #
+ # root = Root.new
+ # root.path = "/rails"
+ # root.add "app/controllers"
+ #
+ # root["app/controllers"].expanded #=> ["/rails/app/controllers"]
+ # root["app/controllers"].existent #=> ["/rails/app/controllers"]
+ #
+ # Check the Path documentation for more information.
+ class Root < ::Hash
include PathParent
-
attr_accessor :path
def initialize(path)
raise if path.is_a?(Array)
- @children = {}
+ @current = nil
@path = path
@root = self
- @all_paths = []
+ super()
+ end
+
+ def []=(path, value)
+ value = Path.new(self, path, value) unless value.is_a?(Path)
+ super(path, value)
+ end
+
+ def add(path, options={})
+ with = options[:with] || path
+ self[path] = Path.new(self, path, with, options)
end
def all_paths
- @all_paths.uniq!
- @all_paths
+ values.tap { |v| v.uniq! }
end
def autoload_once
@@ -52,68 +104,54 @@ module Rails
filter_by(:load_path?)
end
- def push(*)
- raise "Application root can only have one physical path"
- end
-
- alias unshift push
- alias << push
- alias concat push
-
protected
def filter_by(constraint)
all = []
all_paths.each do |path|
if path.send(constraint)
- paths = path.paths
- paths -= path.children.values.map { |p| p.send(constraint) ? [] : p.paths }.flatten
+ paths = path.existent
+ paths -= path.children.map { |p| p.send(constraint) ? [] : p.existent }.flatten
all.concat(paths)
end
end
all.uniq!
- all.reject! { |p| !File.exists?(p) }
all
end
end
- class Path
- include PathParent, Enumerable
+ class Path < Array
+ include PathParent
attr_reader :path
attr_accessor :glob
- def initialize(root, *paths)
- options = paths.last.is_a?(::Hash) ? paths.pop : {}
- @children = {}
+ def initialize(root, current, *paths)
+ options = paths.last.is_a?(::Hash) ? paths.pop : {}
+ super(paths.flatten)
+
+ @current = current
@root = root
- @paths = paths.flatten
@glob = options[:glob]
- autoload_once! if options[:autoload_once]
- eager_load! if options[:eager_load]
- autoload! if options[:autoload]
- load_path! if options[:load_path]
-
- @root.all_paths << self
- end
-
- def each
- to_a.each { |p| yield p }
+ 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 push(path)
- @paths.push path
+ def children
+ keys = @root.keys.select { |k| k.include?(@current) }
+ keys.delete(@current)
+ @root.values_at(*keys.sort)
end
- alias << push
-
- def unshift(path)
- @paths.unshift path
+ def first
+ expanded.first
end
- def concat(paths)
- @paths.concat paths
+ def last
+ expanded.last
end
%w(autoload_once eager_load autoload load_path).each do |m|
@@ -132,20 +170,36 @@ module Rails
RUBY
end
- def paths
+ # 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 = []
- result = @paths.map do |p|
+ each do |p|
path = File.expand_path(p, @root.path)
- @glob ? Dir[File.join(path, @glob)] : path
+
+ if @glob
+ result.concat Dir[File.join(path, @glob)]
+ else
+ result << path
+ end
end
- result.flatten!
result.uniq!
result
end
- alias to_a paths
+ # Returns all expanded paths but only if they exist in the filesystem.
+ def existent
+ expanded.select { |f| File.exists?(f) }
+ end
+
+ def paths
+ ActiveSupport::Deprecation.warn "paths is deprecated. Please call expand instead."
+ expanded
+ end
+
+ alias to_a expanded
end
end
-end \ No newline at end of file
+end
diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb
index be229cc9a2..ceddd25eaa 100644
--- a/railties/lib/rails/plugin.rb
+++ b/railties/lib/rails/plugin.rb
@@ -16,8 +16,12 @@ module Rails
# Besides this conceptual difference, the only difference between Rails::Engine and
# Rails::Plugin is that plugins automatically load the file "init.rb" at the plugin
# root during the boot process.
- #
+ #
class Plugin < Engine
+ def self.global_plugins
+ @global_plugins ||= []
+ end
+
def self.inherited(base)
raise "You cannot inherit from Rails::Plugin"
end
@@ -28,6 +32,11 @@ module Rails
Dir["#{path}/*"].each do |plugin_path|
plugin = new(plugin_path)
next unless list.include?(plugin.name) || list.include?(:all)
+ if global_plugins.include?(plugin.name)
+ warn "WARNING: plugin #{plugin.name} from #{path} was not loaded. Plugin with the same name has been already loaded."
+ next
+ end
+ global_plugins << plugin.name
plugins << plugin
end
end
@@ -39,17 +48,8 @@ module Rails
attr_reader :name, :path
- def load_tasks
- super
- load_deprecated_tasks
- end
-
- def load_deprecated_tasks
- tasks = Dir["#{root}/{tasks,rails/tasks}/**/*.rake"].sort
- if tasks.any?
- ActiveSupport::Deprecation.warn "Rake tasks in #{tasks.to_sentence} are deprecated. Use lib/tasks instead"
- tasks.each { |ext| load(ext) }
- end
+ def railtie_name
+ name.to_s
end
def initialize(root)
@@ -62,29 +62,28 @@ module Rails
end
initializer :handle_lib_autoload, :before => :set_load_path do |app|
- paths = if app.config.reload_plugins
+ autoload = if app.config.reload_plugins
config.autoload_paths
else
config.autoload_once_paths
end
- paths.concat config.paths.lib.to_a
+ autoload.concat paths["lib"].existent
end
initializer :load_init_rb, :before => :load_config_initializers do |app|
- files = %w(rails/init.rb init.rb).map { |path| File.expand_path path, root }
- if initrb = files.find { |path| File.file? path }
- if initrb == files.first
- ActiveSupport::Deprecation.warn "Use toplevel init.rb; rails/init.rb is deprecated: #{initrb}"
- end
+ init_rb = File.expand_path("init.rb", root)
+ if File.file?(init_rb)
config = app.config
- eval(File.read(initrb), binding, initrb)
+ # TODO: think about evaling initrb in context of Engine (currently it's
+ # always evaled in context of Rails::Application)
+ eval(File.read(init_rb), binding, init_rb)
end
end
initializer :sanity_check_railties_collision do
if Engine.subclasses.map { |k| k.root.to_s }.include?(root.to_s)
- raise "\"#{name}\" is a Railtie/Engine and cannot be installed as plugin"
+ raise "\"#{name}\" is a Railtie/Engine and cannot be installed as a plugin"
end
end
end
diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb
index 011ac6cecc..830d840894 100644
--- a/railties/lib/rails/rack/log_tailer.rb
+++ b/railties/lib/rails/rack/log_tailer.rb
@@ -19,7 +19,7 @@ module Rails
def tail!
@file.seek @cursor
- if !@file.eof?
+ unless @file.eof?
contents = @file.read
@cursor = @file.tell
$stdout.print contents
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
index b3dc1f894c..3be262de08 100644
--- a/railties/lib/rails/rack/logger.rb
+++ b/railties/lib/rails/rack/logger.rb
@@ -19,9 +19,9 @@ module Rails
def before_dispatch(env)
request = ActionDispatch::Request.new(env)
- path = request.fullpath
+ path = request.filtered_path
- info "\n\nStarted #{env["REQUEST_METHOD"]} \"#{path}\" " \
+ info "\n\nStarted #{request.request_method} \"#{path}\" " \
"for #{request.ip} at #{Time.now.to_default_s}"
end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index 8a6e2716dc..7fca565124 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -1,58 +1,45 @@
require 'rails/initializable'
require 'rails/configuration'
require 'active_support/inflector'
-require 'active_support/deprecation'
module Rails
- # Railtie is the core of the Rails Framework and provides several hooks to extend
+ # Railtie is the core of the Rails framework and provides several hooks to extend
# Rails and/or modify the initialization process.
#
# Every major component of Rails (Action Mailer, Action Controller,
- # Action View, Active Record and Active Resource) are all Railties, so each of
- # them is responsible to set their own initialization. This makes, for example,
- # Rails absent of any Active Record hook, allowing any other ORM framework to hook in.
+ # Action View, Active Record and Active Resource) is a Railtie. Each of
+ # them is responsible for their own initialization. This makes Rails itself
+ # absent of any component hooks, allowing other components to be used in
+ # place of any of the Rails defaults.
#
# Developing a Rails extension does _not_ require any implementation of
# Railtie, but if you need to interact with the Rails framework during
- # or after boot, then Railtie is what you need to do that interaction.
+ # or after boot, then Railtie is needed.
#
- # For example, the following would need you to implement Railtie in your
- # plugin:
+ # For example, an extension doing any of the following would require Railtie:
#
# * creating initializers
- # * configuring a Rails framework or the Application, like setting a generator
- # * adding Rails config.* keys to the environment
- # * setting up a subscriber to the Rails +ActiveSupport::Notifications+
- # * adding rake tasks into rails
+ # * configuring a Rails framework for the application, like setting a generator
+ # * adding config.* keys to the environment
+ # * setting up a subscriber with ActiveSupport::Notifications
+ # * adding rake tasks
#
# == Creating your Railtie
#
- # Implementing Railtie in your Rails extension is done by creating a class
- # Railtie that has your extension name and making sure that this gets loaded
- # during boot time of the Rails stack.
+ # To extend Rails using Railtie, create a Railtie class which inherits
+ # from Rails::Railtie within your extension's namespace. This class must be
+ # loaded during the Rails boot process.
#
- # You can do this however you wish, but here is an example if you want to provide
- # it for a gem that can be used with or without Rails:
+ # The following example demonstrates an extension which can be used with or without Rails.
#
- # * Create a file (say, lib/my_gem/railtie.rb) which contains class Railtie inheriting from
- # Rails::Railtie and is namespaced to your gem:
- #
- # # lib/my_gem/railtie.rb
- # module MyGem
- # class Railtie < Rails::Railtie
- # end
+ # # lib/my_gem/railtie.rb
+ # module MyGem
+ # class Railtie < Rails::Railtie
# end
+ # end
#
- # * Require your own gem as well as rails in this file:
- #
- # # lib/my_gem/railtie.rb
- # require 'my_gem'
- # require 'rails'
- #
- # module MyGem
- # class Railtie < Rails::Railtie
- # end
- # end
+ # # lib/my_gem.rb
+ # require 'my_gem/railtie' if defined?(Rails)
#
# == Initializers
#
@@ -84,10 +71,10 @@ module Rails
#
# class MyRailtie < Rails::Railtie
# # Customize the ORM
- # config.generators.orm :my_railtie_orm
+ # config.app_generators.orm :my_railtie_orm
#
# # Add a to_prepare block which is executed once in production
- # # and before which request in development
+ # # and before each request in development
# config.to_prepare do
# MyRailtie.setup!
# end
@@ -98,7 +85,7 @@ module Rails
# If your railtie has rake tasks, you can tell Rails to load them through the method
# rake tasks:
#
- # class MyRailtie < Railtie
+ # class MyRailtie < Rails::Railtie
# rake_tasks do
# load "path/to/my_railtie.tasks"
# end
@@ -108,7 +95,7 @@ module Rails
# your generators at a different location, you can specify in your Railtie a block which
# will load them during normal generators lookup:
#
- # class MyRailtie < Railtie
+ # class MyRailtie < Rails::Railtie
# generators do
# require "path/to/my_railtie_generator"
# end
@@ -121,7 +108,7 @@ module Rails
# described here can be used in all three.
#
# 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"
@@ -131,25 +118,19 @@ module Rails
ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
class << self
+ private :new
+
def subclasses
@subclasses ||= []
end
def inherited(base)
unless base.abstract_railtie?
- base.send(:include, self::Configurable)
+ base.send(:include, Railtie::Configurable)
subclasses << base
end
end
- def railtie_name(*)
- ActiveSupport::Deprecation.warn "railtie_name is deprecated and has no effect", caller
- end
-
- def log_subscriber(*)
- ActiveSupport::Deprecation.warn "log_subscriber is deprecated and has no effect", caller
- end
-
def rake_tasks(&blk)
@rake_tasks ||= []
@rake_tasks << blk if blk
@@ -171,6 +152,22 @@ module Rails
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).gsub("/", "_")
+ end
+ end
+
+ delegate :railtie_name, :to => "self.class"
+
+ def config
+ @config ||= Railtie::Configuration.new
end
def eager_load!
@@ -182,6 +179,13 @@ module Rails
def load_tasks
self.class.rake_tasks.each(&:call)
+
+ # load also tasks from all superclasses
+ klass = self.class.superclass
+ while klass.respond_to?(:rake_tasks)
+ klass.rake_tasks.each { |t| self.instance_exec(&t) }
+ klass = klass.superclass
+ end
end
def load_generators
diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb
index a2eb938c5a..920ab67ff1 100644
--- a/railties/lib/rails/railtie/configurable.rb
+++ b/railties/lib/rails/railtie/configurable.rb
@@ -1,22 +1,32 @@
module Rails
class Railtie
module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
+ extend ActiveSupport::Concern
module ClassMethods
- def config
- @config ||= Railtie::Configuration.new
- end
+ delegate :config, :to => :instance
def inherited(base)
- raise "You cannot inherit from a Rails::Railtie child"
+ raise "You cannot inherit from a #{self.superclass.name} child"
end
- end
- def config
- self.class.config
+ 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
diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb
index 4e6f94c534..2c7b5bc048 100644
--- a/railties/lib/rails/railtie/configuration.rb
+++ b/railties/lib/rails/railtie/configuration.rb
@@ -16,47 +16,49 @@ module Rails
@@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new
end
- # Holds generators configuration:
+ # This allows you to modify application's generators from Railties.
#
- # config.generators do |g|
- # g.orm :datamapper, :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
- @@generators ||= Rails::Configuration::Generators.new
- if block_given?
- yield @@generators
- else
- @@generators
- end
+ # 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
+ def generators(&block) #:nodoc
+ ActiveSupport::Deprecation.warn "config.generators in Rails::Railtie is deprecated. Please use config.app_generators instead."
+ app_generators(&block)
+ 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
@@ -65,6 +67,13 @@ module Rails
super || @@options.key?(name.to_sym)
end
+ # static_asset_paths is a Hash containing asset_paths
+ # with associated public folders, like:
+ # { "/" => "/app/public", "/my_engine" => "app/engines/my_engine/public" }
+ def static_asset_paths
+ @@static_asset_paths ||= ActiveSupport::OrderedHash.new
+ end
+
private
def method_missing(name, *args, &blk)
@@ -78,4 +87,4 @@ module Rails
end
end
end
-end \ No newline at end of file
+end
diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb
index e8d1d1e039..4d57c5973c 100644
--- a/railties/lib/rails/ruby_version_check.rb
+++ b/railties/lib/rails/ruby_version_check.rb
@@ -14,8 +14,7 @@ elsif RUBY_VERSION > '1.9' and RUBY_VERSION < '1.9.2'
$stderr.puts <<-end_message
Rails 3 doesn't officially support Ruby 1.9.1 since recent stable
- releases have segfaulted the test suite. Please upgrade to Ruby 1.9.2
- before Rails 3 is released!
+ releases have segfaulted the test suite. Please upgrade to Ruby 1.9.2.
You're running
#{RUBY_DESCRIPTION}
diff --git a/railties/lib/rails/script_rails_loader.rb b/railties/lib/rails/script_rails_loader.rb
index 91672e5d81..7054089614 100644
--- a/railties/lib/rails/script_rails_loader.rb
+++ b/railties/lib/rails/script_rails_loader.rb
@@ -17,11 +17,11 @@ module Rails
rescue SystemCallError
# could not chdir, no problem just return
end
-
+
def self.in_rails_application?
File.exists?(SCRIPT_RAILS)
end
-
+
def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent)
end
diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb
index 9807000578..af52014728 100644
--- a/railties/lib/rails/tasks.rb
+++ b/railties/lib/rails/tasks.rb
@@ -11,6 +11,7 @@ $VERBOSE = nil
routes
statistics
tmp
+ railties
).each do |task|
load "rails/tasks/#{task}.rake"
end
diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake
index c1b1a41d48..edd716d7d0 100644
--- a/railties/lib/rails/tasks/documentation.rake
+++ b/railties/lib/rails/tasks/documentation.rake
@@ -4,15 +4,15 @@ require 'rake/rdoctask'
class RDocTaskWithoutDescriptions < Rake::RDocTask
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
@@ -47,7 +47,7 @@ namespace :doc do
rdoc.rdoc_files.include('app/**/*.rb')
rdoc.rdoc_files.include('lib/**/*.rb')
}
- Rake::Task['doc:app'].comment = "Generate docs for the app -- also availble doc:rails, doc:guides, doc:plugins (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
+ Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides, doc:plugins (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
# desc 'Generate documentation for the Rails framework.'
RDocTaskWithoutDescriptions.new("rails") { |rdoc|
diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake
new file mode 100644
index 0000000000..2f0e7be896
--- /dev/null
+++ b/railties/lib/rails/tasks/engine.rake
@@ -0,0 +1,69 @@
+task "load_app" do
+ namespace :app do
+ load APP_RAKEFILE
+ end
+
+ if !defined?(ENGINE_PATH) || !ENGINE_PATH
+ ENGINE_PATH = find_engine_path(APP_RAKEFILE)
+ end
+end
+
+def app_task(name)
+ task name => [:load_app, "app:db:#{name}"]
+end
+
+namespace :db do
+ app_task "reset"
+
+ desc "Migrate the database (options: VERSION=x, VERBOSE=false)."
+ app_task "migrate"
+ app_task "migrate:up"
+ app_task "migrate:down"
+ app_task "migrate:redo"
+ app_task "migrate:reset"
+
+ desc "Display status of migrations"
+ app_task "migrate:status"
+
+ desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
+ app_task "create"
+ app_task "create:all"
+
+ desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
+ app_task "drop"
+ app_task "drop:all"
+
+ desc "Load fixtures into the current environment's database."
+ app_task "fixtures:load"
+
+ desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)."
+ app_task "rollback"
+
+ desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
+ app_task "schema:dump"
+
+ desc "Load a schema.rb file into the database"
+ app_task "schema:load"
+
+ desc "Load the seed data from db/seeds.rb"
+ app_task "seed"
+
+ desc "Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)"
+ app_task "setup"
+
+ desc "Dump the database structure to an SQL file"
+ app_task "structure:dump"
+
+ desc "Retrieves the current schema version number"
+ app_task "version"
+end
+
+def find_engine_path(path)
+ return if path == "/"
+
+ if Rails::Engine.find(path)
+ path
+ else
+ find_engine_path(File.expand_path('..', path))
+ end
+end
diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake
index 443dacd739..5222b7bf50 100644
--- a/railties/lib/rails/tasks/framework.rake
+++ b/railties/lib/rails/tasks/framework.rake
@@ -1,21 +1,4 @@
namespace :rails do
- namespace :freeze do
- # desc "The rails:freeze:gems is deprecated, please use bundle install instead"
- task :gems do
- abort "The rails:freeze:gems is deprecated, please use bundle install instead"
- end
-
- # desc 'The freeze:edge command has been deprecated, specify the path setting in your app Gemfile instead and bundle install'
- task :edge do
- abort 'The freeze:edge command has been deprecated, specify the path setting in your app Gemfile instead and bundle install'
- end
- end
-
- # desc 'The unfreeze command has been deprecated, please use bundler commands instead'
- task :unfreeze do
- abort 'The unfreeze command has been deprecated, please use bundler commands instead'
- end
-
desc "Update both configs and public/javascripts from Rails (or use just update:javascripts or update:configs)"
task :update => [ "update:configs", "update:javascripts", "update:scripts", "update:application_controller" ]
@@ -77,7 +60,7 @@ namespace :rails do
# desc "Update Prototype javascripts from your current rails install"
task :javascripts do
- invoke_from_app_generator :create_prototype_files
+ invoke_from_app_generator :create_javascript_files
end
# desc "Adds new scripts to the application script/ directory"
diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake
index c6c22d83bf..e505b8c338 100644
--- a/railties/lib/rails/tasks/misc.rake
+++ b/railties/lib/rails/tasks/misc.rake
@@ -7,7 +7,7 @@ task :rails_env do
end
end
-desc 'Generate a crytographically secure secret key (this is typically used to generate a secret for cookie sessions).'
+desc 'Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions).'
task :secret do
require 'active_support/secure_random'
puts ActiveSupport::SecureRandom.hex(64)
diff --git a/railties/lib/rails/tasks/railties.rake b/railties/lib/rails/tasks/railties.rake
new file mode 100644
index 0000000000..16703879cf
--- /dev/null
+++ b/railties/lib/rails/tasks/railties.rake
@@ -0,0 +1,29 @@
+namespace :railties do
+ namespace :install do
+ # desc "Copies missing assets from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2"
+ task :assets => :rails_env do
+ require 'rails/generators/base'
+ Rails.application.initialize!
+
+ to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map {|n| n.strip }
+ app_public_path = Rails.application.paths["public"].first
+
+ Rails.application.railties.all do |railtie|
+ next unless to_load == :all || to_load.include?(railtie.railtie_name)
+
+ if railtie.respond_to?(:paths) && (path = railtie.paths["public"].first) &&
+ (assets_dir = railtie.config.compiled_asset_path) && File.exist?(path)
+
+ Rails::Generators::Base.source_root(path)
+ copier = Rails::Generators::Base.new
+ Dir[File.join(path, "**/*")].each do |file|
+ relative = file.gsub(/^#{path}\//, '')
+ if File.file?(file)
+ copier.copy_file relative, File.join(app_public_path, assets_dir, relative)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake
index a99232c4be..02e22361e0 100644
--- a/railties/lib/rails/tasks/routes.rake
+++ b/railties/lib/rails/tasks/routes.rake
@@ -1,20 +1,27 @@
desc 'Print out all defined routes in match order, with names. Target specific controller with CONTROLLER=x.'
task :routes => :environment do
Rails.application.reload_routes!
- all_routes = ENV['CONTROLLER'] ? Rails.application.routes.routes.select { |route| route.defaults[:controller] == ENV['CONTROLLER'] } : Rails.application.routes.routes
+ all_routes = Rails.application.routes.routes
+
+ if ENV['CONTROLLER']
+ all_routes = all_routes.select{ |route| route.defaults[:controller] == ENV['CONTROLLER'] }
+ end
+
routes = all_routes.collect do |route|
- # TODO: The :index method is deprecated in 1.9 in favor of :key
- # but we don't have :key in 1.8.7. We can remove this check when
- # stop supporting 1.8.x
- key_method = Hash.method_defined?('key') ? 'key' : 'index'
- name = Rails.application.routes.named_routes.routes.send(key_method, route).to_s
- reqs = route.requirements.empty? ? "" : route.requirements.inspect
- {:name => name, :verb => route.verb.to_s, :path => route.path, :reqs => reqs}
+
+ reqs = route.requirements.dup
+ reqs[:to] = route.app unless route.app.class.name.to_s =~ /^ActionDispatch::Routing/
+ reqs = reqs.empty? ? "" : reqs.inspect
+
+ {:name => route.name.to_s, :verb => route.verb.to_s, :path => route.path, :reqs => reqs}
end
- routes.reject!{ |r| r[:path] == "/rails/info/properties" } # skip the route if it's internal info route
- name_width = routes.collect {|r| r[:name]}.collect {|n| n.length}.max
- verb_width = routes.collect {|r| r[:verb]}.collect {|v| v.length}.max
- path_width = routes.collect {|r| r[:path]}.collect {|s| s.length}.max
+
+ routes.reject! { |r| r[:path] =~ %r{/rails/info/properties} } # Skip the route if it's internal info route
+
+ name_width = routes.map{ |r| r[:name].length }.max
+ verb_width = routes.map{ |r| r[:verb].length }.max
+ path_width = routes.map{ |r| r[:path].length }.max
+
routes.each do |r|
puts "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
end
diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb
index ec5e4a357c..00029e627e 100644
--- a/railties/lib/rails/test_help.rb
+++ b/railties/lib/rails/test_help.rb
@@ -1,6 +1,6 @@
-# Make double-sure the RAILS_ENV is set to test,
-# so fixtures are loaded to the right database
-abort("Abort testing: Your Rails environment is not running in test mode!") unless Rails.env.test?
+# 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 'test/unit'
require 'active_support/core_ext/kernel/requires'
@@ -19,9 +19,13 @@ if defined?(ActiveRecord)
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
self.fixture_path = "#{Rails.root}/test/fixtures/"
+
+ setup do
+ ActiveRecord::IdentityMap.clear
+ end
end
- ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
+ ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
def create_fixtures(*table_names, &block)
Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
@@ -39,14 +43,3 @@ class ActionDispatch::IntegrationTest
@routes = Rails.application.routes
end
end
-
-begin
- require_library_or_gem 'ruby-debug'
- Debugger.start
- if Debugger.respond_to?(:settings)
- Debugger.settings[:autoeval] = true
- Debugger.settings[:autolist] = 1
- end
-rescue LoadError
- # ruby-debug wasn't available so neither can the debugging be
-end
diff --git a/railties/lib/rails/test_unit/railtie.rb b/railties/lib/rails/test_unit/railtie.rb
index e3fafc4b9d..2b6170ebfb 100644
--- a/railties/lib/rails/test_unit/railtie.rb
+++ b/railties/lib/rails/test_unit/railtie.rb
@@ -1,6 +1,6 @@
module Rails
class TestUnitRailtie < Rails::Railtie
- config.generators do |c|
+ config.app_generators do |c|
c.test_framework :test_unit, :fixture => true,
:fixture_replacement => nil
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index 38c14fcd6b..28dc40379b 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -1,3 +1,4 @@
+require 'rbconfig'
require 'rake/testtask'
# Monkey-patch to silence the description from Rake::TestTask to cut down on rake -T noise
@@ -62,7 +63,7 @@ end
module Kernel
def silence_stderr
old_stderr = STDERR.dup
- STDERR.reopen(Config::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
+ STDERR.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
STDERR.sync = true
yield
ensure
@@ -72,7 +73,8 @@ end
desc 'Runs test:units, test:functionals, test:integration together (also available: test:benchmark, test:profile, test:plugins)'
task :test do
- errors = %w(test:units test:functionals test:integration).collect do |task|
+ tests_to_run = ENV['TEST'] ? ["test:single"] : %w(test:units test:functionals test:integration)
+ errors = tests_to_run.collect do |task|
begin
Rake::Task[task].invoke
nil
@@ -122,6 +124,10 @@ namespace :test do
end
Rake::Task['test:uncommitted'].comment = "Test changes since last checkin (only Subversion and Git)"
+ Rake::TestTask.new(:single => "test:prepare") do |t|
+ t.libs << "test"
+ end
+
TestTaskWithoutDescription.new(:units => "test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/unit/**/*_test.rb'
diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb
index c5d1d02bc1..b076881c21 100644
--- a/railties/lib/rails/version.rb
+++ b/railties/lib/rails/version.rb
@@ -1,10 +1,10 @@
module Rails
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
index d76b74190b..c3793d3ac3 100644
--- a/railties/railties.gemspec
+++ b/railties/railties.gemspec
@@ -19,8 +19,8 @@ Gem::Specification.new do |s|
s.rdoc_options << '--exclude' << '.'
s.has_rdoc = false
- s.add_dependency('rake', '>= 0.8.3')
- s.add_dependency('thor', '~> 0.14.0')
+ s.add_dependency('rake', '>= 0.8.7')
+ s.add_dependency('thor', '~> 0.14.4')
s.add_dependency('activesupport', version)
s.add_dependency('actionpack', version)
end
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index a05bae5dcc..8b38081667 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -11,7 +11,8 @@ require 'action_controller'
require 'rails/all'
# TODO: Remove these hacks
-class TestApp < Rails::Application
- config.root = File.dirname(__FILE__)
+module TestApp
+ class Application < Rails::Application
+ config.root = File.dirname(__FILE__)
+ end
end
-Rails.application = TestApp
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 9928ee2c52..044fd2a278 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -26,24 +26,23 @@ module ApplicationTests
FileUtils.rm_rf(new_app) if File.directory?(new_app)
end
- test "Rails::Application.instance is nil until app is initialized" do
+ test "Rails.application is nil until app is initialized" do
require 'rails'
- assert_nil Rails::Application.instance
+ assert_nil Rails.application
require "#{app_path}/config/environment"
- assert_equal AppTemplate::Application.instance, Rails::Application.instance
+ assert_equal AppTemplate::Application.instance, Rails.application
end
- test "Rails::Application responds to all instance methods" do
+ 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, Rails.application.routes_reloader
- assert_equal Rails::Application.routes_reloader, AppTemplate::Application.routes_reloader
+ 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.to_a, ["#{app_path}/app/views"]
+ assert_equal AppTemplate::Application.paths["app/views"].expanded, ["#{app_path}/app/views"]
end
test "the application root is set correctly" do
@@ -96,6 +95,11 @@ module ApplicationTests
assert AppTemplate::Application.config.allow_concurrency
end
+ test "asset_path defaults to nil for application" do
+ require "#{app_path}/config/environment"
+ assert_equal nil, AppTemplate::Application.config.asset_path
+ end
+
test "the application can be marked as threadsafe when there are no frameworks" do
FileUtils.rm_rf("#{app_path}/config/environments")
add_to_config <<-RUBY
@@ -125,22 +129,6 @@ module ApplicationTests
assert !ActionController.autoload?(:RecordIdentifier)
end
- test "runtime error is raised if config.frameworks= is used" do
- add_to_config "config.frameworks = []"
-
- assert_raises RuntimeError do
- require "#{app_path}/config/environment"
- end
- end
-
- test "runtime error is raised if config.frameworks is used" do
- add_to_config "config.frameworks -= []"
-
- assert_raises RuntimeError do
- require "#{app_path}/config/environment"
- 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|
@@ -172,22 +160,32 @@ module ApplicationTests
assert $prepared
end
+ def assert_utf8
+ if RUBY_VERSION < '1.9'
+ assert_equal "UTF8", $KCODE
+ else
+ assert_equal Encoding::UTF_8, Encoding.default_external
+ assert_equal Encoding::UTF_8, Encoding.default_internal
+ end
+ 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"
-
- unless RUBY_VERSION < '1.9'
- assert_equal Encoding::UTF_8, Encoding.default_external
- assert_equal Encoding::UTF_8, Encoding.default_internal
- end
+ assert_utf8
end
test "config.paths.public sets Rails.public_path" do
add_to_config <<-RUBY
- config.paths.public = "somewhere"
+ config.paths["public"] = "somewhere"
RUBY
require "#{app_path}/config/application"
@@ -218,7 +216,7 @@ module ApplicationTests
protect_from_forgery
def index
- render :inline => "<%= csrf_meta_tag %>"
+ render :inline => "<%= csrf_meta_tags %>"
end
end
@@ -267,5 +265,73 @@ module ApplicationTests
get "/"
assert_not_equal res, last_response.body
end
+
+ test "config.asset_path is not passed through env" do
+ make_basic_app do |app|
+ app.config.asset_path = "/omg%s"
+ end
+
+ class ::OmgController < ActionController::Base
+ def index
+ render :inline => "<%= image_path('foo.jpg') %>"
+ end
+ end
+
+ get "/"
+ assert_equal "/omg/images/foo.jpg", last_response.body
+ end
+
+ test "config.action_view.cache_template_loading with cache_classes default" do
+ add_to_config "config.cache_classes = true"
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading without cache_classes default" do
+ add_to_config "config.cache_classes = false"
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert !ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading = false" do
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ config.action_view.cache_template_loading = false
+ RUBY
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert !ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading = true" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ config.action_view.cache_template_loading = true
+ RUBY
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert ActionView::Resolver.caching?
+ end
+
+ test "config.action_dispatch.show_exceptions is sent in env" do
+ make_basic_app do |app|
+ app.config.action_dispatch.show_exceptions = true
+ end
+
+ class ::OmgController < ActionController::Base
+ def index
+ render :text => env["action_dispatch.show_exceptions"]
+ end
+ end
+
+ get "/"
+ assert_equal 'true', last_response.body
+ end
end
end
diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb
index a72e6916dd..793e73556c 100644
--- a/railties/test/application/console_test.rb
+++ b/railties/test/application/console_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
class ConsoleTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
+ include ActiveSupport::Testing::Isolation
def setup
build_app
@@ -14,27 +14,26 @@ class ConsoleTest < Test::Unit::TestCase
end
def test_app_method_should_return_integration_session
+ TestHelpers::Rack.send :remove_method, :app
load_environment
console_session = app
- assert_not_nil console_session
- assert_instance_of ActionController::Integration::Session, console_session
+ assert_instance_of ActionDispatch::Integration::Session, console_session
end
def test_new_session_should_return_integration_session
load_environment
session = new_session
- assert_not_nil session
- assert_instance_of ActionController::Integration::Session, session
+ assert_instance_of ActionDispatch::Integration::Session, session
end
- def test_reload_should_fire_preparation_callbacks
+ def test_reload_should_fire_preparation_and_cleanup_callbacks
load_environment
a = b = c = nil
# TODO: These should be defined on the initializer
- ActionDispatch::Callbacks.to_prepare { a = b = c = 1 }
- ActionDispatch::Callbacks.to_prepare { b = c = 2 }
- ActionDispatch::Callbacks.to_prepare { c = 3 }
+ ActionDispatch::Reloader.to_cleanup { a = b = c = 1 }
+ ActionDispatch::Reloader.to_cleanup { b = c = 2 }
+ ActionDispatch::Reloader.to_prepare { c = 3 }
# Hide Reloading... output
silence_stream(STDOUT) { reload! }
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
index d258625f42..8b840fffd0 100644
--- a/railties/test/application/generators_test.rb
+++ b/railties/test/application/generators_test.rb
@@ -25,6 +25,11 @@ module ApplicationTests
yield app_const.config
end
+ test "allow running plugin new generator inside Rails app directory" do
+ FileUtils.cd(rails_root){ `ruby script/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)
@@ -69,7 +74,7 @@ module ApplicationTests
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 ["#{app_path}/lib/templates", "some/where"], Rails::Generators.templates_path
+ assert_equal ["some/where"], Rails::Generators.templates_path
end
test "generators no color on initialization" do
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
index d8e916f45f..19311a7fa0 100644
--- a/railties/test/application/initializers/frameworks_test.rb
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class FrameworlsTest < Test::Unit::TestCase
+ class FrameworksTest < Test::Unit::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -61,9 +61,77 @@ module ApplicationTests
require "#{app_path}/config/environment"
assert Foo.method_defined?(:foo_path)
+ assert Foo.method_defined?(:main_app)
assert_equal ["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
+ match "/: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
+
# AS
test "if there's no config.active_support.bare, all of ActiveSupport is required" do
use_frameworks []
@@ -98,17 +166,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
- expects = [ActiveRecord::QueryCache, ActiveRecord::SessionStore]
- middleware = Rails.application.config.middleware.map { |m| m.klass }
- assert_equal expects, middleware & expects
- end
-
- test "database middleware initializes when allow concurrency is true" do
- add_to_config "config.threadsafe!"
-
- require "#{app_path}/config/environment"
-
- expects = [ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache]
+ expects = [ActiveRecord::IdentityMap::Middleware, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActiveRecord::SessionStore]
middleware = Rails.application.config.middleware.map { |m| m.klass }
assert_equal expects, middleware & expects
end
diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb
index 4baa8a8170..390f65ab5c 100644
--- a/railties/test/application/initializers/i18n_test.rb
+++ b/railties/test/application/initializers/i18n_test.rb
@@ -63,6 +63,36 @@ module ApplicationTests
assert I18n.load_path.include?("#{app_path}/config/another_locale.yml")
end
+ test "load_path is populated before eager loaded models" do
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ RUBY
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "1"
+ YAML
+
+ app_file 'app/models/foo.rb', <<-RUBY
+ class Foo < ActiveRecord::Base
+ @foo = I18n.t(:foo)
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] }
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+ load_app
+
+ get "/i18n"
+ assert_equal "1", last_response.body
+ end
+
test "locales are reloaded if they change between requests" do
add_to_config <<-RUBY
config.cache_classes = false
@@ -74,7 +104,7 @@ en:
YAML
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] }
end
RUBY
@@ -147,4 +177,4 @@ en:
assert_fallbacks :ca => [:ca, :"es-ES", :es, :'en-US', :en]
end
end
-end \ No newline at end of file
+end
diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb
index 340ce67511..c340465e87 100644
--- a/railties/test/application/loading_test.rb
+++ b/railties/test/application/loading_test.rb
@@ -18,10 +18,10 @@ class LoadingTest < Test::Unit::TestCase
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
@@ -42,6 +42,23 @@ class LoadingTest < Test::Unit::TestCase
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
+
def test_descendants_are_cleaned_on_each_request_without_cache_classes
add_to_config <<-RUBY
config.cache_classes = false
@@ -53,7 +70,7 @@ class LoadingTest < Test::Unit::TestCase
MODEL
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match '/load', :to => lambda { |env| [200, {}, Post.all] }
match '/unload', :to => lambda { |env| [200, {}, []] }
end
@@ -72,8 +89,13 @@ class LoadingTest < Test::Unit::TestCase
assert_equal [], ActiveRecord::Base.descendants
end
+ test "initialize_cant_be_called_twice" do
+ require "#{app_path}/config/environment"
+ assert_raise(RuntimeError) { ::AppTemplate::Application.initialize! }
+ end
+
protected
-
+
def setup_ar!
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
diff --git a/railties/test/application/middleware/best_practices_test.rb b/railties/test/application/middleware/best_practices_test.rb
new file mode 100644
index 0000000000..5b722e7510
--- /dev/null
+++ b/railties/test/application/middleware/best_practices_test.rb
@@ -0,0 +1,26 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class BestPracticesTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+ simple_controller
+ end
+
+ test "simple controller in production mode returns best standards" do
+ get '/foo'
+ assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"]
+ end
+
+ test "simple controller in development mode leaves out Chrome" do
+ app("development")
+ get "/foo"
+ assert_equal "IE=Edge", last_response.headers["X-UA-Compatible"]
+ 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 0000000000..f582ed0e42
--- /dev/null
+++ b/railties/test/application/middleware/cache_test.rb
@@ -0,0 +1,150 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class RoutingTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+ end
+
+ def simple_controller
+ controller :expires, <<-RUBY
+ class ExpiresController < ApplicationController
+ def expires_header
+ expires_in 10, :public => !params[:private]
+ render :text => ActiveSupport::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
+ private
+ def render_conditionally(headers)
+ if stale?(headers.merge(:public => !params[:private]))
+ render :text => ActiveSupport::SecureRandom.hex(16)
+ end
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match ':controller(/:action)'
+ end
+ RUBY
+ 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
+
+ get "/expires/expires_header"
+ assert_equal "miss, 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
+
+ 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
+
+ get "/expires/expires_etag"
+ assert_equal "miss, 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
+
+ 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
+
+ get "/expires/expires_last_modified"
+ assert_equal "miss, 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
+
+ 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/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb
new file mode 100644
index 0000000000..f28302d70a
--- /dev/null
+++ b/railties/test/application/middleware/remote_ip_test.rb
@@ -0,0 +1,63 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class RemoteIpTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ def remote_ip(env = {})
+ remote_ip = nil
+ env = Rack::MockRequest.env_for("/").merge(env).merge!(
+ 'action_dispatch.show_exceptions' => false,
+ 'action_dispatch.secret_token' => '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.2", 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 0000000000..0128261cd4
--- /dev/null
+++ b/railties/test/application/middleware/sendfile_test.rb
@@ -0,0 +1,56 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class SendfileTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ 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 ''" do
+ make_basic_app
+ simple_controller
+
+ get "/"
+ 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
+ end
+end
diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb
new file mode 100644
index 0000000000..5487e41e0a
--- /dev/null
+++ b/railties/test/application/middleware/show_exceptions_test.rb
@@ -0,0 +1,37 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class ShowExceptionsTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ test "unspecified route when set action_dispatch.show_exceptions to false" do
+ make_basic_app do |app|
+ app.config.action_dispatch.show_exceptions = false
+ end
+
+ assert_raise(ActionController::RoutingError) do
+ get '/foo'
+ end
+ end
+
+ test "unspecified route when set action_dispatch.show_exceptions to true" do
+ make_basic_app do |app|
+ app.config.action_dispatch.show_exceptions = true
+ end
+
+ assert_nothing_raised(ActionController::RoutingError) do
+ get '/foo'
+ end
+ end
+ end
+end
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index 1f127cee78..b314832685 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -27,7 +27,10 @@ module ApplicationTests
"ActionDispatch::ShowExceptions",
"ActionDispatch::RemoteIp",
"Rack::Sendfile",
+ "ActionDispatch::Reloader",
"ActionDispatch::Callbacks",
+ "ActiveRecord::IdentityMap::Middleware",
+ "ActiveRecord::ConnectionAdapters::ConnectionManagement",
"ActiveRecord::QueryCache",
"ActionDispatch::Cookies",
"ActionDispatch::Session::CookieStore",
@@ -35,15 +38,26 @@ module ApplicationTests
"ActionDispatch::ParamsParser",
"Rack::MethodOverride",
"ActionDispatch::Head",
+ "Rack::ConditionalGet",
+ "Rack::ETag",
"ActionDispatch::BestStandardsSupport"
], middleware
end
+ test "Rack::Cache is present when action_controller.perform_caching is set" do
+ add_to_config "config.action_controller.perform_caching = true"
+
+ boot!
+
+ assert_equal "Rack::Cache", middleware.first
+ end
+
test "removing Active Record omits its middleware" do
use_frameworks []
boot!
assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement")
assert !middleware.include?("ActiveRecord::QueryCache")
+ assert !middleware.include?("ActiveRecord::IdentityMap::Middleware")
end
test "removes lock if allow concurrency is set" do
@@ -64,10 +78,16 @@ module ApplicationTests
assert !middleware.include?("ActionDispatch::Static")
end
- test "removes show exceptions if action_dispatch.show_exceptions is disabled" do
+ test "includes show exceptions even action_dispatch.show_exceptions is disabled" do
add_to_config "config.action_dispatch.show_exceptions = false"
boot!
- assert !middleware.include?("ActionDispatch::ShowExceptions")
+ assert middleware.include?("ActionDispatch::ShowExceptions")
+ end
+
+ test "removes ActionDispatch::Reloader if cache_classes is true" do
+ add_to_config "config.cache_classes = true"
+ boot!
+ assert !middleware.include?("ActionDispatch::Reloader")
end
test "use middleware" do
@@ -94,87 +114,57 @@ module ApplicationTests
assert_equal "Rack::Runtime", middleware.fourth
end
+ test "identity map is inserted" do
+ boot!
+ assert middleware.include?("ActiveRecord::IdentityMap::Middleware")
+ end
+
test "insert middleware before" do
add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config"
boot!
assert_equal "Rack::Config", middleware.first
end
- # x_sendfile_header middleware
- test "config.action_dispatch.x_sendfile_header defaults to ''" do
+ # ConditionalGet + Etag
+ test "conditional get + etag middlewares handle http caching based on body" do
make_basic_app
class ::OmgController < ActionController::Base
def index
- send_file __FILE__
+ if params[:nothing]
+ render :text => ""
+ else
+ render :text => "OMG"
+ end
end
end
- get "/"
- 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
-
- class ::OmgController < ActionController::Base
- def index
- send_file __FILE__
- end
- end
+ etag = "5af83e3196bf99f440f31f2e1a6c9afe".inspect
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
-
- class ::OmgController < ActionController::Base
- def index
- send_file __FILE__
- end
- end
-
- get "/"
- assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"]
- end
-
- # remote_ip tests
- 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.2", 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
-
+ 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"
+ puts last_response.body
+ 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
+
+ # Show exceptions middleware
test "show exceptions middleware filter backtrace before logging" do
my_middleware = Struct.new(:app) do
def call(env)
@@ -203,21 +193,5 @@ module ApplicationTests
def middleware
AppTemplate::Application.middleware.map(&:klass).map(&:name)
end
-
- def remote_ip(env = {})
- remote_ip = nil
- env = Rack::MockRequest.env_for("/").merge(env).merge!(
- 'action_dispatch.show_exceptions' => false,
- 'action_dispatch.secret_token' => '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
end
end
diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb
index c98b11556b..b1ff6e9cb1 100644
--- a/railties/test/application/paths_test.rb
+++ b/railties/test/application/paths_test.rb
@@ -25,7 +25,7 @@ module ApplicationTests
end
def assert_path(paths, *dir)
- assert_equal [root(*dir)], paths.paths
+ assert_equal [root(*dir)], paths.expanded
end
def assert_in_load_path(*path)
@@ -37,20 +37,20 @@ module ApplicationTests
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.vendor.plugins, "vendor", "plugins"
- assert_path @paths.tmp, "tmp"
- assert_path @paths.tmp.cache, "tmp", "cache"
- 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_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["vendor/plugins"], "vendor/plugins"
+ assert_path @paths["tmp"], "tmp"
+ assert_path @paths["tmp/cache"], "tmp/cache"
+ 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.to_a.first
+ assert_equal root("app", "controllers"), @paths["app/controllers"].expanded.first
end
test "booting up Rails yields a list of paths that are eager" do
diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb
index 863950c04f..b0a9925890 100644
--- a/railties/test/application/rackup_test.rb
+++ b/railties/test/application/rackup_test.rb
@@ -31,13 +31,6 @@ module ApplicationTests
assert_kind_of Rails::Application, Rails.application
end
- # Passenger still uses AC::Dispatcher, so we need to
- # keep it working for now
- test "deprecated ActionController::Dispatcher still works" do
- rackup
- assert_kind_of Rails::Application, ActionController::Dispatcher.new
- end
-
test "the config object is available on the application object" do
rackup
assert_equal 'UTC', Rails.application.config.time_zone
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index d6e100ffe3..59e5ef4dee 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -14,7 +14,7 @@ module ApplicationTests
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
@@ -33,5 +33,71 @@ module ApplicationTests
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_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_routes_output_strips_anchors_from_http_verbs
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/cart', :to => 'cart#show'
+ end
+ RUBY
+ assert_match 'cart GET /cart(.:format)', Dir.chdir(app_path){ `rake routes` }
+ end
+
+ def test_model_and_migration_generator_with_change_syntax
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate migration add_email_to_users email:string`
+ end
+
+ output = Dir.chdir(app_path){ `rake db:migrate` }
+ assert_match /create_table\(:users\)/, output
+ assert_match /CreateUsers: migrated/, output
+ assert_match /add_column\(:users, :email, :string\)/, output
+ assert_match /AddEmailToUsers: migrated/, output
+
+ output = Dir.chdir(app_path){ `rake db:rollback STEP=2` }
+ assert_match /drop_table\("users"\)/, output
+ assert_match /CreateUsers: reverted/, output
+ assert_match /remove_column\("users", :email\)/, output
+ assert_match /AddEmailToUsers: reverted/, output
+ end
+
+ def test_loading_specific_fixtures
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate model product name:string`
+ `rake db:migrate`
+ end
+
+ require "#{rails_root}/config/environment"
+
+ # loading a specific fixture
+ errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` }
+ assert $?.success?, errormsg
+
+ assert_equal 2, ::AppTemplate::Application::Product.count
+ assert_equal 0, ::AppTemplate::Application::User.count
+ end
end
-end \ No newline at end of file
+end
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index febc53bac9..62589c998d 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -11,34 +11,6 @@ module ApplicationTests
extend Rack::Test::Methods
end
- 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 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 |map|
- match ':controller(/:action)'
- end
- RUBY
- end
-
test "rails/info/properties in development" do
app("development")
get "/rails/info/properties"
@@ -58,21 +30,6 @@ module ApplicationTests
assert_equal 'foo', last_response.body
end
- test "simple controller in production mode returns best standards" do
- simple_controller
-
- get '/foo'
- assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"]
- end
-
- test "simple controller in development mode leaves out Chrome" do
- simple_controller
- app("development")
-
- get "/foo"
- assert_equal "IE=Edge", last_response.headers["X-UA-Compatible"]
- end
-
test "simple controller with helper" do
controller :foo, <<-RUBY
class FooController < ApplicationController
@@ -91,7 +48,7 @@ module ApplicationTests
RUBY
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match ':controller(/:action)'
end
RUBY
@@ -102,7 +59,7 @@ module ApplicationTests
test "mount rack app" do
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ 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.
@@ -132,7 +89,7 @@ module ApplicationTests
RUBY
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match ':controller(/:action)'
end
RUBY
@@ -164,7 +121,7 @@ module ApplicationTests
RUBY
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match 'admin/foo', :to => 'admin/foo#index'
match 'foo', :to => 'foo#index'
end
@@ -177,6 +134,34 @@ module ApplicationTests
assert_equal 'admin::foo', last_response.body
end
+ test "routes appending blocks" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match ':controller#:action'
+ end
+ RUBY
+
+ add_to_config <<-R
+ routes.append do
+ match '/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
+ match '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
@@ -192,7 +177,7 @@ module ApplicationTests
RUBY
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match 'foo', :to => 'foo#bar'
end
RUBY
@@ -203,7 +188,7 @@ module ApplicationTests
assert_equal 'bar', last_response.body
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match 'foo', :to => 'foo#baz'
end
RUBY
@@ -215,7 +200,32 @@ module ApplicationTests
end
end
- test 'resource routing with irrigular inflection' do
+ 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
+ match '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
+
+ test 'resource routing with irregular inflection' do
app_file 'config/initializers/inflection.rb', <<-RUBY
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'yazi', 'yazilar'
@@ -223,7 +233,7 @@ module ApplicationTests
RUBY
app_file 'config/routes.rb', <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
resources :yazilar
end
RUBY
diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb
index 07a3d94120..292d1e247f 100644
--- a/railties/test/application/runner_test.rb
+++ b/railties/test/application/runner_test.rb
@@ -18,6 +18,10 @@ module ApplicationTests
MODEL
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
diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb
index de316a6fd0..1fbbb40132 100644
--- a/railties/test/application/test_test.rb
+++ b/railties/test/application/test_test.rb
@@ -53,7 +53,7 @@ module ApplicationTests
app_file 'test/integration/posts_test.rb', <<-RUBY
require 'test_helper'
- class PostsTest < ActionController::IntegrationTest
+ class PostsTest < ActionDispatch::IntegrationTest
def test_index
get '/posts'
assert_response :success
diff --git a/railties/test/fixtures/lib/empty_builder.rb b/railties/test/fixtures/lib/app_builders/empty_builder.rb
index babd9c2461..babd9c2461 100644
--- a/railties/test/fixtures/lib/empty_builder.rb
+++ b/railties/test/fixtures/lib/app_builders/empty_builder.rb
diff --git a/railties/test/fixtures/lib/app_builders/simple_builder.rb b/railties/test/fixtures/lib/app_builders/simple_builder.rb
new file mode 100644
index 0000000000..993d3a2aa2
--- /dev/null
+++ b/railties/test/fixtures/lib/app_builders/simple_builder.rb
@@ -0,0 +1,7 @@
+class AppBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
diff --git a/railties/test/fixtures/lib/app_builders/tweak_builder.rb b/railties/test/fixtures/lib/app_builders/tweak_builder.rb
new file mode 100644
index 0000000000..cb50be01cb
--- /dev/null
+++ b/railties/test/fixtures/lib/app_builders/tweak_builder.rb
@@ -0,0 +1,7 @@
+class AppBuilder < Rails::AppBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
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 0000000000..e4378bbd1a
--- /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/plugin_builders/empty_builder.rb b/railties/test/fixtures/lib/plugin_builders/empty_builder.rb
new file mode 100644
index 0000000000..5c5607621c
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/empty_builder.rb
@@ -0,0 +1,2 @@
+class PluginBuilder
+end
diff --git a/railties/test/fixtures/lib/plugin_builders/simple_builder.rb b/railties/test/fixtures/lib/plugin_builders/simple_builder.rb
new file mode 100644
index 0000000000..08f6c5535d
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/simple_builder.rb
@@ -0,0 +1,7 @@
+class PluginBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
diff --git a/railties/test/fixtures/lib/plugin_builders/spec_builder.rb b/railties/test/fixtures/lib/plugin_builders/spec_builder.rb
new file mode 100644
index 0000000000..aa18c7ddaa
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/spec_builder.rb
@@ -0,0 +1,19 @@
+class PluginBuilder < Rails::PluginBuilder
+ def test
+ create_file "spec/spec_helper.rb"
+ append_file "Rakefile", <<-EOF
+# spec tasks in rakefile
+
+task :default => :spec
+ EOF
+ end
+
+ def generate_test_dummy
+ dummy_path("spec/dummy")
+ super
+ end
+
+ def skip_test_unit?
+ true
+ end
+end
diff --git a/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb b/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb
new file mode 100644
index 0000000000..1e801409a4
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb
@@ -0,0 +1,7 @@
+class PluginBuilder < Rails::PluginBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
diff --git a/railties/test/fixtures/lib/simple_builder.rb b/railties/test/fixtures/lib/simple_builder.rb
deleted file mode 100644
index 47dcdc0d96..0000000000
--- a/railties/test/fixtures/lib/simple_builder.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-class AppBuilder
- def configru
- create_file "config.ru", <<-R.strip
-run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }
- R
- end
-end \ No newline at end of file
diff --git a/railties/test/fixtures/lib/tweak_builder.rb b/railties/test/fixtures/lib/tweak_builder.rb
deleted file mode 100644
index eed20ecc9b..0000000000
--- a/railties/test/fixtures/lib/tweak_builder.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-class AppBuilder < Rails::AppBuilder
- def configru
- create_file "config.ru", <<-R.strip
-run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }
- R
- end
-end \ No newline at end of file
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index 0472ca73a8..68d4c17623 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -7,11 +7,16 @@ class ActionsTest < Rails::Generators::TestCase
arguments [destination_root]
def setup
+ Rails.application = TestApp::Application
super
@git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git'
@svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk'
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/
@@ -79,37 +84,6 @@ class ActionsTest < Rails::Generators::TestCase
assert_file 'Gemfile', /gem "will\-paginate"/
end
- def test_gem_with_options_should_include_all_options_in_gemfile
- run_generator
-
- assert_deprecated do
- action :gem, 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com'
- end
-
- assert_deprecated do
- action :gem, 'thoughtbot-factory_girl', :require_as => 'factory_girl', :source => 'http://gems.github.com'
- end
-
- assert_file 'Gemfile', /gem "mislav\-will\-paginate", :require => "will\-paginate"/
- assert_file 'Gemfile', /source "http:\/\/gems\.github\.com"/
- assert_file 'Gemfile', /gem "thoughtbot-factory_girl", :require => "factory_girl"/
- end
-
- def test_gem_with_env_should_include_all_dependencies_in_gemfile
- run_generator
-
- assert_deprecated do
- action :gem, 'rspec', :env => %w(development test)
- end
-
- assert_deprecated do
- action :gem, 'rspec-rails', :only => %w(development test)
- end
-
- assert_file 'Gemfile', /gem "rspec", :group => \["development", "test"\]/
- assert_file 'Gemfile', /gem "rspec-rails", :group => \["development", "test"\]/
- end
-
def test_gem_with_version_should_include_version_in_gemfile
run_generator
@@ -204,12 +178,6 @@ class ActionsTest < Rails::Generators::TestCase
action :capify!
end
- def test_freeze_is_deprecated
- assert_deprecated do
- action :freeze!
- end
- end
-
def test_route_should_add_data_to_the_routes_block_in_config_routes
run_generator
route_command = "route '/login', :controller => 'sessions', :action => 'new'"
@@ -223,6 +191,31 @@ class ActionsTest < Rails::Generators::TestCase
assert_match(/Welcome to Rails/, action(:readme, "README"))
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(/Welcome to Rails/, action(:readme, "README"))
+ 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)
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 08cfb585f9..018c2fa6bf 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/app/app_generator'
+require 'generators/shared_generator_tests.rb'
DEFAULT_APP_FILES = %w(
.gitignore
@@ -40,28 +41,10 @@ DEFAULT_APP_FILES = %w(
class AppGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
arguments [destination_root]
+ include SharedGeneratorTests
- def setup
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
- end
-
- def teardown
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- end
-
- def test_application_skeleton_is_created
- run_generator
-
- DEFAULT_APP_FILES.each{ |path| assert_file path }
- end
-
- def test_application_generate_pretend
- run_generator ["testapp", "--pretend"]
-
- DEFAULT_APP_FILES.each{ |path| assert_no_file path }
+ def default_files
+ ::DEFAULT_APP_FILES
end
def test_application_controller_and_layout_files
@@ -70,42 +53,34 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_no_file "public/stylesheets/application.css"
end
- def test_options_before_application_name_raises_an_error
- content = capture(:stderr){ run_generator(["--skip-active-record", destination_root]) }
- assert_equal "Options should be given after the application name. For details run: rails --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_equal "Invalid application name #{reserved}. Please give a name which does not match one of the reserved rails words.\n", content
- end
- 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_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_application_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_equal "Invalid application name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another application name.\n", content
- end
- 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
+ # TODO: Suppress the output of this (it's because of a Thor::Error)
+ `rails new test`
+ assert_equal false, $?.success?
+ end
+
+ def test_application_new_exits_with_message_and_non_zero_code_when_generating_inside_existing_rails_directory
+ app_root = File.join(destination_root, 'myfirstapp')
+ run_generator [app_root]
+ output = nil
+ Dir.chdir(app_root) do
+ output = `rails new mysecondapp`
+ end
+ assert_equal "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\nType 'rails' for help.\n", output
+ assert_equal false, $?.success?
+ end
+
def test_application_name_is_detected_if_it_exists_and_app_folder_renamed
app_root = File.join(destination_root, "myapp")
app_moved_root = File.join(destination_root, "myapp_moved")
@@ -118,16 +93,26 @@ class AppGeneratorTest < Rails::Generators::TestCase
FileUtils.mv(app_root, app_moved_root)
- # forces the shell to automatically overwrite all files
- Thor::Base.shell.send(:attr_accessor, :always_force)
- shell = Thor::Base.shell.new
- shell.send(:always_force=, true)
-
generator = Rails::Generators::AppGenerator.new ["rails"], { :with_dispatchers => true },
- :destination_root => app_moved_root, :shell => shell
+ :destination_root => app_moved_root, :shell => @shell
generator.send(:app_const)
silence(:stdout){ 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)
+ silence(:stdout){ generator.send(:create_config_files) }
+ assert_file "myapp/config/initializers/session_store.rb", /_myapp_session/
end
def test_application_names_are_not_singularized
@@ -138,18 +123,22 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_config_database_is_added_by_default
run_generator
assert_file "config/database.yml", /sqlite3/
- assert_file "Gemfile", /^gem\s+["']sqlite3-ruby["'],\s+:require\s+=>\s+["']sqlite3["']$/
+ assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
end
def test_config_another_database
run_generator([destination_root, "-d", "mysql"])
assert_file "config/database.yml", /mysql/
- assert_file "Gemfile", /^gem\s+["']mysql["']$/
+ assert_file "Gemfile", /^gem\s+["']mysql2["']$/
end
- def test_config_database_is_not_added_if_skip_active_record_is_given
+ def test_generator_if_skip_active_record_is_given
run_generator [destination_root, "--skip-active-record"]
assert_no_file "config/database.yml"
+ assert_file "test/test_helper.rb" do |helper_content|
+ assert_no_match /fixtures :all/, helper_content
+ end
+ assert_file "test/performance/browsing_test.rb"
end
def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given
@@ -163,26 +152,37 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "public/javascripts/application.js"
assert_file "public/javascripts/prototype.js"
assert_file "public/javascripts/rails.js"
+ assert_file "public/javascripts/controls.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/effects.js"
assert_file "test"
end
- def test_prototype_and_test_unit_are_skipped_if_required
- run_generator [destination_root, "--skip-prototype", "--skip-test-unit"]
+ def test_javascript_is_skipped_if_required
+ run_generator [destination_root, "--skip-javascript"]
assert_file "config/application.rb", /^\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(\)/
assert_file "public/javascripts/application.js"
assert_no_file "public/javascripts/prototype.js"
assert_no_file "public/javascripts/rails.js"
- assert_no_file "test"
end
- def test_shebang_is_added_to_rails_file
- run_generator [destination_root, "--ruby", "foo/bar/baz"]
- assert_file "script/rails", /#!foo\/bar\/baz/
+ def test_config_prototype_javascript_library
+ run_generator [destination_root, "-j", "prototype"]
+ assert_file "config/application.rb", /#\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(jquery rails\)/
+ assert_file "public/javascripts/application.js"
+ assert_file "public/javascripts/prototype.js"
+ assert_file "public/javascripts/controls.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/effects.js"
+ assert_file "public/javascripts/rails.js", /prototype/
end
- def test_shebang_when_is_the_same_as_default_use_env
- run_generator [destination_root, "--ruby", Thor::Util.ruby_command]
- assert_file "script/rails", /#!\/usr\/bin\/env/
+ def test_config_jquery_javascript_library
+ run_generator [destination_root, "-j", "jquery"]
+ assert_file "config/application.rb", /^\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(jquery rails\)/
+ assert_file "public/javascripts/application.js"
+ assert_file "public/javascripts/jquery.js"
+ assert_file "public/javascripts/rails.js", /jQuery/
end
def test_template_from_dir_pwd
@@ -190,21 +190,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_match /It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])
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 = "http://gist.github.com/103208.txt"
- 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!/, silence(:stdout){ generator.invoke_all }
- end
-
def test_usage_read_from_file
File.expects(:read).returns("USAGE FROM FILE")
assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc
@@ -224,17 +209,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file 'lib/test_file.rb', 'heres test data'
end
- def test_dev_option
- generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install")
- silence(:stdout){ generator.invoke_all }
- rails_path = File.expand_path('../../..', Rails.root)
- assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/
- end
-
- def test_edge_option
- generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install")
- silence(:stdout){ generator.invoke_all }
- assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$/
+ 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" do |file|
+ assert_match /config.generators.test_framework = false/, file
+ end
end
protected
@@ -250,60 +229,21 @@ class CustomAppGeneratorTest < Rails::Generators::TestCase
tests Rails::Generators::AppGenerator
arguments [destination_root]
+ include SharedCustomGeneratorTests
- def setup
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
- end
-
- def teardown
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- Object.class_eval { remove_const :AppBuilder if const_defined?(:AppBuilder) }
- end
-
- def test_builder_option_with_empty_app_builder
- FileUtils.cd(Rails.root)
- run_generator([destination_root, "-b", "#{Rails.root}/lib/empty_builder.rb"])
- DEFAULT_APP_FILES.each{ |path| assert_no_file path }
- end
-
- def test_builder_option_with_simple_app_builder
- FileUtils.cd(Rails.root)
- run_generator([destination_root, "-b", "#{Rails.root}/lib/simple_builder.rb"])
- (DEFAULT_APP_FILES - ['config.ru']).each{ |path| assert_no_file path }
- assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }]
- end
-
- def test_builder_option_with_relative_path
- here = File.expand_path(File.dirname(__FILE__))
- FileUtils.cd(here)
- run_generator([destination_root, "-b", "../fixtures/lib/simple_builder.rb"])
- (DEFAULT_APP_FILES - ['config.ru']).each{ |path| assert_no_file path }
- assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }]
+protected
+ def default_files
+ ::DEFAULT_APP_FILES
end
- def test_builder_option_with_tweak_app_builder
- FileUtils.cd(Rails.root)
- run_generator([destination_root, "-b", "#{Rails.root}/lib/tweak_builder.rb"])
- DEFAULT_APP_FILES.each{ |path| assert_file path }
- assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }]
+ def builders_dir
+ "app_builders"
end
- def test_builder_option_with_http
- path = "http://gist.github.com/103208.txt"
- template = "class AppBuilder; end"
- template.instance_eval "def read; self; end" # Make the string respond to read
-
- generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
- capture(:stdout) { generator.invoke_all }
-
- DEFAULT_APP_FILES.each{ |path| assert_no_file path }
+ def builder_class
+ :AppBuilder
end
-protected
-
def action(*args, &block)
silence(:stdout){ generator.send(*args, &block) }
end
diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb
index de7e4de2a6..064546a3f3 100644
--- a/railties/test/generators/generated_attribute_test.rb
+++ b/railties/test/generators/generated_attribute_test.rb
@@ -108,4 +108,16 @@ class GeneratedAttributeTest < Rails::Generators::TestCase
)
end
end
+
+ def test_nil_type_raises_exception
+ assert_raise Thor::Error do
+ create_generated_attribute(nil, 'title')
+ end
+ end
+
+ def test_missing_type_raises_exception
+ assert_raise Thor::Error do
+ create_generated_attribute('', 'title')
+ end
+ end
end
diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb
index 26f975a191..f4c975fc18 100644
--- a/railties/test/generators/generator_generator_test.rb
+++ b/railties/test/generators/generator_generator_test.rb
@@ -17,4 +17,43 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase
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
index 4a5a9b2932..1b9a8fd8a7 100644
--- a/railties/test/generators/generators_test_helper.rb
+++ b/railties/test/generators/generators_test_helper.rb
@@ -34,6 +34,6 @@ module GeneratorsTestHelper
routes = File.expand_path("../../../lib/rails/generators/rails/app/templates/config/routes.rb", __FILE__)
destination = File.join(destination_root, "config")
FileUtils.mkdir_p(destination)
- FileUtils.cp File.expand_path(routes), destination
+ FileUtils.cp routes, destination
end
-end \ No newline at end of file
+end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index 450dec7716..f4fdc46328 100644
--- a/railties/test/generators/mailer_generator_test.rb
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -59,6 +59,15 @@ class MailerGeneratorTest < Rails::Generators::TestCase
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
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index f9d1e42d24..6eecfc8e2e 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -34,15 +34,10 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
run_generator [migration, "title:string", "body:text"]
assert_migration "db/migrate/#{migration}.rb" do |content|
- assert_class_method :up, content do |up|
+ assert_method :change, content do |up|
assert_match /add_column :posts, :title, :string/, up
assert_match /add_column :posts, :body, :text/, up
end
-
- assert_class_method :down, content do |down|
- assert_match /remove_column :posts, :title/, down
- assert_match /remove_column :posts, :body/, down
- end
end
end
@@ -51,12 +46,12 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
run_generator [migration, "title:string", "body:text"]
assert_migration "db/migrate/#{migration}.rb" do |content|
- assert_class_method :up, content do |up|
+ assert_method :up, content do |up|
assert_match /remove_column :posts, :title/, up
assert_match /remove_column :posts, :body/, up
end
- assert_class_method :down, content do |down|
+ assert_method :down, content do |down|
assert_match /add_column :posts, :title, :string/, down
assert_match /add_column :posts, :body, :text/, down
end
@@ -68,11 +63,11 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
run_generator [migration, "title:string", "content:text"]
assert_migration "db/migrate/#{migration}.rb" do |content|
- assert_class_method :up, content do |up|
+ assert_method :up, content do |up|
assert_match /^\s*$/, up
end
- assert_class_method :down, content do |down|
+ assert_method :down, content do |down|
assert_match /^\s*$/, down
end
end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index ef415a4fed..3d773b4134 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -11,6 +11,12 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_match /TestUnit options:/, content
end
+ def test_model_with_missing_attribute_type
+ content = capture(:stderr) { run_generator ["post", "title:string", "body"] }
+ assert_match /Missing type for attribute 'body'/, content
+ assert_match /Example: 'body:string' where string is the type/, content
+ end
+
def test_invokes_default_orm
run_generator
assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/
@@ -93,15 +99,11 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["product", "name:string", "supplier_id:integer"]
assert_migration "db/migrate/create_products.rb" do |m|
- assert_class_method :up, m do |up|
+ assert_method :change, m do |up|
assert_match /create_table :products/, up
assert_match /t\.string :name/, up
assert_match /t\.integer :supplier_id/, up
end
-
- assert_class_method :down, m do |down|
- assert_match /drop_table :products/, down
- end
end
end
@@ -135,16 +137,28 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["account", "--no-timestamps"]
assert_migration "db/migrate/create_accounts.rb" do |m|
- assert_class_method :up, m do |up|
+ assert_method :change, m do |up|
assert_no_match /t.timestamps/, up
end
end
end
- def test_migration_already_exists_error_message
+ 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
- error = capture(:stderr){ run_generator ["Account"], :behavior => :skip }
- assert_match /Another migration is already named create_accounts/, error
+ 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
@@ -159,6 +173,15 @@ class ModelGeneratorTest < Rails::Generators::TestCase
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/unit/account_test.rb", /class AccountTest < ActiveSupport::TestCase/
@@ -180,4 +203,45 @@ class ModelGeneratorTest < Rails::Generators::TestCase
content = capture(:stderr){ run_generator ["object"] }
assert_match /The name 'Object' is either already used in your application or reserved/, content
end
+
+ def test_index_is_added_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_added_for_references_association
+ run_generator ["account", "supplier:references"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_references_association
+ run_generator ["account", "supplier:references", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match /add_index/, up
+ end
+ end
+ end
+
end
diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb
index 1badae0713..f23701e99e 100644
--- a/railties/test/generators/named_base_test.rb
+++ b/railties/test/generators/named_base_test.rb
@@ -98,6 +98,11 @@ class NamedBaseTest < Rails::Generators::TestCase
assert_name g, 'posts', :index_helper
end
+ def test_index_helper_to_pluralize_once
+ g = generator ['Stadium']
+ assert_name g, 'stadia', :index_helper
+ end
+
def test_index_helper_with_uncountable
g = generator ['Sheep']
assert_name g, 'sheep_index', :index_helper
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
new file mode 100644
index 0000000000..d61a02d32f
--- /dev/null
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -0,0 +1,357 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/controller/controller_generator'
+require 'rails/generators/rails/model/model_generator'
+require 'rails/generators/rails/observer/observer_generator'
+require 'rails/generators/mailer/mailer_generator'
+require 'rails/generators/rails/scaffold/scaffold_generator'
+
+class NamespacedGeneratorTestCase < Rails::Generators::TestCase
+ def setup
+ TestApp::Application.isolate_namespace(TestApp)
+ end
+
+ def teardown
+ if TestApp.respond_to?(:_railtie)
+ TestApp.singleton_class.send(:undef_method, :_railtie)
+ TestApp.singleton_class.send(:undef_method, :table_name_prefix)
+ TestApp::Application.isolated = false
+ end
+ end
+end
+
+class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase
+ include GeneratorsTestHelper
+ 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", /module TestApp/, / class AccountController < ApplicationController/
+ assert_file "test/functional/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/
+ 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/unit/helpers/test_app/account_helper_test.rb", /module TestApp/, / class AccountHelperTest/
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/functional/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
+end
+
+class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
+ include GeneratorsTestHelper
+ 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", /'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/unit/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 NamespacedObserverGeneratorTest < NamespacedGeneratorTestCase
+ include GeneratorsTestHelper
+ arguments %w(account)
+ tests Rails::Generators::ObserverGenerator
+
+ def test_invokes_default_orm
+ run_generator
+ assert_file "app/models/test_app/account_observer.rb", /module TestApp/, / class AccountObserver < ActiveRecord::Observer/
+ end
+
+ def test_invokes_default_orm_with_class_path
+ run_generator ["admin/account"]
+ assert_file "app/models/test_app/admin/account_observer.rb", /module TestApp/, / class Admin::AccountObserver < ActiveRecord::Observer/
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/unit/test_app/account_observer_test.rb", /module TestApp/, / class AccountObserverTest < ActiveSupport::TestCase/
+ end
+end
+
+class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase
+ include GeneratorsTestHelper
+ 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@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/functional/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/unit/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" do |content|
+ assert_match(/module TestApp\n class ProductLinesController < ApplicationController/, content)
+ end
+
+ assert_file "test/functional/test_app/product_lines_controller_test.rb",
+ /module TestApp\n class ProductLinesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(
+ index
+ edit
+ new
+ show
+ _form
+ ).each { |view| assert_file "app/views/test_app/product_lines/#{view}.html.erb" }
+ 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/unit/helpers/test_app/product_lines_helper_test.rb"
+
+ # Stylesheets
+ assert_file "public/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/unit/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/functional/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/unit/helpers/test_app/product_lines_helper_test.rb"
+
+ # Stylesheets (should not be removed)
+ assert_file "public/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/unit/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 resources :roles 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/functional/test_app/admin/roles_controller_test.rb",
+ /module TestApp\n class Admin::RolesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(
+ index
+ edit
+ new
+ show
+ _form
+ ).each { |view| assert_file "app/views/test_app/admin/roles/#{view}.html.erb" }
+ assert_no_file "app/views/layouts/admin/roles.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/test_app/admin/roles_helper.rb"
+ assert_file "test/unit/helpers/test_app/admin/roles_helper_test.rb"
+
+ # Stylesheets
+ assert_file "public/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/unit/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 resources :roles end$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/test_app/admin/roles_controller.rb"
+ assert_no_file "test/functional/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/unit/helpers/test_app/admin/roles_helper_test.rb"
+
+ # Stylesheets (should not be removed)
+ assert_file "public/stylesheets/scaffold.css"
+ end
+end
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index c1f646f7c1..e6686a6af4 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -6,7 +6,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
arguments %w(plugin_fu)
def test_plugin_skeleton_is_created
- run_generator
+ silence(:stderr) { run_generator }
year = Date.today.year
%w(
@@ -36,30 +36,36 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
def test_invokes_default_test_framework
- run_generator
+ silence(:stderr) { run_generator }
assert_file "vendor/plugins/plugin_fu/test/plugin_fu_test.rb", /class PluginFuTest < ActiveSupport::TestCase/
assert_file "vendor/plugins/plugin_fu/test/test_helper.rb"
end
def test_logs_if_the_test_framework_cannot_be_found
- content = run_generator ["plugin_fu", "--test-framework=rspec"]
+ content = nil
+ silence(:stderr) { content = run_generator ["plugin_fu", "--test-framework=rspec"] }
assert_match /rspec \[not found\]/, content
end
def test_creates_tasks_if_required
- run_generator ["plugin_fu", "--tasks"]
+ silence(:stderr) { run_generator ["plugin_fu", "--tasks"] }
assert_file "vendor/plugins/plugin_fu/lib/tasks/plugin_fu_tasks.rake"
end
def test_creates_generator_if_required
- run_generator ["plugin_fu", "--generator"]
+ silence(:stderr) { run_generator ["plugin_fu", "--generator"] }
assert_file "vendor/plugins/plugin_fu/lib/generators/templates"
assert_file "vendor/plugins/plugin_fu/lib/generators/plugin_fu_generator.rb",
/class PluginFuGenerator < Rails::Generators::NamedBase/
end
def test_plugin_generator_on_revoke
- run_generator
+ silence(:stderr) { run_generator }
run_generator ["plugin_fu"], :behavior => :revoke
end
+
+ def test_deprecation
+ output = capture(:stderr) { run_generator }
+ assert_match /Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure./, output
+ 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 0000000000..3c11c8dbaf
--- /dev/null
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -0,0 +1,229 @@
+require 'abstract_unit'
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/plugin_new/plugin_new_generator'
+require 'generators/shared_generator_tests.rb'
+
+DEFAULT_PLUGIN_FILES = %w(
+ .gitignore
+ Gemfile
+ Rakefile
+ bukkits.gemspec
+ MIT-LICENSE
+ lib
+ lib/bukkits.rb
+ lib/tasks/bukkits_tasks.rake
+ script/rails
+ 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]
+ include SharedGeneratorTests
+
+ def default_files
+ ::DEFAULT_PLUGIN_FILES
+ end
+
+ def test_invalid_plugin_name_raises_an_error
+ content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
+ assert_equal "Invalid plugin name 43-things. Please give a name which does not start with numbers.\n", content
+ end
+
+ def test_invalid_plugin_name_is_fixed
+ run_generator [File.join(destination_root, "things-43")]
+ assert_file "things-43/lib/things-43.rb", /module Things43/
+ 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_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_assed_by_default_in_full_mode
+ run_generator([destination_root, "--full"])
+ assert_file "test/dummy/config/database.yml", /sqlite/
+ assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
+ end
+
+ def test_config_another_database
+ run_generator([destination_root, "-d", "mysql", "--full"])
+ assert_file "test/dummy/config/database.yml", /mysql/
+ assert_file "Gemfile", /^gem\s+["']mysql2["']$/
+ 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_no_match(/ActiveRecord/, File.read(File.join(destination_root, "test/test_helper.rb")))
+ 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_skipping_javascripts_without_mountable_option
+ run_generator
+ assert_no_file "public/javascripts/prototype.js"
+ assert_no_file "public/javascripts/rails.js"
+ assert_no_file "public/javascripts/controls.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ assert_no_file "public/javascripts/application.js"
+ end
+
+ def test_javascripts_generation
+ run_generator [destination_root, "--mountable"]
+ assert_file "public/javascripts/rails.js"
+ assert_file "public/javascripts/prototype.js"
+ assert_file "public/javascripts/controls.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/application.js"
+ end
+
+ def test_skip_javascripts
+ run_generator [destination_root, "--skip-javascript", "--mountable"]
+ assert_no_file "public/javascripts/prototype.js"
+ assert_no_file "public/javascripts/rails.js"
+ assert_no_file "public/javascripts/controls.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ end
+
+ def test_ensure_that_javascript_option_is_passed_to_app_generator
+ run_generator [destination_root, "--javascript", "jquery"]
+ assert_file "test/dummy/public/javascripts/jquery.js"
+ end
+
+ def test_ensure_that_skip_javascript_option_is_passed_to_app_generator
+ run_generator [destination_root, "--skip_javascript"]
+ assert_no_file "test/dummy/public/javascripts/prototype.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_works
+ run_generator
+ FileUtils.cd destination_root
+ `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
+ `bundle install`
+ assert_match(/2 tests, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test`)
+ end
+
+ def test_creating_engine_in_full_mode
+ run_generator [destination_root, "--full"]
+ assert_file "config/routes.rb", /Rails.application.routes.draw do/
+ assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < Rails::Engine\n end\nend/
+ assert_file "lib/bukkits.rb", /require "bukkits\/engine"/
+ end
+
+ 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 "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", /<title>Bukkits<\/title>/
+ 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_skipping_gemspec
+ run_generator [destination_root, "--skip-gemspec"]
+ assert_no_file "bukkits.gemspec"
+ end
+
+protected
+
+ def action(*args, &block)
+ silence(:stdout){ generator.send(*args, &block) }
+ end
+
+end
+
+class CustomPluginGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ tests Rails::Generators::PluginNewGenerator
+
+ destination File.join(Rails.root, "tmp/bukkits")
+ arguments [destination_root]
+ include SharedCustomGeneratorTests
+
+ def test_overriding_test_framework
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/plugin_builders/spec_builder.rb"])
+ assert_file 'spec/spec_helper.rb'
+ assert_file 'spec/dummy'
+ assert_file 'Rakefile', /task :default => :spec/
+ assert_file 'Rakefile', /# spec tasks in rakefile/
+ assert_file 'script/rails', %r{spec/dummy}
+ end
+
+protected
+ def default_files
+ ::DEFAULT_PLUGIN_FILES
+ end
+
+ def builder_class
+ :PluginBuilder
+ end
+
+ def builders_dir
+ "plugin_builders"
+ end
+
+ def action(*args, &block)
+ silence(:stdout){ generator.send(*args, &block) }
+ end
+end
diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb
index 55d5bd6f83..71b3619351 100644
--- a/railties/test/generators/resource_generator_test.rb
+++ b/railties/test/generators/resource_generator_test.rb
@@ -73,6 +73,11 @@ class ResourceGeneratorTest < Rails::Generators::TestCase
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
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index f12445ae35..df787f61ba 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -3,7 +3,7 @@ require 'rails/generators/rails/scaffold/scaffold_generator'
class ScaffoldGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
- arguments %w(product_line title:string price:integer)
+ arguments %w(product_line title:string product:belongs_to user:references)
setup :copy_routes
@@ -14,48 +14,51 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/
assert_file "test/unit/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
assert_file "test/fixtures/product_lines.yml"
- assert_migration "db/migrate/create_product_lines.rb"
+ assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/
+ assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :product_id/
+ assert_migration "db/migrate/create_product_lines.rb", /references :user/
+ assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :user_id/
# Route
assert_file "config/routes.rb" do |route|
- assert_match /resources :product_lines$/, 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_match(/class ProductLinesController < ApplicationController/, content)
assert_instance_method :index, content do |m|
- assert_match /@product_lines = ProductLine\.all/, m
+ assert_match(/@product_lines = ProductLine\.all/, m)
end
assert_instance_method :show, content do |m|
- assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
end
assert_instance_method :new, content do |m|
- assert_match /@product_line = ProductLine\.new/, m
+ assert_match(/@product_line = ProductLine\.new/, m)
end
assert_instance_method :edit, content do |m|
- assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
end
assert_instance_method :create, content do |m|
- assert_match /@product_line = ProductLine\.new\(params\[:product_line\]\)/, m
- assert_match /@product_line\.save/, m
- assert_match /@product_line\.errors/, m
+ assert_match(/@product_line = ProductLine\.new\(params\[:product_line\]\)/, m)
+ assert_match(/@product_line\.save/, m)
+ assert_match(/@product_line\.errors/, m)
end
assert_instance_method :update, content do |m|
- assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m
- assert_match /@product_line\.update_attributes\(params\[:product_line\]\)/, m
- assert_match /@product_line\.errors/, m
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
+ assert_match(/@product_line\.update_attributes\(params\[:product_line\]\)/, m)
+ assert_match(/@product_line\.errors/, m)
end
assert_instance_method :destroy, content do |m|
- assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m
- assert_match /@product_line\.destroy/, m
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
+ assert_match(/@product_line\.destroy/, m)
end
end
@@ -92,7 +95,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
# Route
assert_file "config/routes.rb" do |route|
- assert_no_match /resources :product_lines$/, route
+ assert_no_match(/resources :product_lines$/, route)
end
# Controller
@@ -123,44 +126,44 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
# Route
assert_file "config/routes.rb" do |route|
- assert_match /namespace :admin do resources :roles end$/, route
+ assert_match(/namespace :admin do resources :roles end$/, route)
end
# Controller
assert_file "app/controllers/admin/roles_controller.rb" do |content|
- assert_match /class Admin::RolesController < ApplicationController/, content
+ assert_match(/class Admin::RolesController < ApplicationController/, content)
assert_instance_method :index, content do |m|
- assert_match /@admin_roles = Admin::Role\.all/, m
+ assert_match(/@admin_roles = Admin::Role\.all/, m)
end
assert_instance_method :show, content do |m|
- assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m
+ assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
end
assert_instance_method :new, content do |m|
- assert_match /@admin_role = Admin::Role\.new/, m
+ assert_match(/@admin_role = Admin::Role\.new/, m)
end
assert_instance_method :edit, content do |m|
- assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m
+ assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
end
assert_instance_method :create, content do |m|
- assert_match /@admin_role = Admin::Role\.new\(params\[:admin_role\]\)/, m
- assert_match /@admin_role\.save/, m
- assert_match /@admin_role\.errors/, m
+ assert_match(/@admin_role = Admin::Role\.new\(params\[:admin_role\]\)/, m)
+ assert_match(/@admin_role\.save/, m)
+ assert_match(/@admin_role\.errors/, m)
end
assert_instance_method :update, content do |m|
- assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m
- assert_match /@admin_role\.update_attributes\(params\[:admin_role\]\)/, m
- assert_match /@admin_role\.errors/, m
+ assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
+ assert_match(/@admin_role\.update_attributes\(params\[:admin_role\]\)/, m)
+ assert_match(/@admin_role\.errors/, m)
end
assert_instance_method :destroy, content do |m|
- assert_match /@admin_role = Admin::Role\.find\(params\[:id\]\)/, m
- assert_match /@admin_role\.destroy/, m
+ assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
+ assert_match(/@admin_role\.destroy/, m)
end
end
@@ -198,7 +201,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
# Route
assert_file "config/routes.rb" do |route|
- assert_no_match /namespace :admin do resources :roles end$/, route
+ assert_no_match(/namespace :admin do resources :roles end$/, route)
end
# Controller
@@ -231,4 +234,10 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/
end
+
+ def test_scaffold_generator_outputs_error_message_on_missing_attribute_type
+ content = capture(:stderr) { run_generator ["post", "title:string", "body"]}
+ assert_match(/Missing type for attribute 'body'/, content)
+ assert_match(/Example: 'body:string' where string is the type/, content)
+ 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 0000000000..c9c5d2fad2
--- /dev/null
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -0,0 +1,195 @@
+module SharedGeneratorTests
+ def setup
+ Rails.application = TestApp::Application
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
+
+ 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_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)? --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"]
+ assert_file "script/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]
+ assert_file "script/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 = "http://gist.github.com/103208.txt"
+ 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!/, silence(:stdout){ generator.invoke_all })
+ end
+
+ def test_dev_option
+ generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ rails_path = File.expand_path('../../..', Rails.root)
+ assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/
+ end
+
+ def test_edge_option
+ generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$}
+ 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 = "http://gist.github.com/103208.txt"
+ 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!/, silence(:stdout){ generator.invoke_all })
+ end
+
+ def test_template_is_executed_when_supplied_an_https_path
+ path = "https://gist.github.com/103208.txt"
+ 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!/, silence(:stdout){ generator.invoke_all })
+ end
+
+ def test_dev_option
+ generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ rails_path = File.expand_path('../../..', Rails.root)
+ assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/
+ end
+
+ def test_edge_option
+ generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$}
+ end
+end
+
+module SharedCustomGeneratorTests
+ def setup
+ Rails.application = TestApp::Application
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
+ end
+
+ def teardown
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ Object.class_eval do
+ remove_const :AppBuilder if const_defined?(:AppBuilder)
+ remove_const :PluginBuilder if const_defined?(:PluginBuilder)
+ end
+ Rails.application = TestApp::Application.instance
+ end
+
+ def test_builder_option_with_empty_app_builder
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/empty_builder.rb"])
+ default_files.each{ |path| assert_no_file path }
+ end
+
+ def test_builder_option_with_simple_plugin_builder
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/simple_builder.rb"])
+ (default_files - ['.gitignore']).each{ |path| assert_no_file path }
+ assert_file ".gitignore", "foobar"
+ end
+
+ def test_builder_option_with_relative_path
+ here = File.expand_path(File.dirname(__FILE__))
+ FileUtils.cd(here)
+ run_generator([destination_root, "-b", "../fixtures/lib/#{builders_dir}/simple_builder.rb"])
+ FileUtils.cd(destination_root)
+ (default_files - ['.gitignore']).each{ |path| assert_no_file path }
+ assert_file ".gitignore", "foobar"
+ end
+
+ def test_builder_option_with_tweak_plugin_builder
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/tweak_builder.rb"])
+ default_files.each{ |path| assert_file path }
+ assert_file ".gitignore", "foobar"
+ end
+
+ def test_builder_option_with_http
+ path = "http://gist.github.com/103208.txt"
+ template = "class #{builder_class}; end"
+ template.instance_eval "def read; self; end" # Make the string respond to read
+
+ generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ capture(:stdout) { generator.invoke_all }
+
+ default_files.each{ |path| assert_no_file(path) }
+ end
+end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index f93800a5ae..99c9d790eb 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -94,6 +94,14 @@ class GeneratorsTest < Rails::Generators::TestCase
assert_match /Rails 2\.x generator/, output
end
+ def test_invoke_with_nested_namespaces
+ model_generator = mock('ModelGenerator') do
+ expects(:start).with(["Account"], {})
+ end
+ Rails::Generators.expects(:find_by_namespace).with('namespace', 'my:awesome').returns(model_generator)
+ Rails::Generators.invoke 'my:awesome:namespace', ["Account"]
+ end
+
def test_rails_generators_help_with_builtin_information
output = capture(:stdout){ Rails::Generators.help }
assert_match /Rails:/, output
@@ -102,6 +110,12 @@ class GeneratorsTest < Rails::Generators::TestCase
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
@@ -114,6 +128,16 @@ class GeneratorsTest < Rails::Generators::TestCase
assert_match /^ active_record:fixjour$/, output
end
+ def test_default_banner_should_show_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:foobar)
+ assert_match /^rails generate foobar:foobar/, klass.banner
+ end
+
+ def test_default_banner_should_not_show_rails_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:model)
+ assert_match /^rails generate model/, klass.banner
+ end
+
def test_no_color_sets_proper_shell
Rails::Generators.no_color!
assert_equal Thor::Shell::Basic, Thor::Base.shell
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 390c0ab543..c5b1cb9a80 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -19,6 +19,7 @@ RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..")
# to run the tests
require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/testing/isolation"
require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/testing/declarative"
+require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/core_ext/kernel/reporting"
module TestHelpers
module Paths
@@ -44,6 +45,17 @@ module TestHelpers
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 }
@@ -123,6 +135,22 @@ module TestHelpers
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
+ match ':controller(/:action)'
+ end
+ RUBY
+ end
+
class Bukkit
attr_reader :path
@@ -187,6 +215,13 @@ module TestHelpers
end
end
+ def remove_from_config(str)
+ file = "#{app_path}/config/application.rb"
+ contents = File.read(file)
+ contents.sub!(/#{str}/, "")
+ File.open(file, "w+") { |f| f.puts contents }
+ end
+
def app_file(path, contents)
FileUtils.mkdir_p File.dirname("#{app_path}/#{path}")
File.open("#{app_path}/#{path}", 'w') do |f|
@@ -203,6 +238,7 @@ module TestHelpers
:activemodel,
:activerecord,
:activeresource] - arr
+ remove_from_config "config.active_record.identity_map = true" if to_remove.include? :activerecord
$:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
end
diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb
index 80fae8c543..6e4e3446b3 100644
--- a/railties/test/paths_test.rb
+++ b/railties/test/paths_test.rb
@@ -20,234 +20,264 @@ class PathsTest < ActiveSupport::TestCase
test "a paths object initialized with nil can be updated" do
root = Rails::Paths::Root.new(nil)
- root.app = "app"
+ root.add "app"
root.path = "/root"
- assert_equal ["/root/app"], root.app.to_a
+ assert_equal ["app"], root["app"]
+ assert_equal ["/root/app"], root["app"].to_a
end
test "creating a root level path" do
- @root.app = "/foo/bar"
- assert_equal ["/foo/bar"], @root.app.to_a
+ @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.app = "app"
+ root.add "app"
assert_raises RuntimeError do
- root.app.to_a
+ root["app"].to_a
end
end
- test "creating a root level path without assignment" do
- @root.app "/foo/bar"
- assert_equal ["/foo/bar"], @root.app.to_a
- end
-
- test "trying to access a path that does not exist raises NoMethodError" do
- assert_raises(NoMethodError) { @root.app }
- end
-
- test "relative paths are relative to the paths root" do
- @root.app = "app"
- assert_equal ["/foo/bar/app"], @root.app.to_a
- end
-
- test "relative paths are relative to the paths root without assignment" do
- @root.app "app"
- assert_equal ["/foo/bar/app"], @root.app.to_a
- end
-
test "creating a child level path" do
- @root.app = "/foo/bar"
- @root.app.models = "/foo/bar/baz"
- assert_equal ["/foo/bar/baz"], @root.app.models.to_a
+ @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 without assignment" do
- @root.app = "/foo/bar"
- @root.app.models "/foo/bar/baz"
- assert_equal ["/foo/bar/baz"], @root.app.models.to_a
+ 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.app = "/app"
- @root.app.models = "baz"
-
- assert_equal ["/foo/bar/baz"], @root.app.models.to_a
+ @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.app = ["/app", "/app2"]
- assert_equal ["/app", "/app2"], @root.app.to_a
- end
-
- test "adding multiple physical paths as an array without assignment" do
- @root.app "/app", "/app2"
- assert_equal ["/app", "/app2"], @root.app.to_a
+ @root.add "app", :with => ["/app", "/app2"]
+ assert_equal ["/app", "/app2"], @root["app"].to_a
end
test "adding multiple physical paths using #push" do
- @root.app = "/app"
- @root.app.push "/app2"
- assert_equal ["/app", "/app2"], @root.app.to_a
+ @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.app = "/app"
- @root.app << "/app2"
- assert_equal ["/app", "/app2"], @root.app.to_a
+ @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.app = "/app"
- @root.app.concat ["/app2", "/app3"]
- assert_equal ["/app", "/app2", "/app3"], @root.app.to_a
+ @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.app = "/app"
- @root.app.unshift "/app2"
- assert_equal ["/app2", "/app"], @root.app.to_a
+ @root.add "app"
+ @root["app"].unshift "app2"
+ assert_equal ["/foo/bar/app2", "/foo/bar/app"], @root["app"].to_a
end
test "the root can only have one physical path" do
assert_raise(RuntimeError) { Rails::Paths::Root.new(["/fiz", "/biz"]) }
- assert_raise(RuntimeError) { @root.push "/biz" }
- assert_raise(RuntimeError) { @root.unshift "/biz" }
- assert_raise(RuntimeError) { @root.concat ["/biz"]}
- assert_raise(RuntimeError) { @root << "/biz" }
end
test "it is possible to add a path that should be autoloaded only once" do
- @root.app = "/app"
- @root.app.autoload_once!
- assert @root.app.autoload_once?
- assert @root.autoload_once.include?(@root.app.paths.first)
+ @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"] = "/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.paths.first)
+ @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.app "/app", :autoload_once => true
- assert @root.app.autoload_once?
+ @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.app "/app", "/app2", :autoload_once => true
- assert @root.app.autoload_once?
+ @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.paths.first }.size
+ @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"
+ @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.paths.first)
+ @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"] = "/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.paths.first)
+ @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.app "/app", :eager_load => true
- assert @root.app.eager_load?
+ @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.app "/app", "/app2", :eager_load => true
- assert @root.app.eager_load?
+ @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.app "/app", :eager_load => true, :autoload_once => true
- assert @root.app.eager_load?
- assert @root.app.autoload_once?
+ @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.paths.first }.size
+ @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"
+ @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
+ @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.app "/app", :glob => "*.rb"
- assert_equal "*.rb", @root.app.glob
+ @root.add "app", :with => "/app", :glob => "*.rb"
+ 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"
+ @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.app "/app", :load_path => true
- assert @root.app.load_path?
+ @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"
+ @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.app "/app", :autoload => true
- assert @root.app.autoload?
+ @root.add "app", :with => "/app", :autoload => true
+ assert @root["app"].autoload?
assert_equal ["/app"], @root.autoload_paths
end
+
+ # Deprecated API tests
+
+ test "reading a root level path with assignment" do
+ @root.add "app"
+ assert_deprecated do
+ assert_equal ["/foo/bar/app"], @root.app.to_a
+ end
+ end
+
+ test "creating a root level path with assignment" do
+ assert_deprecated do
+ @root.app = "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app"].to_a
+ end
+
+ test "creating a root level path without assignment" do
+ assert_deprecated do
+ @root.app "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app"].to_a
+ end
+
+ test "reading a nested level path with assignment" do
+ @root.add "app"
+ @root.add "app/model"
+ assert_deprecated do
+ assert_equal ["/foo/bar/app/model"], @root.app.model.to_a
+ end
+ end
+
+ test "creating a nested level path with assignment" do
+ @root.add "app"
+ assert_deprecated do
+ @root.app.model = "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app/model"].to_a
+ end
+
+ test "creating a nested level path without assignment" do
+ @root.add "app"
+ assert_deprecated do
+ @root.app.model "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app/model"].to_a
+ end
+
+ test "trying to access a path that does not exist raises NoMethodError" do
+ assert_deprecated do
+ assert_raises(NoMethodError) { @root.app }
+ end
+ end
end
diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb
index 687c2d1568..9d194f41a6 100644
--- a/railties/test/rails_info_controller_test.rb
+++ b/railties/test/rails_info_controller_test.rb
@@ -14,26 +14,28 @@ class InfoControllerTest < ActionController::TestCase
Rails.application.routes.draw do
match '/rails/info/properties' => "rails/info#properties"
end
- @controller.stubs(:consider_all_requests_local? => false, :local_request? => true)
+ @request.stubs(:local? => true)
+ @controller.stubs(:consider_all_requests_local? => false)
@routes = Rails.application.routes
Rails::InfoController.send(:include, @routes.url_helpers)
end
test "info controller does not allow remote requests" do
- @controller.stubs(:consider_all_requests_local? => false, :local_request? => false)
+ @request.stubs(:local? => false)
get :properties
assert_response :forbidden
end
test "info controller renders an error message when request was forbidden" do
- @controller.stubs(:consider_all_requests_local? => false, :local_request? => false)
+ @request.stubs(:local? => false)
get :properties
assert_select 'p'
end
test "info controller allows requests when all requests are considered local" do
- @controller.stubs(:consider_all_requests_local? => true, :local_request? => false)
+ @request.stubs(:local? => false)
+ @controller.stubs(:consider_all_requests_local? => true)
get :properties
assert_response :success
end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 7410a10712..0ce00db3c4 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -1,10 +1,15 @@
require "isolation/abstract_unit"
require "railties/shared_tests"
+require 'stringio'
+require 'rack/test'
+require 'rack/file'
module RailtiesTest
class EngineTest < Test::Unit::TestCase
+
include ActiveSupport::Testing::Isolation
include SharedTests
+ include Rack::Test::Methods
def setup
build_app
@@ -13,6 +18,7 @@ module RailtiesTest
plugin.write "lib/bukkits.rb", <<-RUBY
class Bukkits
class Engine < ::Rails::Engine
+ railtie_name "bukkits"
end
end
RUBY
@@ -50,5 +56,750 @@ module RailtiesTest
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
+ class 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 "it provides routes as default endpoint" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ match "/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 "engine can load its own plugins" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY
+ config.yaffle_loaded = true
+ RUBY
+
+ boot_rails
+
+ assert Bukkits::Engine.config.yaffle_loaded
+ end
+
+ test "engine does not load plugins that already exists in application" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY
+ config.engine_yaffle_loaded = true
+ RUBY
+
+ app_file "vendor/plugins/yaffle/init.rb", <<-RUBY
+ config.app_yaffle_loaded = true
+ RUBY
+
+ warnings = capture(:stderr) { boot_rails }
+
+ assert !warnings.empty?
+ assert !Bukkits::Engine.config.respond_to?(:engine_yaffle_loaded)
+ assert Rails.application.config.app_yaffle_loaded
+ end
+
+ test "it loads its environment file" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ @plugin.write "config/environments/development.rb", <<-RUBY
+ Bukkits::Engine.configure do
+ config.environment_loaded = true
+ end
+ RUBY
+
+ boot_rails
+
+ assert Bukkits::Engine.config.environment_loaded
+ end
+
+ test "it passes router in env" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ endpoint lambda { |env| [200, {'Content-Type' => 'text/html'}, 'hello'] }
+ end
+ end
+ RUBY
+
+ 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 "it allows to set asset_path" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ match "/foo" => "foo#index"
+ end
+ RUBY
+
+ @plugin.write "app/controllers/foo_controller.rb", <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :index
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/foo/index.html.erb", <<-ERB
+ <%= image_path("foo.png") %>
+ <%= javascript_include_tag("foo") %>
+ <%= stylesheet_link_tag("foo") %>
+ ERB
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ add_to_config 'config.asset_path = "/omg%s"'
+
+ boot_rails
+
+ # should set asset_path with engine name by default
+ assert_equal "/bukkits_engine%s", ::Bukkits::Engine.config.asset_path
+
+ ::Bukkits::Engine.config.asset_path = "/bukkits%s"
+
+ get("/bukkits/foo")
+ stripped_body = last_response.body.split("\n").map(&:strip).join
+
+ expected = "/omg/bukkits/images/foo.png" +
+ "<script src=\"/omg/bukkits/javascripts/foo.js\" type=\"text/javascript\"></script>" +
+ "<link href=\"/omg/bukkits/stylesheets/foo.css\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />"
+ assert_equal expected, stripped_body
+ end
+
+ test "default application's asset_path" do
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ match "/foo" => "foo#index"
+ end
+ RUBY
+
+ @plugin.write "app/controllers/foo_controller.rb", <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :inline => '<%= image_path("foo.png") %>'
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ boot_rails
+
+ get("/bukkits/foo")
+ assert_equal "/bukkits/images/foo.png", last_response.body.strip
+ end
+
+ test "engine's files are served via ActionDispatch::Static" do
+ add_to_config "config.serve_static_assets = true"
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ engine_name :bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "public/bukkits.html", "/bukkits/bukkits.html"
+ app_file "public/app.html", "/app.html"
+ app_file "public/bukkits/file_from_app.html", "/bukkits/file_from_app.html"
+
+ boot_rails
+
+ get("/app.html")
+ assert_equal File.read(File.join(app_path, "public/app.html")), last_response.body
+
+ get("/bukkits/bukkits.html")
+ assert_equal File.read(File.join(@plugin.path, "public/bukkits.html")), last_response.body
+
+ get("/bukkits/file_from_app.html")
+ assert_equal File.read(File.join(app_path, "public/bukkits/file_from_app.html")), last_response.body
+ end
+
+ test "an applications files are given priority over an engines files when served via ActionDispatch::Static" do
+ add_to_config "config.serve_static_assets = true"
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ engine_name :bukkits
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ @plugin.write "public/bukkits.html", "in engine"
+
+ app_file "public/bukkits/bukkits.html", "in app"
+
+ boot_rails
+
+ get('/bukkits/bukkits.html')
+
+ assert_equal 'in app', last_response.body.strip
+ end
+
+ test "shared engine should include application's helpers and own helpers" do
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match "/foo" => "bukkits/foo#index", :as => "foo"
+ match "/foo/show" => "bukkits/foo#show"
+ match "/foo/bar" => "bukkits/foo#bar"
+ end
+ RUBY
+
+ app_file "app/helpers/some_helper.rb", <<-RUBY
+ module SomeHelper
+ def something
+ "Something... Something... Something..."
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/bar_helper.rb", <<-RUBY
+ module BarHelper
+ def bar
+ "It's a bar."
+ end
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/foo_controller.rb", <<-RUBY
+ class Bukkits::FooController < ActionController::Base
+ def index
+ render :inline => "<%= something %>"
+ end
+
+ def show
+ render :text => foo_path
+ end
+
+ def bar
+ render :inline => "<%= bar %>"
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ get("/foo")
+ assert_equal "Something... Something... Something...", last_response.body
+
+ get("/foo/show")
+ assert_equal "/foo", last_response.body
+
+ get("/foo/bar")
+ assert_equal "It's a bar.", last_response.body
+ end
+
+ test "isolated engine should include only its own routes and helpers" do
+ @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
+ match "/bar" => "bar#index", :as => "bar"
+ mount Bukkits::Engine => "/bukkits", :as => "bukkits"
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ match "/foo" => "foo#index", :as => "foo"
+ match "/foo/show" => "foo#show"
+ match "/from_app" => "foo#from_app"
+ match "/routes_helpers_in_view" => "foo#routes_helpers_in_view"
+ match "/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, 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 "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) do Bukkits::Engine.config.bukkits_seeds_loaded end
+
+ Bukkits::Engine.load_seed
+ assert Bukkits::Engine.config.bukkits_seeds_loaded
+ end
+
+ test "using namespace more than once on one module should not overwrite _railtie method" do
+ @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, 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
+
+ require "#{rails_root}/config/environment"
+
+ 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 :datamapper
+ 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
+ require "#{rails_root}/config/environment"
+
+ 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 :datamapper, 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
+ require "#{rails_root}/config/environment"
+
+ 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
+ require "#{rails_root}/config/environment"
+
+ 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
+ require "#{rails_root}/config/environment"
+
+ 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 "ensure that engine properly sets assets directories" do
+ add_to_config("config.action_dispatch.show_exceptions = false")
+ add_to_config("config.serve_static_assets = true")
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "public/stylesheets/foo.css", ""
+ @plugin.write "public/javascripts/foo.js", ""
+
+ @plugin.write "app/views/layouts/bukkits/application.html.erb", <<-RUBY
+ <%= stylesheet_link_tag :all %>
+ <%= javascript_include_tag :all %>
+ <%= yield %>
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/home_controller.rb", <<-RUBY
+ module Bukkits
+ class HomeController < ActionController::Base
+ def index
+ render :text => "Good morning!", :layout => "bukkits/application"
+ end
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ match "/home" => "home#index"
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ boot_rails
+
+ require "#{rails_root}/config/environment"
+
+ assert_equal File.join(@plugin.path, "public"), Bukkits::HomeController.assets_dir
+ assert_equal File.join(@plugin.path, "public/stylesheets"), Bukkits::HomeController.stylesheets_dir
+ assert_equal File.join(@plugin.path, "public/javascripts"), Bukkits::HomeController.javascripts_dir
+
+ assert_equal File.join(app_path, "public"), ActionController::Base.assets_dir
+ assert_equal File.join(app_path, "public/stylesheets"), ActionController::Base.stylesheets_dir
+ assert_equal File.join(app_path, "public/javascripts"), ActionController::Base.javascripts_dir
+
+ get "/bukkits/home"
+
+ assert_match %r{bukkits/stylesheets/foo.css}, last_response.body
+ assert_match %r{bukkits/javascripts/foo.js}, last_response.body
+ end
+
+ private
+ def app
+ Rails.application
+ end
end
end
diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb
new file mode 100644
index 0000000000..47a4753e78
--- /dev/null
+++ b/railties/test/railties/mounted_engine_test.rb
@@ -0,0 +1,174 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class ApplicationRoutingTest < Test::Unit::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")
+
+ @plugin = engine "blog"
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match "/engine_route" => "application_generating#engine_route"
+ match "/engine_route_in_view" => "application_generating#engine_route_in_view"
+ match "/url_for_engine_route" => "application_generating#url_for_engine_route"
+ match "/polymorphic_route" => "application_generating#polymorphic_route"
+ scope "/:user", :user => "anonymous" do
+ mount Blog::Engine => "/blog"
+ end
+ root :to => 'main#index'
+ 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
+ match '/generate_application_route', :to => 'posts#generate_application_route'
+ match '/application_route_in_view', :to => 'posts#application_route_in_view'
+ 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
+ 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 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
+ end
+ RUBY
+
+ boot_rails
+ end
+
+ def app
+ @app ||= begin
+ require "#{app_path}/config/environment"
+ Rails.application
+ end
+ end
+
+ def reset_script_name!
+ Rails.application.routes.default_url_options = {}
+ end
+
+ def script_name(script_name)
+ Rails.application.routes.default_url_options = {:script_name => script_name}
+ end
+
+ test "routes generation in engine and application" do
+ # test generating engine's route from engine
+ get "/john/blog/posts"
+ assert_equal "/john/blog/posts/1", last_response.body
+
+ # test generating engine's route from engine with default_url_options
+ script_name "/foo"
+ get "/john/blog/posts", {}, 'SCRIPT_NAME' => "/foo"
+ assert_equal "/foo/john/blog/posts/1", last_response.body
+ reset_script_name!
+
+ # test generating engine's route from application
+ get "/engine_route"
+ 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
+ script_name "/foo"
+ get "/engine_route", {}, 'SCRIPT_NAME' => "/foo"
+ assert_equal "/foo/anonymous/blog/posts", last_response.body
+
+ script_name "/foo"
+ get "/url_for_engine_route", {}, 'SCRIPT_NAME' => "/foo"
+ assert_equal "/foo/john/blog/posts", last_response.body
+ reset_script_name!
+
+ # test generating application's route from engine
+ get "/someone/blog/generate_application_route"
+ 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
+ script_name "/foo"
+ get "/someone/blog/generate_application_route", {}, 'SCRIPT_NAME' => '/foo'
+ assert_equal "/foo/", last_response.body
+ reset_script_name!
+
+ # test polymorphic routes
+ get "/polymorphic_route"
+ assert_equal "http://example.org/anonymous/blog/posts/44", last_response.body
+ end
+ end
+end
+
diff --git a/railties/test/railties/plugin_test.rb b/railties/test/railties/plugin_test.rb
index b143f56484..c15ac05103 100644
--- a/railties/test/railties/plugin_test.rb
+++ b/railties/test/railties/plugin_test.rb
@@ -110,37 +110,10 @@ module RailtiesTest
boot_rails
rescue Exception => e
rescued = true
- assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as plugin', e.message
+ assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as a plugin', e.message
end
assert rescued, "Expected boot rails to fail"
end
-
- test "loads deprecated rails/init.rb" do
- @plugin.write "rails/init.rb", <<-RUBY
- $loaded = true
- RUBY
-
- boot_rails
- assert $loaded
- end
-
- test "deprecated tasks are also loaded" do
- $executed = false
- @plugin.write "tasks/foo.rake", <<-RUBY
- task :foo do
- $executed = true
- end
- RUBY
-
- boot_rails
- require 'rake'
- require 'rake/rdoctask'
- require 'rake/testtask'
- Rails.application.load_tasks
- Rake::Task[:foo].invoke
- assert $executed
- end
-
end
end
diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb
index db0fd87491..7ea8364ae9 100644
--- a/railties/test/railties/railtie_test.rb
+++ b/railties/test/railties/railtie_test.rb
@@ -19,6 +19,22 @@ module RailtiesTest
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 manualy" 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
@@ -87,6 +103,30 @@ module RailtiesTest
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 'rake/rdoctask'
+
+ 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
@@ -132,7 +172,7 @@ module RailtiesTest
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
diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb
index ce7c55c11c..3eb79d57c8 100644
--- a/railties/test/railties/shared_tests.rb
+++ b/railties/test/railties/shared_tests.rb
@@ -10,6 +10,100 @@ module RailtiesTest
@app ||= Rails.application
end
+ def test_install_migrations_and_assets
+ @plugin.write "public/javascripts/foo.js", "doSomething()"
+
+ @plugin.write "db/migrate/1_create_users.rb", <<-RUBY
+ class CreateUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ app_file "db/migrate/1_create_sessions.rb", <<-RUBY
+ class CreateSessions < ActiveRecord::Migration
+ end
+ RUBY
+
+ add_to_config "ActiveRecord::Base.timestamped_migrations = false"
+
+ Dir.chdir(app_path) do
+ `rake bukkits:install`
+ assert File.exists?("#{app_path}/db/migrate/2_create_users.rb")
+ assert File.exists?(app_path("public/bukkits/javascripts/foo.js"))
+ end
+ end
+
+ def test_copying_assets
+ @plugin.write "public/javascripts/foo.js", "doSomething()"
+ @plugin.write "public/stylesheets/foo.css", "h1 { font-size: 10000px }"
+ @plugin.write "public/images/img.png", ""
+
+ Dir.chdir(app_path) do
+ `rake bukkits:install:assets --trace`
+
+ assert File.exists?(app_path("public/bukkits/javascripts/foo.js"))
+ assert_equal "doSomething()\n", File.read(app_path("public/bukkits/javascripts/foo.js"))
+ assert File.exists?(app_path("public/bukkits/stylesheets/foo.css"))
+ assert_equal "h1 { font-size: 10000px }\n", File.read(app_path("public/bukkits/stylesheets/foo.css"))
+ assert File.exists?(app_path("public/bukkits/images/img.png"))
+ end
+ end
+
+ def test_copying_migrations
+ @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
+ end
+ RUBY
+
+ yaffle = plugin "acts_as_yaffle", "::LEVEL = config.log_level" do |plugin|
+ plugin.write "lib/acts_as_yaffle.rb", "class ActsAsYaffle; end"
+ end
+
+ yaffle.write "db/migrate/1_create_yaffles.rb", <<-RUBY
+ class CreateYaffles < ActiveRecord::Migration
+ end
+ RUBY
+
+ add_to_config "ActiveRecord::Base.timestamped_migrations = false"
+
+ Dir.chdir(app_path) do
+ output = `rake bukkits:install:migrations`
+
+ assert File.exists?("#{app_path}/db/migrate/2_create_users.rb")
+ assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.rb")
+ assert_match /Copied migration 2_create_users.rb from bukkits/, output
+ assert_match /Copied migration 3_add_last_name_to_users.rb from bukkits/, output
+ assert_match /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output
+ assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length
+
+ output = `rake railties:install:migrations`
+
+ assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.rb")
+ assert_match /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output
+ assert_match /Copied migration 4_create_yaffles.rb from acts_as_yaffle/, output
+ assert_no_match /2_create_users/, output
+
+ migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length
+ output = `rake railties:install:migrations`
+
+ assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length
+ end
+ end
+
def test_puts_its_lib_directory_on_load_path
boot_rails
require "another"
@@ -129,7 +223,7 @@ module RailtiesTest
RUBY
app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do |map|
+ AppTemplate::Application.routes.draw do
match 'foo', :to => 'foo#index'
end
RUBY
@@ -143,7 +237,7 @@ module RailtiesTest
RUBY
@plugin.write "config/routes.rb", <<-RUBY
- Rails.application.routes.draw do |map|
+ Rails.application.routes.draw do
match 'foo', :to => 'bar#index'
match 'bar', :to => 'bar#index'
end
@@ -200,7 +294,7 @@ YAML
boot_rails
- assert_equal %W(
+ expected_locales = %W(
#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml
#{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml
#{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml
@@ -208,7 +302,13 @@ YAML
#{@plugin.path}/config/locales/en.yml
#{app_path}/config/locales/en.yml
#{app_path}/app/locales/en.yml
- ).map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) }
+ ).map { |path| File.expand_path(path) }
+
+ actual_locales = I18n.load_path.map { |path|
+ File.expand_path(path)
+ } & expected_locales # remove locales external to Rails
+
+ assert_equal expected_locales, actual_locales
assert_equal "2", I18n.t(:foo)
assert_equal "1", I18n.t(:bar)
diff --git a/railties/test/script_rails_loader_test.rb b/railties/test/script_rails_loader_test.rb
index 2a87e5cb58..3ccc147749 100644
--- a/railties/test/script_rails_loader_test.rb
+++ b/railties/test/script_rails_loader_test.rb
@@ -2,21 +2,21 @@ require 'abstract_unit'
require 'rails/script_rails_loader'
class ScriptRailsLoaderTest < ActiveSupport::TestCase
-
+
test "is in a rails application if script/rails exists" do
File.stubs(:exists?).returns(true)
assert Rails::ScriptRailsLoader.in_rails_application?
end
-
+
test "is in a rails application if parent directory has script/rails" do
File.stubs(:exists?).with("/foo/bar/script/rails").returns(false)
File.stubs(:exists?).with("/foo/script/rails").returns(true)
assert Rails::ScriptRailsLoader.in_rails_application_subdirectory?(Pathname.new("/foo/bar"))
end
-
+
test "is not in a rails application if at the root directory and doesn't have script/rails" do
Pathname.any_instance.stubs(:root?).returns true
assert !Rails::ScriptRailsLoader.in_rails_application?
end
-
+
end \ No newline at end of file
diff --git a/release.rb b/release.rb
deleted file mode 100644
index 2076515f0e..0000000000
--- a/release.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-version = ARGV.pop
-
-%w( activesupport activemodel activerecord activeresource actionpack actionmailer railties ).each do |framework|
- puts "Building and pushing #{framework}..."
- `cd #{framework} && gem build #{framework}.gemspec && gem push #{framework}-#{version}.gem && rm #{framework}-#{version}.gem`
-end
-
-puts "Building and pushing Rails..."
-`gem build rails.gemspec`
-`gem push rails-#{version}.gem`
-`rm rails-#{version}.gem` \ No newline at end of file
diff --git a/tasks/release.rb b/tasks/release.rb
new file mode 100644
index 0000000000..a605fed160
--- /dev/null
+++ b/tasks/release.rb
@@ -0,0 +1,96 @@
+FRAMEWORKS = %w( activesupport activemodel activerecord activeresource actionpack actionmailer railties )
+
+root = File.expand_path('../../', __FILE__)
+version = File.read("#{root}/RAILS_VERSION").strip
+tag = "v#{version}"
+
+directory "dist"
+
+(FRAMEWORKS + ['rails']).each do |framework|
+ namespace framework do
+ gem = "dist/#{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)
+
+ major, minor, tiny, pre = version.split('.')
+ pre = pre ? pre.inspect : "nil"
+
+ ruby.gsub! /^(\s*)MAJOR = .*?$/, "\\1MAJOR = #{major}"
+ raise "Could not insert MAJOR in #{file}" unless $1
+
+ ruby.gsub! /^(\s*)MINOR = .*?$/, "\\1MINOR = #{minor}"
+ raise "Could not insert MINOR in #{file}" unless $1
+
+ ruby.gsub! /^(\s*)TINY = .*?$/, "\\1TINY = #{tiny}"
+ raise "Could not insert TINY in #{file}" unless $1
+
+ ruby.gsub! /^(\s*)PRE = .*?$/, "\\1PRE = #{pre}"
+ raise "Could not insert PRE in #{file}" unless $1
+
+ File.open(file, 'w') { |f| f.write ruby }
+ end
+
+ task gem => %w(update_version_rb dist) do
+ cmd = ""
+ cmd << "cd #{framework} && " unless framework == "rails"
+ cmd << "gem build #{gemspec} && mv #{framework}-#{version}.gem #{root}/dist/"
+ 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 :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('dist/commit_message.txt', 'w') do |f|
+ f.puts "# Preparing for #{version} release\n"
+ f.puts
+ f.puts "# UNCOMMENT THE LINE ABOVE TO APPROVE THIS COMMIT"
+ end
+
+ sh "git add . && git commit --verbose --template=dist/commit_message.txt"
+ rm_f "dist/commit_message.txt"
+ end
+
+ task :tag do
+ sh "git tag #{tag}"
+ end
+
+ task :release => %w(ensure_clean_state build commit tag push)
+end
diff --git a/version.rb b/version.rb
index c5d1d02bc1..b076881c21 100644
--- a/version.rb
+++ b/version.rb
@@ -1,10 +1,10 @@
module Rails
module VERSION #:nodoc:
MAJOR = 3
- MINOR = 0
+ MINOR = 1
TINY = 0
- BUILD = "rc"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end