aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore8
-rw-r--r--.gitmodules6
-rw-r--r--Gemfile24
-rw-r--r--Rakefile22
-rw-r--r--actionmailer/CHANGELOG24
-rw-r--r--actionmailer/Rakefile1
-rw-r--r--actionmailer/actionmailer.gemspec1
-rw-r--r--actionmailer/lib/action_mailer.rb37
-rw-r--r--actionmailer/lib/action_mailer/adv_attr_accessor.rb32
-rw-r--r--actionmailer/lib/action_mailer/base.rb219
-rw-r--r--actionmailer/lib/action_mailer/delivery_method.rb5
-rw-r--r--actionmailer/lib/action_mailer/delivery_method/file.rb4
-rw-r--r--actionmailer/lib/action_mailer/delivery_method/smtp.rb7
-rw-r--r--actionmailer/lib/action_mailer/deprecated_body.rb8
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb33
-rw-r--r--actionmailer/lib/action_mailer/part.rb107
-rw-r--r--actionmailer/lib/action_mailer/part_container.rb55
-rw-r--r--actionmailer/lib/action_mailer/quoting.rb2
-rw-r--r--actionmailer/lib/action_mailer/railtie.rb25
-rw-r--r--actionmailer/lib/action_mailer/test_case.rb5
-rw-r--r--actionmailer/lib/action_mailer/tmail_compat.rb20
-rw-r--r--actionmailer/lib/action_mailer/utils.rb7
-rwxr-xr-xactionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb2933
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb5
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb426
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb46
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb46
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb41
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb67
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb63
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb581
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb960
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb9
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb1130
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb3
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb579
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb495
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb6
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb3
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb248
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb132
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb1478
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb379
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb118
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb58
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb49
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb261
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb280
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb337
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb39
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail.rb18
-rw-r--r--actionmailer/test/abstract_unit.rb7
-rw-r--r--actionmailer/test/adv_attr_test.rb32
-rw-r--r--actionmailer/test/asset_host_test.rb6
-rw-r--r--actionmailer/test/fixtures/attachments/foo.jpgbin0 -> 2029 bytes
-rw-r--r--actionmailer/test/fixtures/attachments/test.jpgbin0 -> 2029 bytes
-rw-r--r--actionmailer/test/mail_helper_test.rb4
-rw-r--r--actionmailer/test/mail_layout_test.rb62
-rw-r--r--actionmailer/test/mail_render_test.rb47
-rw-r--r--actionmailer/test/mail_service_test.rb354
-rw-r--r--actionmailer/test/mail_test.rb24
-rw-r--r--actionmailer/test/quoting_test.rb29
-rw-r--r--actionmailer/test/test_helper_test.rb12
-rw-r--r--actionmailer/test/tmail_compat_test.rb23
-rw-r--r--actionmailer/test/tmail_test.rb22
-rw-r--r--actionmailer/test/url_test.rb58
-rw-r--r--actionpack/CHANGELOG14
-rw-r--r--actionpack/Rakefile2
-rw-r--r--actionpack/actionpack.gemspec4
-rw-r--r--actionpack/lib/abstract_controller.rb28
-rw-r--r--actionpack/lib/abstract_controller/base.rb30
-rw-r--r--actionpack/lib/abstract_controller/exceptions.rb12
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb2
-rw-r--r--actionpack/lib/abstract_controller/layouts.rb162
-rw-r--r--actionpack/lib/abstract_controller/localized_cache.rb2
-rw-r--r--actionpack/lib/abstract_controller/logger.rb48
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb (renamed from actionpack/lib/abstract_controller/rendering_controller.rb)51
-rw-r--r--actionpack/lib/action_controller.rb120
-rw-r--r--actionpack/lib/action_controller/base.rb76
-rw-r--r--actionpack/lib/action_controller/caching.rb24
-rw-r--r--actionpack/lib/action_controller/caching/fragments.rb2
-rw-r--r--actionpack/lib/action_controller/dispatch/dispatcher.rb5
-rw-r--r--actionpack/lib/action_controller/metal.rb26
-rw-r--r--actionpack/lib/action_controller/metal/benchmarking.rb73
-rw-r--r--actionpack/lib/action_controller/metal/compatibility.rb7
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb2
-rw-r--r--actionpack/lib/action_controller/metal/cookies.rb106
-rw-r--r--actionpack/lib/action_controller/metal/exceptions.rb11
-rw-r--r--actionpack/lib/action_controller/metal/filter_parameter_logging.rb22
-rw-r--r--actionpack/lib/action_controller/metal/flash.rb89
-rw-r--r--actionpack/lib/action_controller/metal/head.rb7
-rw-r--r--actionpack/lib/action_controller/metal/helpers.rb2
-rw-r--r--actionpack/lib/action_controller/metal/layouts.rb171
-rw-r--r--actionpack/lib/action_controller/metal/logger.rb89
-rw-r--r--actionpack/lib/action_controller/metal/rack_delegation.rb (renamed from actionpack/lib/action_controller/metal/rack_convenience.rb)10
-rw-r--r--actionpack/lib/action_controller/metal/redirecting.rb90
-rw-r--r--actionpack/lib/action_controller/metal/redirector.rb22
-rw-r--r--actionpack/lib/action_controller/metal/render_options.rb103
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb91
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb (renamed from actionpack/lib/action_controller/metal/rendering_controller.rb)16
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb39
-rw-r--r--actionpack/lib/action_controller/metal/rescue.rb (renamed from actionpack/lib/action_controller/metal/rescuable.rb)0
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb20
-rw-r--r--actionpack/lib/action_controller/metal/session.rb15
-rw-r--r--actionpack/lib/action_controller/metal/streaming.rb2
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb2
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb2
-rw-r--r--actionpack/lib/action_controller/metal/verification.rb70
-rw-r--r--actionpack/lib/action_controller/notifications.rb10
-rw-r--r--actionpack/lib/action_controller/railtie.rb96
-rw-r--r--actionpack/lib/action_controller/test_case.rb (renamed from actionpack/lib/action_controller/testing/test_case.rb)3
-rw-r--r--actionpack/lib/action_controller/testing/process.rb111
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner.rb28
-rw-r--r--actionpack/lib/action_dispatch.rb56
-rw-r--r--actionpack/lib/action_dispatch/http/headers.rb14
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb6
-rwxr-xr-xactionpack/lib/action_dispatch/http/request.rb14
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb41
-rw-r--r--actionpack/lib/action_dispatch/http/status_codes.rb42
-rw-r--r--actionpack/lib/action_dispatch/http/utils.rb20
-rw-r--r--actionpack/lib/action_dispatch/middleware/cascade.rb29
-rw-r--r--actionpack/lib/action_dispatch/middleware/params_parser.rb47
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/abstract_store.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cookie_store.rb11
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb16
-rw-r--r--actionpack/lib/action_dispatch/middleware/stack.rb5
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb2
-rw-r--r--actionpack/lib/action_dispatch/routing.rb107
-rw-r--r--actionpack/lib/action_dispatch/routing/deprecated_mapper.rb5
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb624
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb260
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/dom.rb4
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb48
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/selector.rb22
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/tag.rb21
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb12
-rw-r--r--actionpack/lib/action_dispatch/testing/performance_test.rb24
-rw-r--r--actionpack/lib/action_dispatch/testing/test_process.rb42
-rw-r--r--actionpack/lib/action_view.rb56
-rw-r--r--actionpack/lib/action_view/base.rb3
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb42
-rw-r--r--actionpack/lib/action_view/helpers/sanitize_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/translation_helper.rb2
-rw-r--r--actionpack/lib/action_view/paths.rb2
-rw-r--r--actionpack/lib/action_view/railtie.rb2
-rw-r--r--actionpack/lib/action_view/render/partials.rb100
-rw-r--r--actionpack/lib/action_view/render/rendering.rb63
-rw-r--r--actionpack/lib/action_view/safe_buffer.rb1
-rw-r--r--actionpack/lib/action_view/template.rb (renamed from actionpack/lib/action_view/template/template.rb)38
-rw-r--r--actionpack/lib/action_view/template/error.rb156
-rw-r--r--actionpack/lib/action_view/template/handler.rb47
-rw-r--r--actionpack/lib/action_view/template/handlers.rb96
-rw-r--r--actionpack/lib/action_view/template/handlers/builder.rb4
-rw-r--r--actionpack/lib/action_view/template/handlers/erb.rb7
-rw-r--r--actionpack/lib/action_view/template/handlers/rjs.rb4
-rw-r--r--actionpack/lib/action_view/template/resolver.rb18
-rw-r--r--actionpack/lib/action_view/template/text.rb70
-rw-r--r--actionpack/lib/action_view/test_case.rb5
-rw-r--r--actionpack/test/abstract/abstract_controller_test.rb2
-rw-r--r--actionpack/test/abstract/helper_test.rb2
-rw-r--r--actionpack/test/abstract/layouts_test.rb28
-rw-r--r--actionpack/test/abstract/localized_cache_test.rb2
-rw-r--r--actionpack/test/abstract/render_test.rb4
-rw-r--r--actionpack/test/abstract_unit.rb54
-rw-r--r--actionpack/test/active_record_unit.rb8
-rw-r--r--actionpack/test/activerecord/active_record_store_test.rb2
-rw-r--r--actionpack/test/activerecord/controller_runtime_test.rb39
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb22
-rw-r--r--actionpack/test/controller/base_test.rb13
-rw-r--r--actionpack/test/controller/benchmark_test.rb33
-rw-r--r--actionpack/test/controller/caching_test.rb12
-rw-r--r--actionpack/test/controller/cookie_test.rb35
-rw-r--r--actionpack/test/controller/dispatcher_test.rb13
-rw-r--r--actionpack/test/controller/filter_params_test.rb2
-rw-r--r--actionpack/test/controller/flash_test.rb45
-rw-r--r--actionpack/test/controller/helper_test.rb2
-rw-r--r--actionpack/test/controller/layout_test.rb2
-rw-r--r--actionpack/test/controller/logging_test.rb66
-rw-r--r--actionpack/test/controller/mime_responds_test.rb67
-rw-r--r--actionpack/test/controller/redirect_test.rb4
-rw-r--r--actionpack/test/controller/render_other_test.rb14
-rw-r--r--actionpack/test/controller/render_test.rb68
-rw-r--r--actionpack/test/controller/render_xml_test.rb4
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb20
-rw-r--r--actionpack/test/controller/resources_test.rb8
-rw-r--r--actionpack/test/controller/routing_test.rb317
-rw-r--r--actionpack/test/controller/test_test.rb25
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb10
-rw-r--r--actionpack/test/controller/webservice_test.rb4
-rw-r--r--actionpack/test/dispatch/request/multipart_params_parsing_test.rb2
-rw-r--r--actionpack/test/dispatch/response_test.rb121
-rw-r--r--actionpack/test/dispatch/routing_test.rb153
-rw-r--r--actionpack/test/dispatch/test_request_test.rb2
-rw-r--r--actionpack/test/lib/controller/fake_controllers.rb13
-rw-r--r--actionpack/test/lib/controller/fake_models.rb1
-rw-r--r--actionpack/test/template/ajax_test.rb12
-rw-r--r--actionpack/test/template/atom_feed_helper_test.rb12
-rw-r--r--actionpack/test/template/form_helper_test.rb40
-rw-r--r--actionpack/test/template/render_test.rb8
-rw-r--r--actionpack/test/template/test_case_test.rb4
-rw-r--r--actionpack/test/template/translation_helper_test.rb4
-rw-r--r--actionpack/test/template/url_helper_test.rb51
-rwxr-xr-xactivemodel/Rakefile1
-rw-r--r--activemodel/lib/active_model.rb47
-rw-r--r--activemodel/lib/active_model/callbacks.rb91
-rw-r--r--activemodel/lib/active_model/errors.rb11
-rw-r--r--activemodel/lib/active_model/lint.rb14
-rw-r--r--activemodel/lib/active_model/locale/en.yml3
-rw-r--r--activemodel/lib/active_model/naming.rb26
-rw-r--r--activemodel/lib/active_model/railtie.rb2
-rw-r--r--activemodel/lib/active_model/translation.rb22
-rw-r--r--activemodel/lib/active_model/validations.rb57
-rw-r--r--activemodel/lib/active_model/validations/acceptance.rb21
-rw-r--r--activemodel/lib/active_model/validations/confirmation.rb20
-rw-r--r--activemodel/lib/active_model/validations/exclusion.rb26
-rw-r--r--activemodel/lib/active_model/validations/format.rb28
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb26
-rw-r--r--activemodel/lib/active_model/validations/length.rb129
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb122
-rw-r--r--activemodel/lib/active_model/validations/presence.rb15
-rw-r--r--activemodel/lib/active_model/validations/with.rb11
-rw-r--r--activemodel/lib/active_model/validations_repair_helper.rb35
-rw-r--r--activemodel/lib/active_model/validator.rb56
-rw-r--r--activemodel/test/cases/callbacks_test.rb70
-rw-r--r--activemodel/test/cases/helper.rb7
-rw-r--r--activemodel/test/cases/lint_test.rb2
-rw-r--r--activemodel/test/cases/naming_test.rb3
-rw-r--r--activemodel/test/cases/tests_database.rb1
-rw-r--r--activemodel/test/cases/translation_test.rb36
-rw-r--r--activemodel/test/cases/validations/acceptance_validation_test.rb33
-rw-r--r--activemodel/test/cases/validations/conditional_validation_test.rb5
-rw-r--r--activemodel/test/cases/validations/confirmation_validation_test.rb34
-rw-r--r--activemodel/test/cases/validations/exclusion_validation_test.rb23
-rw-r--r--activemodel/test/cases/validations/format_validation_test.rb33
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb23
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb33
-rw-r--r--activemodel/test/cases/validations/length_validation_test.rb53
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb41
-rw-r--r--activemodel/test/cases/validations/presence_validation_test.rb54
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb66
-rw-r--r--activemodel/test/cases/validations_test.rb11
-rw-r--r--activemodel/test/models/person.rb6
-rw-r--r--activemodel/test/models/track_back.rb4
-rw-r--r--activerecord/CHANGELOG108
-rw-r--r--activerecord/lib/active_record.rb151
-rwxr-xr-xactiverecord/lib/active_record/associations.rb137
-rw-r--r--activerecord/lib/active_record/associations/association_collection.rb62
-rw-r--r--activerecord/lib/active_record/associations/association_proxy.rb2
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb44
-rw-r--r--activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb20
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb4
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb4
-rw-r--r--activerecord/lib/active_record/autosave_association.rb46
-rwxr-xr-xactiverecord/lib/active_record/base.rb449
-rw-r--r--activerecord/lib/active_record/calculations.rb202
-rw-r--r--activerecord/lib/active_record/callbacks.rb61
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb12
-rwxr-xr-xactiverecord/lib/active_record/connection_adapters/abstract_adapter.rb10
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb15
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb6
-rw-r--r--activerecord/lib/active_record/locale/en.yml3
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb42
-rw-r--r--activerecord/lib/active_record/named_scope.rb38
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb48
-rw-r--r--activerecord/lib/active_record/notifications.rb5
-rw-r--r--activerecord/lib/active_record/railtie.rb71
-rw-r--r--activerecord/lib/active_record/railties/controller_runtime.rb31
-rw-r--r--activerecord/lib/active_record/railties/databases.rake (renamed from railties/lib/rails/tasks/databases.rake)0
-rw-r--r--activerecord/lib/active_record/reflection.rb18
-rw-r--r--activerecord/lib/active_record/relation.rb214
-rw-r--r--activerecord/lib/active_record/relation/calculation_methods.rb177
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb120
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb45
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb141
-rw-r--r--activerecord/lib/active_record/relation/spawn_methods.rb75
-rw-r--r--activerecord/lib/active_record/validations.rb2
-rw-r--r--activerecord/lib/active_record/validations/associated.rb16
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb135
-rw-r--r--activerecord/test/cases/associations/eager_test.rb17
-rw-r--r--activerecord/test/cases/associations/habtm_join_table_test.rb16
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb1
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb22
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb6
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb30
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb292
-rw-r--r--activerecord/test/cases/associations_test.rb10
-rw-r--r--activerecord/test/cases/autosave_association_test.rb60
-rwxr-xr-xactiverecord/test/cases/base_test.rb41
-rw-r--r--activerecord/test/cases/batches_test.rb2
-rw-r--r--activerecord/test/cases/calculations_test.rb20
-rw-r--r--activerecord/test/cases/dirty_test.rb2
-rw-r--r--activerecord/test/cases/finder_test.rb65
-rw-r--r--activerecord/test/cases/helper.rb14
-rw-r--r--activerecord/test/cases/locking_test.rb20
-rw-r--r--activerecord/test/cases/method_scoping_test.rb174
-rw-r--r--activerecord/test/cases/migration_test.rb47
-rw-r--r--activerecord/test/cases/multiple_db_test.rb6
-rw-r--r--activerecord/test/cases/named_scope_test.rb4
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb53
-rw-r--r--activerecord/test/cases/readonly_test.rb41
-rw-r--r--activerecord/test/cases/relations_test.rb495
-rw-r--r--activerecord/test/cases/validations/association_validation_test.rb5
-rw-r--r--activerecord/test/cases/validations/i18n_validation_test.rb4
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb13
-rw-r--r--activerecord/test/cases/validations_repair_helper.rb23
-rw-r--r--activerecord/test/cases/validations_test.rb32
-rw-r--r--activerecord/test/cases/yaml_serialization_test.rb11
-rw-r--r--activerecord/test/fixtures/edges.yml3
-rw-r--r--activerecord/test/fixtures/faces.yml4
-rw-r--r--activerecord/test/fixtures/interests.yml6
-rw-r--r--activerecord/test/models/face.rb4
-rw-r--r--activerecord/test/models/interest.rb1
-rw-r--r--activerecord/test/models/man.rb2
-rw-r--r--activerecord/test/models/pirate.rb2
-rw-r--r--activerecord/test/models/reply.rb6
-rw-r--r--activerecord/test/models/ship.rb2
-rw-r--r--activerecord/test/schema/schema.rb6
-rw-r--r--activeresource/Rakefile3
-rw-r--r--activeresource/lib/active_resource.rb28
-rw-r--r--activeresource/lib/active_resource/base.rb143
-rw-r--r--activeresource/lib/active_resource/railtie.rb2
-rw-r--r--activeresource/lib/active_resource/schema.rb55
-rw-r--r--activeresource/test/abstract_unit.rb9
-rw-r--r--activeresource/test/cases/base/schema_test.rb420
-rw-r--r--activeresource/test/cases/base_test.rb6
-rw-r--r--activesupport/CHANGELOG4
-rw-r--r--activesupport/Rakefile1
-rw-r--r--activesupport/activesupport.gemspec2
-rw-r--r--activesupport/lib/active_support.rb38
-rw-r--r--activesupport/lib/active_support/all.rb1
-rw-r--r--activesupport/lib/active_support/autoload.rb28
-rw-r--r--activesupport/lib/active_support/benchmarkable.rb1
-rw-r--r--activesupport/lib/active_support/cache.rb1
-rw-r--r--activesupport/lib/active_support/cache/compressed_mem_cache_store.rb2
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb1
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache.rb1
-rw-r--r--activesupport/lib/active_support/callbacks.rb87
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/class/delegating_attributes.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/class/removal.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/date/conversions.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/calculations.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/conversions.rb15
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/hash/conversions.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/integer/multiple.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/loading.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/synchronization.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/object/blank.rb22
-rw-r--r--activesupport/lib/active_support/core_ext/object/extending.rb74
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_param.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_query.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/string.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/string/exclude.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/string/interpolation.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb46
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb1
-rw-r--r--activesupport/lib/active_support/dependencies/autoload.rb49
-rw-r--r--activesupport/lib/active_support/deprecated_callbacks.rb284
-rw-r--r--activesupport/lib/active_support/deprecation/method_wrappers.rb1
-rw-r--r--activesupport/lib/active_support/duration.rb1
-rw-r--r--activesupport/lib/active_support/i18n.rb2
-rw-r--r--activesupport/lib/active_support/json/encoding.rb13
-rw-r--r--activesupport/lib/active_support/message_encryptor.rb1
-rw-r--r--activesupport/lib/active_support/message_verifier.rb3
-rw-r--r--activesupport/lib/active_support/notifications.rb144
-rw-r--r--activesupport/lib/active_support/notifications/fanout.rb101
-rw-r--r--activesupport/lib/active_support/notifications/instrumenter.rb46
-rw-r--r--activesupport/lib/active_support/rescuable.rb2
-rw-r--r--activesupport/lib/active_support/ruby/shim.rb1
-rw-r--r--activesupport/lib/active_support/testing/isolation.rb79
-rw-r--r--activesupport/lib/active_support/testing/performance.rb679
-rw-r--r--activesupport/lib/active_support/testing/setup_and_teardown.rb73
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb1
-rw-r--r--activesupport/lib/active_support/vendor.rb2
-rwxr-xr-xactivesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE20
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile20
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile5
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec27
-rwxr-xr-xactivesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb204
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb215
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb53
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb5
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb99
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb124
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb1
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml3
-rw-r--r--activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb567
-rw-r--r--activesupport/lib/active_support/whiny_nil.rb5
-rw-r--r--activesupport/lib/active_support/xml_mini/jdom.rb2
-rw-r--r--activesupport/lib/active_support/xml_mini/libxml.rb110
-rw-r--r--activesupport/lib/active_support/xml_mini/libxmlsax.rb84
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogiri.rb51
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogirisax.rb82
-rw-r--r--activesupport/test/autoload.rb80
-rw-r--r--activesupport/test/callback_inheritance_test.rb35
-rw-r--r--activesupport/test/core_ext/blank_test.rb9
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb4
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb5
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb8
-rw-r--r--activesupport/test/core_ext/integer_ext_test.rb5
-rw-r--r--activesupport/test/core_ext/object/to_query_test.rb8
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb31
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb6
-rw-r--r--activesupport/test/deprecation_test.rb2
-rw-r--r--activesupport/test/fixtures/autoload/another_class.rb2
-rw-r--r--activesupport/test/fixtures/autoload/some_class.rb2
-rw-r--r--activesupport/test/isolation_test.rb262
-rw-r--r--activesupport/test/json/encoding_test.rb4
-rw-r--r--activesupport/test/notifications_test.rb278
-rw-r--r--activesupport/test/test_test.rb9
-rw-r--r--activesupport/test/whiny_nil_test.rb13
-rw-r--r--activesupport/test/xml_mini/libxml_engine_test.rb9
-rw-r--r--activesupport/test/xml_mini/libxmlsax_engine_test.rb194
-rw-r--r--activesupport/test/xml_mini/nokogiri_engine_test.rb40
-rw-r--r--activesupport/test/xml_mini/nokogirisax_engine_test.rb217
-rw-r--r--ci/geminstaller.yml2
m---------rack0
m---------rack-mount0
-rw-r--r--rails.gemspec (renamed from railties/rails.gemspec)12
-rw-r--r--railties/CHANGELOG22
-rw-r--r--railties/Rakefile76
-rwxr-xr-xrailties/bin/rails9
-rw-r--r--railties/builtin/routes.rb3
-rw-r--r--railties/lib/rails.rb99
-rw-r--r--railties/lib/rails/all.rb15
-rw-r--r--railties/lib/rails/application.rb295
-rw-r--r--railties/lib/rails/commands/console.rb89
-rw-r--r--railties/lib/rails/commands/dbconsole.rb171
-rwxr-xr-xrailties/lib/rails/commands/ncgi/tracker69
-rw-r--r--railties/lib/rails/commands/server.rb119
-rw-r--r--railties/lib/rails/configuration.rb121
-rw-r--r--railties/lib/rails/console_app.rb2
-rw-r--r--railties/lib/rails/core.rb73
-rw-r--r--railties/lib/rails/generators.rb191
-rw-r--r--railties/lib/rails/generators/actions.rb6
-rw-r--r--railties/lib/rails/generators/base.rb62
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb2
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb74
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile9
-rwxr-xr-xrailties/lib/rails/generators/rails/app/templates/Rakefile2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb8
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config.ru2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb70
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/boot.rb11
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environment.rb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb17
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt19
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb31
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt33
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb27
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt29
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt7
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/routes.rb57
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore3
-rwxr-xr-xrailties/lib/rails/generators/rails/app/templates/script/console.tt (renamed from railties/lib/rails/generators/rails/app/templates/script/console)1
-rwxr-xr-xrailties/lib/rails/generators/rails/app/templates/script/dbconsole.tt (renamed from railties/lib/rails/generators/rails/app/templates/script/dbconsole)1
-rwxr-xr-xrailties/lib/rails/generators/rails/app/templates/script/server2
-rwxr-xr-xrailties/lib/rails/generators/rails/app/templates/script/server.tt5
-rw-r--r--railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/Rakefile1
-rw-r--r--railties/lib/rails/generators/rails/resource/resource_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold/USAGE2
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb6
-rw-r--r--railties/lib/rails/generators/test_case.rb239
-rw-r--r--railties/lib/rails/generators/test_unit/model/templates/fixtures.yml14
-rw-r--r--railties/lib/rails/initializable.rb27
-rw-r--r--railties/lib/rails/initializer.rb17
-rw-r--r--railties/lib/rails/plugin.rb90
-rw-r--r--railties/lib/rails/rack/debugger.rb2
-rw-r--r--railties/lib/rails/rack/log_tailer.rb4
-rw-r--r--railties/lib/rails/rack/static.rb2
-rw-r--r--railties/lib/rails/railtie.rb43
-rw-r--r--railties/lib/rails/tasks.rb6
-rw-r--r--railties/lib/rails/tasks/framework.rake8
-rw-r--r--railties/lib/rails/tasks/misc.rake4
-rw-r--r--railties/lib/rails/tasks/testing.rake11
-rw-r--r--railties/lib/rails/test_help.rb10
-rw-r--r--railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb3
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/CHANGELOG.rdoc (renamed from railties/lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc)8
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/LICENSE (renamed from railties/lib/rails/vendor/thor-0.12.0/LICENSE)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/README.rdoc (renamed from railties/lib/rails/vendor/thor-0.12.0/README.rdoc)20
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/Thorfile (renamed from railties/lib/rails/vendor/thor-0.12.0/Thorfile)2
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb)84
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions.rb)11
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/create_file.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/create_file.rb)4
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/directory.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/directory.rb)6
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/empty_directory.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/empty_directory.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/file_manipulation.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/file_manipulation.rb)16
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/inject_into_file.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/inject_into_file.rb)2
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/base.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/base.rb)62
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/file_binary_read.rb9
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/hash_with_indifferent_access.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/hash_with_indifferent_access.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/ordered_hash.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/ordered_hash.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/error.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/error.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/group.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/group.rb)44
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/invocation.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/invocation.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/argument.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/argument.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/arguments.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/arguments.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/option.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/option.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/options.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/options.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/rake_compat.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/rake_compat.rb)0
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/runner.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/runner.rb)84
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb)2
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell/basic.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/basic.rb)78
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell/color.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/color.rb)2
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/task.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/task.rb)75
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/util.rb (renamed from railties/lib/rails/vendor/thor-0.12.0/lib/thor/util.rb)26
-rw-r--r--railties/lib/rails/vendor/thor-0.12.3/lib/thor/version.rb3
-rw-r--r--railties/railties.gemspec28
-rw-r--r--railties/test/abstract_unit.rb6
-rw-r--r--railties/test/application/configuration_test.rb106
-rw-r--r--railties/test/application/generators_test.rb46
-rw-r--r--railties/test/application/initializer_test.rb183
-rw-r--r--railties/test/application/load_test.rb30
-rw-r--r--railties/test/application/notifications_test.rb51
-rw-r--r--railties/test/application/routing_test.rb180
-rw-r--r--railties/test/fixtures/plugins/engines/engine/config/routes.rb2
-rw-r--r--railties/test/fixtures/vendor/plugins/mspec/lib/rails_generators/mspec_generator.rb (renamed from railties/test/fixtures/vendor/plugins/mspec/lib/generators/mspec_generator.rb)0
-rw-r--r--railties/test/generators/actions_test.rb14
-rw-r--r--railties/test/generators/app_generator_test.rb55
-rw-r--r--railties/test/generators/controller_generator_test.rb15
-rw-r--r--railties/test/generators/generator_generator_test.rb9
-rw-r--r--railties/test/generators/generators_test_helper.rb94
-rw-r--r--railties/test/generators/helper_generator_test.rb9
-rw-r--r--railties/test/generators/integration_test_generator_test.rb9
-rw-r--r--railties/test/generators/mailer_generator_test.rb9
-rw-r--r--railties/test/generators/metal_generator_test.rb9
-rw-r--r--railties/test/generators/migration_generator_test.rb41
-rw-r--r--railties/test/generators/model_generator_test.rb15
-rw-r--r--railties/test/generators/named_base_test.rb8
-rw-r--r--railties/test/generators/observer_generator_test.rb9
-rw-r--r--railties/test/generators/performance_test_generator_test.rb9
-rw-r--r--railties/test/generators/plugin_generator_test.rb9
-rw-r--r--railties/test/generators/resource_generator_test.rb19
-rw-r--r--railties/test/generators/scaffold_controller_generator_test.rb27
-rw-r--r--railties/test/generators/scaffold_generator_test.rb32
-rw-r--r--railties/test/generators/session_migration_generator_test.rb9
-rw-r--r--railties/test/generators/stylesheets_generator_test.rb11
-rw-r--r--railties/test/generators_test.rb24
-rw-r--r--railties/test/initializable_test.rb10
-rw-r--r--railties/test/initializer/check_ruby_version_test.rb56
-rw-r--r--railties/test/initializer/initialize_i18n_test.rb11
-rw-r--r--railties/test/initializer/path_test.rb174
-rw-r--r--railties/test/isolation/abstract_unit.rb19
-rw-r--r--railties/test/metal_test.rb1
-rw-r--r--railties/test/paths_test.rb3
-rw-r--r--railties/test/plugins/configuration_test.rb36
-rw-r--r--railties/test/plugins/framework_extension_test.rb52
-rw-r--r--railties/test/rails_info_controller_test.rb8
555 files changed, 13587 insertions, 19109 deletions
diff --git a/.gitignore b/.gitignore
index 70b7c0057a..9a65e4996f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,16 +7,9 @@ activerecord/doc
actionpack/doc
actionmailer/doc
activesupport/doc
-activemodel/pkg
-activeresource/pkg
-activerecord/pkg
-actionpack/pkg
activemodel/test/fixtures/fixture_database.sqlite3
-actionmailer/pkg
-activesupport/pkg
actionpack/test/tmp
activesupport/test/fixtures/isolation_test
-railties/pkg
railties/test/500.html
railties/test/fixtures/tmp
railties/test/initializer/root/log
@@ -31,3 +24,4 @@ railties/guides/output
bin
vendor/gems/
railties/tmp
+pkg
diff --git a/.gitmodules b/.gitmodules
index 20ed3ed9c9..d0be7ff194 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,6 +1,6 @@
[submodule "arel"]
path = arel
url = git://github.com/rails/arel.git
-[submodule "rack-mount"]
- path = rack-mount
- url = git://github.com/rails/rack-mount.git
+[submodule "rack"]
+ path = rack
+ url = git://github.com/rails/rack.git
diff --git a/Gemfile b/Gemfile
index 8f4fed2cdd..2aca5065f5 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,23 +1,27 @@
-clear_sources
-source 'http://gemcutter.org'
-
gem "rake", ">= 0.8.7"
gem "mocha", ">= 0.9.8"
+gem "ruby-debug", ">= 0.10.3" if RUBY_VERSION < '1.9'
-gem "rails", "3.0.pre", :vendored_at => "railties"
+gem "rails", "3.0.pre", :path => "railties"
%w(activesupport activemodel actionpack actionmailer activerecord activeresource).each do |lib|
- gem lib, '3.0.pre', :vendored_at => lib
+ gem lib, '3.0.pre', :path => lib
end
+# AS
+gem "i18n", ">= 0.3.0"
+
# AR
gem "arel", "0.2.pre", :git => "git://github.com/rails/arel.git"
gem "sqlite3-ruby", ">= 1.2.5"
-gem "pg", ">= 0.8.0"
-gem "mysql", ">= 2.8.1"
+
+only :test do
+ gem "pg", ">= 0.8.0"
+ gem "mysql", ">= 2.8.1"
+end
# AP
-gem "rack", "1.0.1", :git => "git://github.com/rails/rack.git"
-gem "rack-mount", :git => "git://github.com/rails/rack-mount.git"
+gem "rack", "1.1.0", :git => "git://github.com/rack/rack.git"
+gem "rack-test", "0.5.3"
gem "RedCloth", ">= 4.2.2"
if ENV['CI']
@@ -34,3 +38,5 @@ if ENV['CI']
gem "test-unit", ">= 2.0.5"
end
end
+
+disable_system_gems
diff --git a/Rakefile b/Rakefile
index 6aa8f61028..5ae09160f0 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,9 +1,10 @@
require 'rake'
require 'rake/rdoctask'
+require 'rake/gempackagetask'
env = %(PKG_BUILD="#{ENV['PKG_BUILD']}") if ENV['PKG_BUILD']
-PROJECTS = %w(activesupport actionpack actionmailer activeresource activerecord activemodel railties)
+PROJECTS = %w(activesupport activemodel actionpack actionmailer activeresource activerecord railties)
Dir["#{File.dirname(__FILE__)}/*/lib/*/version.rb"].each do |version_path|
require version_path
@@ -23,11 +24,28 @@ task :default => %w(test test:isolated)
end
end
+desc "Smoke-test all projects"
+task :smoke do
+ (PROJECTS - %w(activerecord)).each do |project|
+ system %(cd #{project} && #{env} #{$0} test:isolated)
+ end
+ system %(cd activerecord && #{env} #{$0} sqlite3:isolated_test)
+end
+
+spec = eval(File.read('rails.gemspec'))
+Rake::GemPackageTask.new(spec) do |pkg|
+ pkg.gem_spec = spec
+end
+
task :install => :gem do
+ system %(cd arel && gem build arel.gemspec && gem install arel-0.2.pre.gem --no-ri --no-rdoc --ignore-dependencies)
+ system %(cd rack && rake gem VERSION=1.0.2.pre && gem install rack-1.0.2.pre.gem --no-ri --no-rdoc --ignore-dependencies)
(PROJECTS - ["railties"]).each do |project|
+ puts "INSTALLING #{project}"
system("gem install #{project}/pkg/#{project}-#{ActionPack::VERSION::STRING}.gem --no-ri --no-rdoc")
end
- system("gem install railties/pkg/rails-#{ActionPack::VERSION::STRING}.gem --no-ri --no-rdoc")
+ system("gem install railties/pkg/railties-#{ActionPack::VERSION::STRING}.gem --no-ri --no-rdoc")
+ system("gem install pkg/rails-#{ActionPack::VERSION::STRING}.gem --no-ri --no-rdoc")
end
desc "Generate documentation for the Rails framework"
diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG
index 773e603d73..785bf98c55 100644
--- a/actionmailer/CHANGELOG
+++ b/actionmailer/CHANGELOG
@@ -1,3 +1,27 @@
+*Rails 3.0 (pending)*
+
+* The Mail::Message class has helped methods for all the field types that return 'common' defaults for the common use case, so to get the subject, mail.subject will give you a string, mail.date will give you a DateTime object, mail.from will give you an array of address specs (mikel@test.lindsaar.net) etc. If you want to access the field object itself, call mail[:field_name] which will return the field object you want, which you can then chain, like mail[:from].formatted
+
+* Mail#content_type now returns the content_type field as a string. If you want the mime type of a mail, then you call Mail#mime_type (eg, text/plain), if you want the parameters of the content type field, you call Mail#content_type_parameters which gives you a hash, eg {'format' => 'flowed', 'charset' => 'utf-8'}
+
+* ActionMailer::Base :default_implicit_parts_order now is in the sequence of the order you want, no reversing of ordering takes place. The default order now is text/plain, then text/enriched, then text/html and then any other part that is not one of these three.
+
+* Mail does not have "quoted_body", "quoted_subject" etc. All of these are accessed via body.encoded, subject.encoded etc
+
+* Every object in a Mail object returns an object, never a string. So Mail.body returns a Mail::Body class object, need to call #encoded or #decoded to get the string you want.
+* Mail::Message#set_content_type does not exist, it is simply Mail::Message#content_type
+
+* Every mail message gets a unique message_id unless you specify one, had to change all the tests that check for equality with expected.encoded == actual.encoded to first replace their message_ids with control values
+
+* Mail now has a proper concept of parts, remove the ActionMailer::Part and ActionMailer::PartContainer classes
+
+* Calling #encoded on any object returns it as a string ready to go into the output stream of an email, this means it includes the \r\n at the end of the lines and the object is pre-wrapped with \r\n\t if it is a header field. Also, the "encoded" value includes the field name if it is a header field.
+
+* Attachments are only the actual attachment, with filename etc. A part contains an attachment. The part has the content_type etc. So attachments.last.content_type is invalid. But parts.last.content_type
+
+* There is no idea of a "sub_head" in Mail. A part is just a Message with some extra functionality, so it just has a "header" like a normal mail message
+
+
*2.3.2 [Final] (March 15, 2009)*
* Fixed that ActionMailer should send correctly formatted Return-Path in MAIL FROM for SMTP #1842 [Matt Jones]
diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile
index 1a7ece5068..6c19371514 100644
--- a/actionmailer/Rakefile
+++ b/actionmailer/Rakefile
@@ -23,7 +23,6 @@ task :default => [ :test ]
Rake::TestTask.new { |t|
t.libs << "test"
t.pattern = 'test/*_test.rb'
- t.verbose = true
t.warning = true
}
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index efe50c4f84..8adea46d35 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -11,6 +11,7 @@ Gem::Specification.new do |s|
s.homepage = "http://www.rubyonrails.org"
s.add_dependency('actionpack', '= 3.0.pre')
+ s.add_dependency('mail', '~> 1.5.0')
s.files = Dir['CHANGELOG', 'README', 'MIT-LICENSE', 'lib/**/*']
s.has_rdoc = true
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
index 23f04a11ba..55ddbb24f4 100644
--- a/actionmailer/lib/action_mailer.rb
+++ b/actionmailer/lib/action_mailer.rb
@@ -21,36 +21,27 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-actionpack_path = "#{File.dirname(__FILE__)}/../../actionpack/lib"
-$:.unshift(actionpack_path) if File.directory?(actionpack_path)
+actionpack_path = File.expand_path('../../../actionpack/lib', __FILE__)
+$:.unshift(actionpack_path) if File.directory?(actionpack_path) && !$:.include?(actionpack_path)
+
require 'action_controller'
require 'action_view'
module ActionMailer
- def self.load_all!
- [Base, Part, ::Text::Format, ::Net::SMTP]
- end
+ extend ::ActiveSupport::Autoload
- autoload :AdvAttrAccessor, 'action_mailer/adv_attr_accessor'
- autoload :DeprecatedBody, 'action_mailer/deprecated_body'
- autoload :Base, 'action_mailer/base'
- autoload :DeliveryMethod, 'action_mailer/delivery_method'
- autoload :Part, 'action_mailer/part'
- autoload :PartContainer, 'action_mailer/part_container'
- autoload :Quoting, 'action_mailer/quoting'
- autoload :TestCase, 'action_mailer/test_case'
- autoload :TestHelper, 'action_mailer/test_helper'
- autoload :Utils, 'action_mailer/utils'
+ autoload :AdvAttrAccessor
+ autoload :Base
+ autoload :DeliveryMethod
+ autoload :DeprecatedBody
+ autoload :MailHelper
+ autoload :Quoting
+ autoload :TestCase
+ autoload :TestHelper
end
module Text
- autoload :Format, 'action_mailer/vendor/text_format'
-end
+ extend ActiveSupport::Autoload
-module Net
- autoload :SMTP, 'net/smtp'
+ autoload :Format, 'action_mailer/vendor/text_format'
end
-
-autoload :MailHelper, 'action_mailer/mail_helper'
-
-require 'action_mailer/vendor/tmail'
diff --git a/actionmailer/lib/action_mailer/adv_attr_accessor.rb b/actionmailer/lib/action_mailer/adv_attr_accessor.rb
index e77029afdd..be6b1feca9 100644
--- a/actionmailer/lib/action_mailer/adv_attr_accessor.rb
+++ b/actionmailer/lib/action_mailer/adv_attr_accessor.rb
@@ -1,29 +1,25 @@
module ActionMailer
module AdvAttrAccessor #:nodoc:
- def self.included(base)
- base.extend(ClassMethods)
- end
-
- module ClassMethods #:nodoc:
- def adv_attr_accessor(*names)
- names.each do |name|
- ivar = "@#{name}"
+ def adv_attr_accessor(*names)
+ names.each do |name|
+ ivar = "@#{name}"
- define_method("#{name}=") do |value|
- instance_variable_set(ivar, value)
+ class_eval <<-ACCESSORS, __FILE__, __LINE__ + 1
+ def #{name}=(value)
+ #{ivar} = value
end
- define_method(name) do |*parameters|
- raise ArgumentError, "expected 0 or 1 parameters" unless parameters.length <= 1
- if parameters.empty?
- if instance_variable_names.include?(ivar)
- instance_variable_get(ivar)
- 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
- instance_variable_set(ivar, parameters.first)
+ #{ivar} = args.first
end
end
- end
+ ACCESSORS
+
+ 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 dfa1b6444b..25b8e4874e 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -1,9 +1,10 @@
require 'active_support/core_ext/class'
+require 'mail'
+require 'action_mailer/tmail_compat'
module ActionMailer #:nodoc:
# Action Mailer allows you to send email from your application using a mailer model and views.
#
- #
# = Mailer Models
#
# To use Action Mailer, you need to create a mailer model.
@@ -22,7 +23,8 @@ module ActionMailer #:nodoc:
# bcc ["bcc@example.com", "Order Watcher <watcher@example.com>"]
# from "system@example.com"
# subject "New account information"
- # body :account => recipient
+ #
+ # @account = recipient
# end
# end
#
@@ -42,13 +44,6 @@ module ActionMailer #:nodoc:
# address. Setting this is useful when you want delivery notifications sent to a different address than
# the one in <tt>from</tt>.
#
- # The <tt>body</tt> method has special behavior. It takes a hash which generates an instance variable
- # named after each key in the hash containing the value that that key points to.
- #
- # So, for example, <tt>body :account => recipient</tt> would result
- # in an instance variable <tt>@account</tt> with the value of <tt>recipient</tt> being accessible in the
- # view.
- #
#
# = Mailer views
#
@@ -68,7 +63,12 @@ module ActionMailer #:nodoc:
# You can even use Action Pack helpers in these views. For example:
#
# You got a new note!
- # <%= truncate(note.body, 25) %>
+ # <%= truncate(@note.body, 25) %>
+ #
+ # If you need to access the subject, from or the recipients in the view, you can do that through mailer object:
+ #
+ # You got a new note from <%= mailer.from %>!
+ # <%= truncate(@note.body, 25) %>
#
#
# = Generating URLs
@@ -150,7 +150,7 @@ module ActionMailer #:nodoc:
#
# part "text/plain" do |p|
# p.body = render_message("signup-as-plain", :account => recipient)
- # p.transfer_encoding = "base64"
+ # p.content_transfer_encoding = "base64"
# end
# end
# end
@@ -250,29 +250,23 @@ module ActionMailer #:nodoc:
# <tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client
# and appear last in the mime encoded message. You can also pick a different order from inside a method with
# +implicit_parts_order+.
- class Base
- include AdvAttrAccessor, PartContainer, Quoting, Utils
+ class Base < AbstractController::Base
+ include Quoting
+ extend AdvAttrAccessor
- include AbstractController::RenderingController
+ include AbstractController::Logger
+ include AbstractController::Rendering
include AbstractController::LocalizedCache
include AbstractController::Layouts
-
include AbstractController::Helpers
- helper MailHelper
- if Object.const_defined?(:ActionController)
- include ActionController::UrlWriter
- end
+ helper ActionMailer::MailHelper
+ include ActionController::UrlWriter
include ActionMailer::DeprecatedBody
private_class_method :new #:nodoc:
- class_inheritable_accessor :view_paths
- self.view_paths = []
-
- cattr_accessor :logger
-
@@raise_delivery_errors = true
cattr_accessor :raise_delivery_errors
@@ -291,10 +285,16 @@ module ActionMailer #:nodoc:
@@default_mime_version = "1.0"
cattr_accessor :default_mime_version
- @@default_implicit_parts_order = [ "text/html", "text/enriched", "text/plain" ]
+ # This specifies the order that the parts of a multipart email will be. Usually you put
+ # text/plain at the top so someone without a MIME capable email reader can read the plain
+ # text of your email first.
+ #
+ # Any content type that is not listed here will be inserted in the order you add them to
+ # the email after the content types you list here.
+ @@default_implicit_parts_order = [ "text/plain", "text/enriched", "text/html" ]
cattr_accessor :default_implicit_parts_order
- @@protected_instance_variables = []
+ @@protected_instance_variables = %w(@parts @mail)
cattr_reader :protected_instance_variables
# Specify the BCC addresses for the message
@@ -344,24 +344,13 @@ module ActionMailer #:nodoc:
# have multiple mailer methods share the same template.
adv_attr_accessor :template
- # The mail and action_name instances referenced by this mailer.
- attr_reader :mail, :action_name
-
- # Where the response body is stored.
- attr_internal :response_body
-
# 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.
- attr_writer :mailer_name
+ adv_attr_accessor :mailer_name
- def mailer_name(value = nil)
- if value
- @mailer_name = value
- else
- @mailer_name || self.class.mailer_name
- end
- end
+ # Expose the internal mail
+ attr_reader :mail
# Alias controller_path to mailer_name so render :partial in views work.
alias :controller_path :mailer_name
@@ -376,6 +365,7 @@ module ActionMailer #:nodoc:
def mailer_name
@mailer_name ||= name.underscore
end
+ alias :controller_path :mailer_name
def delivery_method=(method_name)
@delivery_method = ActionMailer::DeliveryMethod.lookup_method(method_name)
@@ -411,8 +401,7 @@ module ActionMailer #:nodoc:
# end
def receive(raw_email)
logger.info "Received mail:\n #{raw_email}" unless logger.nil?
- mail = TMail::Mail.parse(raw_email)
- mail.base64_decode
+ mail = Mail.new(raw_email)
new.receive(mail)
end
@@ -447,21 +436,47 @@ module ActionMailer #:nodoc:
superclass_delegating_reader :delivery_method
self.delivery_method = :smtp
+ # Add a part to a multipart message, with the given content-type. The
+ # part itself is yielded to the block so that other properties (charset,
+ # body, headers, etc.) can be set on it.
+ def part(params)
+ params = {:content_type => params} if String === params
+ if custom_headers = params.delete(:headers)
+ ActiveSupport::Deprecation.warn('Passing custom headers with :headers => {} is deprecated. ' <<
+ 'Please just pass in custom headers directly.', caller[0,10])
+ params.merge!(custom_headers)
+ end
+ part = Mail::Part.new(params)
+ yield part if block_given?
+ @parts << part
+ end
+
+ # Add an attachment to a multipart message. This is simply a part with the
+ # content-disposition set to "attachment".
+ def attachment(params, &block)
+ super # Run deprecation hooks
+
+ params = { :content_type => params } if String === params
+ params = { :content_disposition => "attachment",
+ :content_transfer_encoding => "base64" }.merge(params)
+
+ part(params, &block)
+ end
+
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
# will be initialized according to the named method. If not, the mailer will
# remain uninitialized (useful when you only need to invoke the "receive"
# method, for instance).
- def initialize(method_name=nil, *parameters) #:nodoc:
- @_response_body = nil
+ def initialize(method_name=nil, *args)
super()
- create!(method_name, *parameters) if method_name
+ process(method_name, *args) if method_name
end
- # Initialize the mailer via the given +method_name+. The body will be
- # rendered and a new TMail::Mail object created.
- def create!(method_name, *parameters) #:nodoc:
+ # Process the mailer via the given +method_name+. The body will be
+ # rendered and a new Mail object created.
+ def process(method_name, *args)
initialize_defaults(method_name)
- __send__(method_name, *parameters)
+ super
# Create e-mail parts
create_parts
@@ -470,11 +485,11 @@ module ActionMailer #:nodoc:
@subject ||= I18n.t(:subject, :scope => [:actionmailer, mailer_name, method_name],
:default => method_name.humanize)
- # build the mail object itself
- @mail = create_mail
+ # Build the mail object itself
+ create_mail
end
- # Delivers a TMail::Mail object. By default, it delivers the cached mail
+ # 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 = @mail)
@@ -485,7 +500,7 @@ module ActionMailer #:nodoc:
logger.debug "\n#{mail.encoded}"
end
- ActiveSupport::Notifications.instrument(:deliver_mail, :mail => @mail) do
+ ActiveSupport::Notifications.instrument(:deliver_mail, :mail => mail) do
begin
self.delivery_method.perform_delivery(mail) if perform_deliveries
rescue Exception => e # Net::SMTP errors or sendmail pipe errors
@@ -501,15 +516,14 @@ module ActionMailer #:nodoc:
# 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) #:nodoc:
@charset ||= @@default_charset.dup
@content_type ||= @@default_content_type.dup
@implicit_parts_order ||= @@default_implicit_parts_order.dup
@mime_version ||= @@default_mime_version.dup if @@default_mime_version
- @mailer_name ||= self.class.mailer_name
+ @mailer_name ||= self.class.mailer_name.dup
@template ||= method_name
- @action_name = @template
@parts ||= []
@headers ||= {}
@@ -518,29 +532,18 @@ module ActionMailer #:nodoc:
super # Run deprecation hooks
end
- def create_parts
+ def create_parts #:nodoc:
super # Run deprecation hooks
if String === response_body
- @parts.unshift Part.new(
- :content_type => "text/plain",
- :disposition => "inline",
- :charset => charset,
- :body => response_body
- )
+ @parts.unshift create_inline_part(response_body)
else
- self.class.template_root.find_all(@template, {}, mailer_name).each do |template|
- @parts << Part.new(
- :content_type => template.mime_type ? template.mime_type.to_s : "text/plain",
- :disposition => "inline",
- :charset => charset,
- :body => render_to_body(:_template => template)
- )
+ self.class.template_root.find_all(@template, {}, @mailer_name).each do |template|
+ @parts << create_inline_part(render_to_body(:_template => template), template.mime_type)
end
if @parts.size > 1
@content_type = "multipart/alternative" if @content_type !~ /^multipart/
- @parts = sort_parts(@parts, @implicit_parts_order)
end
# If this is a multipart e-mail add the mime_version if it is not
@@ -549,37 +552,19 @@ module ActionMailer #:nodoc:
end
end
- def sort_parts(parts, order = [])
- order = order.collect { |s| s.downcase }
-
- parts = parts.sort do |a, b|
- a_ct = a.content_type.downcase
- b_ct = b.content_type.downcase
-
- a_in = order.include? a_ct
- b_in = order.include? b_ct
-
- s = case
- when a_in && b_in
- order.index(a_ct) <=> order.index(b_ct)
- when a_in
- -1
- when b_in
- 1
- else
- a_ct <=> b_ct
- end
-
- # reverse the ordering because parts that come last are displayed
- # first in mail clients
- (s * -1)
- end
+ def create_inline_part(body, mime_type=nil) #:nodoc:
+ ct = mime_type || "text/plain"
+ main_type, sub_type = split_content_type(ct.to_s)
- parts
+ Mail::Part.new(
+ :content_type => [main_type, sub_type, {:charset => charset}],
+ :content_disposition => "inline",
+ :body => body
+ )
end
- def create_mail
- m = TMail::Mail.new
+ def create_mail #:nodoc:
+ m = Mail.new
m.subject, = quote_any_if_necessary(charset, subject)
m.to, m.from = quote_any_address_if_necessary(charset, recipients, from)
@@ -592,27 +577,43 @@ module ActionMailer #:nodoc:
headers.each { |k, v| m[k] = v }
real_content_type, ctype_attrs = parse_content_type
-
- if @parts.empty?
- m.set_content_type(real_content_type, nil, ctype_attrs)
- m.body = normalize_new_lines(body)
- elsif @parts.size == 1 && @parts.first.parts.empty?
- m.set_content_type(real_content_type, nil, ctype_attrs)
- m.body = normalize_new_lines(@parts.first.body)
+ main_type, sub_type = split_content_type(real_content_type)
+
+ if @parts.size == 1 && @parts.first.parts.empty?
+ m.content_type([main_type, sub_type, ctype_attrs])
+ m.body = @parts.first.body.encoded
else
@parts.each do |p|
- part = (TMail::Mail === p ? p : p.to_mail(self))
- m.parts << part
+ m.add_part(p)
end
+ m.body.set_sort_order(@implicit_parts_order)
+ m.body.sort_parts!
+
if real_content_type =~ /multipart/
ctype_attrs.delete "charset"
- m.set_content_type(real_content_type, nil, ctype_attrs)
+ m.content_type([main_type, sub_type, ctype_attrs])
end
end
+ m.content_transfer_encoding = '8bit' unless m.body.only_us_ascii?
+
@mail = m
end
+
+ def split_content_type(ct) #:nodoc:
+ ct.to_s.split("/")
+ end
+
+ def parse_content_type(defaults=nil) #:nodoc:
+ 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)]
+ end
+ end
end
end
diff --git a/actionmailer/lib/action_mailer/delivery_method.rb b/actionmailer/lib/action_mailer/delivery_method.rb
index 29a51afdc3..4f7d3afc3c 100644
--- a/actionmailer/lib/action_mailer/delivery_method.rb
+++ b/actionmailer/lib/action_mailer/delivery_method.rb
@@ -1,7 +1,7 @@
-require "active_support/core_ext/class"
+require 'active_support/core_ext/class'
+
module ActionMailer
module DeliveryMethod
-
autoload :File, 'action_mailer/delivery_method/file'
autoload :Sendmail, 'action_mailer/delivery_method/sendmail'
autoload :Smtp, 'action_mailer/delivery_method/smtp'
@@ -52,6 +52,5 @@ module ActionMailer
superclass_delegating_accessor :settings
self.settings = {}
end
-
end
end
diff --git a/actionmailer/lib/action_mailer/delivery_method/file.rb b/actionmailer/lib/action_mailer/delivery_method/file.rb
index 587ae37ffa..571e32df49 100644
--- a/actionmailer/lib/action_mailer/delivery_method/file.rb
+++ b/actionmailer/lib/action_mailer/delivery_method/file.rb
@@ -6,13 +6,13 @@ module ActionMailer
# A delivery method implementation which writes all mails to a file.
class File < Method
self.settings = {
- :location => defined?(Rails) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
+ :location => defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
}
def perform_delivery(mail)
FileUtils.mkdir_p settings[:location]
- (mail.to + mail.cc + mail.bcc).uniq.each do |to|
+ mail.destinations.uniq.each do |to|
::File.open(::File.join(settings[:location], to), 'a') { |f| f.write(mail) }
end
end
diff --git a/actionmailer/lib/action_mailer/delivery_method/smtp.rb b/actionmailer/lib/action_mailer/delivery_method/smtp.rb
index 86b0ae8329..af30c498b5 100644
--- a/actionmailer/lib/action_mailer/delivery_method/smtp.rb
+++ b/actionmailer/lib/action_mailer/delivery_method/smtp.rb
@@ -1,8 +1,9 @@
+require 'net/smtp'
+
module ActionMailer
module DeliveryMethod
# A delivery method implementation which sends via smtp.
class Smtp < Method
-
self.settings = {
:address => "localhost",
:port => 25,
@@ -15,8 +16,7 @@ module ActionMailer
def perform_delivery(mail)
destinations = mail.destinations
- mail.ready_to_send
- sender = (mail['return-path'] && mail['return-path'].spec) || mail['from']
+ sender = (mail['return-path'] && mail['return-path'].address) || mail['from']
smtp = Net::SMTP.new(settings[:address], settings[:port])
smtp.enable_starttls_auto if settings[:enable_starttls_auto] && smtp.respond_to?(:enable_starttls_auto)
@@ -26,6 +26,5 @@ module ActionMailer
end
end
end
-
end
end
diff --git a/actionmailer/lib/action_mailer/deprecated_body.rb b/actionmailer/lib/action_mailer/deprecated_body.rb
index 50ff262432..20b0989a85 100644
--- a/actionmailer/lib/action_mailer/deprecated_body.rb
+++ b/actionmailer/lib/action_mailer/deprecated_body.rb
@@ -15,6 +15,14 @@ module ActionMailer
@body ||= {}
end
+ def attachment(params, &block)
+ if params[:body]
+ ActiveSupport::Deprecation.warn('attachment :body => "string" is deprecated. To set the body of an attachment ' <<
+ 'please use :data instead, like attachment :data => "string".', caller[0,10])
+ params[:data] = params.delete(:body)
+ end
+ end
+
def create_parts
if String === @body
ActiveSupport::Deprecation.warn('body is deprecated. To set the body with a text ' <<
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
index 351b966abe..701dc34431 100644
--- a/actionmailer/lib/action_mailer/mail_helper.rb
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -1,17 +1,24 @@
-module MailHelper
- # 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)
- formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
- }.join("\n")
+module ActionMailer
+ module MailHelper
+ # 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)
+ 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" }
+ # Make list points stand on their own line
+ formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
+ formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
+
+ formatted
+ end
- formatted
+ # Access the mailer instance.
+ def mailer #:nodoc:
+ @controller
+ end
end
end
diff --git a/actionmailer/lib/action_mailer/part.rb b/actionmailer/lib/action_mailer/part.rb
deleted file mode 100644
index 2bbb59cdb6..0000000000
--- a/actionmailer/lib/action_mailer/part.rb
+++ /dev/null
@@ -1,107 +0,0 @@
-module ActionMailer
- # Represents a subpart of an email message. It shares many similar
- # attributes of ActionMailer::Base. Although you can create parts manually
- # and add them to the +parts+ list of the mailer, it is easier
- # to use the helper methods in ActionMailer::PartContainer.
- class Part
- include AdvAttrAccessor, PartContainer, Utils
-
- # Represents the body of the part, as a string. This should not be a
- # Hash (like ActionMailer::Base), but if you want a template to be rendered
- # into the body of a subpart you can do it with the mailer's +render+ method
- # and assign the result here.
- adv_attr_accessor :body
-
- # Specify the charset for this subpart. By default, it will be the charset
- # of the containing part or mailer.
- adv_attr_accessor :charset
-
- # The content disposition of this part, typically either "inline" or
- # "attachment".
- adv_attr_accessor :content_disposition
-
- # The content type of the part.
- adv_attr_accessor :content_type
-
- # The filename to use for this subpart (usually for attachments).
- adv_attr_accessor :filename
-
- # Accessor for specifying additional headers to include with this part.
- adv_attr_accessor :headers
-
- # The transfer encoding to use for this subpart, like "base64" or
- # "quoted-printable".
- adv_attr_accessor :transfer_encoding
-
- # Create a new part from the given +params+ hash. The valid params keys
- # correspond to the accessors.
- def initialize(params)
- @content_type = params[:content_type]
- @content_disposition = params[:disposition] || "inline"
- @charset = params[:charset]
- @body = params[:body]
- @filename = params[:filename]
- @transfer_encoding = params[:transfer_encoding] || "quoted-printable"
- @headers = params[:headers] || {}
- @parts = []
- end
-
- # Convert the part to a mail object which can be included in the parts
- # list of another mail object.
- def to_mail(defaults)
- part = TMail::Mail.new
-
- real_content_type, ctype_attrs = parse_content_type(defaults)
-
- if @parts.empty?
- part.content_transfer_encoding = transfer_encoding || "quoted-printable"
- case (transfer_encoding || "").downcase
- when "base64" then
- part.body = TMail::Base64.folding_encode(body)
- when "quoted-printable"
- part.body = [normalize_new_lines(body)].pack("M*")
- else
- part.body = body
- end
-
- # Always set the content_type after setting the body and or parts!
- # Also don't set filename and name when there is none (like in
- # non-attachment parts)
- if content_disposition == "attachment"
- ctype_attrs.delete "charset"
- part.set_content_type(real_content_type, nil,
- squish("name" => filename).merge(ctype_attrs))
- part.set_content_disposition(content_disposition,
- squish("filename" => filename).merge(ctype_attrs))
- else
- part.set_content_type(real_content_type, nil, ctype_attrs)
- part.set_content_disposition(content_disposition)
- end
- else
- if String === body
- @parts.unshift Part.new(:charset => charset, :body => @body, :content_type => 'text/plain')
- @body = nil
- end
-
- @parts.each do |p|
- prt = (TMail::Mail === p ? p : p.to_mail(defaults))
- part.parts << prt
- end
-
- if real_content_type =~ /multipart/
- ctype_attrs.delete 'charset'
- part.set_content_type(real_content_type, nil, ctype_attrs)
- end
- end
-
- headers.each { |k,v| part[k] = v }
-
- part
- end
-
- private
- def squish(values={})
- values.delete_if { |k,v| v.nil? }
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/part_container.rb b/actionmailer/lib/action_mailer/part_container.rb
deleted file mode 100644
index abfd8f8426..0000000000
--- a/actionmailer/lib/action_mailer/part_container.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-module ActionMailer
- # Accessors and helpers that ActionMailer::Base and ActionMailer::Part have
- # in common. Using these helpers you can easily add subparts or attachments
- # to your message:
- #
- # def my_mail_message(...)
- # ...
- # part "text/plain" do |p|
- # p.body "hello, world"
- # p.transfer_encoding "base64"
- # end
- #
- # attachment "image/jpg" do |a|
- # a.body = File.read("hello.jpg")
- # a.filename = "hello.jpg"
- # end
- # end
- module PartContainer
- # The list of subparts of this container
- attr_reader :parts
-
- # Add a part to a multipart message, with the given content-type. The
- # part itself is yielded to the block so that other properties (charset,
- # body, headers, etc.) can be set on it.
- def part(params)
- params = {:content_type => params} if String === params
- part = Part.new(params)
- yield part if block_given?
- @parts << part
- end
-
- # Add an attachment to a multipart message. This is simply a part with the
- # content-disposition set to "attachment".
- def attachment(params, &block)
- params = { :content_type => params } if String === params
- params = { :disposition => "attachment",
- :transfer_encoding => "base64" }.merge(params)
- part(params, &block)
- end
-
- private
-
- def parse_content_type(defaults=nil)
- if content_type.blank?
- return defaults ?
- [ defaults.content_type, { 'charset' => defaults.charset } ] :
- [ nil, {} ]
- end
- ctype, *attrs = content_type.split(/;\s*/)
- attrs = attrs.inject({}) { |h,s| k,v = s.split(/=/, 2); h[k] = v; h }
- [ctype, {"charset" => charset || defaults && defaults.charset}.merge(attrs)]
- end
-
- end
-end
diff --git a/actionmailer/lib/action_mailer/quoting.rb b/actionmailer/lib/action_mailer/quoting.rb
index 94fa042002..b30441f9de 100644
--- a/actionmailer/lib/action_mailer/quoting.rb
+++ b/actionmailer/lib/action_mailer/quoting.rb
@@ -43,7 +43,7 @@ module ActionMailer
# "to", "from", "cc", "bcc" and "reply-to" headers.
def quote_address_if_necessary(address, charset)
if Array === address
- address.map { |a| quote_address_if_necessary(a, charset) }
+ address.map { |a| quote_address_if_necessary(a, charset) }.join(", ")
elsif address =~ /^(\S.*)\s+(<.*>)$/
address = $2
phrase = quote_if_necessary($1.gsub(/^['"](.*)['"]$/, '\1'), charset)
diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb
new file mode 100644
index 0000000000..5410c7d75f
--- /dev/null
+++ b/actionmailer/lib/action_mailer/railtie.rb
@@ -0,0 +1,25 @@
+require "action_mailer"
+require "rails"
+
+module ActionMailer
+ class Railtie < Rails::Railtie
+ plugin_name :action_mailer
+
+ initializer "action_mailer.set_configs" do |app|
+ app.config.action_mailer.each do |k,v|
+ ActionMailer::Base.send "#{k}=", v
+ end
+ end
+
+ # TODO: ActionController::Base.logger should delegate to its own config.logger
+ initializer "action_mailer.logger" do
+ ActionMailer::Base.logger ||= Rails.logger
+ end
+
+ initializer "action_mailer.view_paths" do |app|
+ # TODO: this should be combined with the logic for default config.action_mailer.view_paths
+ view_path = ActionView::PathSet.type_cast(app.config.view_path, app.config.cache_classes)
+ ActionMailer::Base.template_root = view_path if ActionMailer::Base.view_paths.blank?
+ end
+ end
+end \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb
index 8035db6f03..e8632d4559 100644
--- a/actionmailer/lib/action_mailer/test_case.rb
+++ b/actionmailer/lib/action_mailer/test_case.rb
@@ -1,4 +1,5 @@
require 'active_support/test_case'
+require 'action_mailer/base'
module ActionMailer
class NonInferrableMailerError < ::StandardError
@@ -43,8 +44,8 @@ module ActionMailer
end
def set_expected_mail
- @expected = TMail::Mail.new
- @expected.set_content_type "text", "plain", { "charset" => charset }
+ @expected = Mail.new
+ @expected.content_type ["text", "plain", { "charset" => charset }]
@expected.mime_version = '1.0'
end
diff --git a/actionmailer/lib/action_mailer/tmail_compat.rb b/actionmailer/lib/action_mailer/tmail_compat.rb
new file mode 100644
index 0000000000..2fd25ff145
--- /dev/null
+++ b/actionmailer/lib/action_mailer/tmail_compat.rb
@@ -0,0 +1,20 @@
+module Mail
+ class Message
+
+ def set_content_type(*args)
+ STDERR.puts("Message#set_content_type is deprecated, please just call Message#content_type with the same arguments.\n#{caller}")
+ content_type(*args)
+ end
+
+ alias :old_transfer_encoding :transfer_encoding
+ def transfer_encoding(value = nil)
+ if value
+ STDERR.puts("Message#transfer_encoding is deprecated, please call Message#content_transfer_encoding with the same arguments.\n#{caller}")
+ content_transfer_encoding(value)
+ else
+ old_transfer_encoding
+ end
+ end
+
+ end
+end \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/utils.rb b/actionmailer/lib/action_mailer/utils.rb
deleted file mode 100644
index 26d2e60aaf..0000000000
--- a/actionmailer/lib/action_mailer/utils.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-module ActionMailer
- module Utils #:nodoc:
- def normalize_new_lines(text)
- text.to_s.gsub(/\r\n?/, "\n")
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb b/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb
index 2d20c7a6a1..81cc7906d8 100755
--- a/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb
+++ b/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb
@@ -1,1466 +1,1467 @@
-#--
-# Text::Format for Ruby
-# Version 0.63
-#
-# Copyright (c) 2002 - 2003 Austin Ziegler
-#
-# $Id: format.rb,v 1.1.1.1 2004/10/14 11:59:57 webster132 Exp $
-#
-# ==========================================================================
-# Revision History ::
-# YYYY.MM.DD Change ID Developer
-# Description
-# --------------------------------------------------------------------------
-# 2002.10.18 Austin Ziegler
-# Fixed a minor problem with tabs not being counted. Changed
-# abbreviations from Hash to Array to better suit Ruby's
-# capabilities. Fixed problems with the way that Array arguments
-# are handled in calls to the major object types, excepting in
-# Text::Format#expand and Text::Format#unexpand (these will
-# probably need to be fixed).
-# 2002.10.30 Austin Ziegler
-# Fixed the ordering of the <=> for binary tests. Fixed
-# Text::Format#expand and Text::Format#unexpand to handle array
-# arguments better.
-# 2003.01.24 Austin Ziegler
-# Fixed a problem with Text::Format::RIGHT_FILL handling where a
-# single word is larger than #columns. Removed Comparable
-# capabilities (<=> doesn't make sense; == does). Added Symbol
-# equivalents for the Hash initialization. Hash initialization has
-# been modified so that values are set as follows (Symbols are
-# highest priority; strings are middle; defaults are lowest):
-# @columns = arg[:columns] || arg['columns'] || @columns
-# Added #hard_margins, #split_rules, #hyphenator, and #split_words.
-# 2003.02.07 Austin Ziegler
-# Fixed the installer for proper case-sensitive handling.
-# 2003.03.28 Austin Ziegler
-# Added the ability for a hyphenator to receive the formatter
-# object. Fixed a bug for strings matching /\A\s*\Z/ failing
-# entirely. Fixed a test case failing under 1.6.8.
-# 2003.04.04 Austin Ziegler
-# Handle the case of hyphenators returning nil for first/rest.
-# 2003.09.17 Austin Ziegler
-# Fixed a problem where #paragraphs(" ") was raising
-# NoMethodError.
-#
-# ==========================================================================
-#++
-
-module Text #:nodoc:
- # Text::Format for Ruby is copyright 2002 - 2005 by Austin Ziegler. It
- # is available under Ruby's licence, the Perl Artistic licence, or the
- # GNU GPL version 2 (or at your option, any later version). As a
- # special exception, for use with official Rails (provided by the
- # rubyonrails.org development team) and any project created with
- # official Rails, the following alternative MIT-style licence may be
- # used:
- #
- # == Text::Format Licence for Rails and Rails Applications
- # 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 names of its contributors may not be used to endorse or
- # promote products derived from this software without specific prior
- # written permission.
- #
- # 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.
- class Format
- VERSION = '0.63'
-
- # Local abbreviations. More can be added with Text::Format.abbreviations
- ABBREV = [ 'Mr', 'Mrs', 'Ms', 'Jr', 'Sr' ]
-
- # Formatting values
- LEFT_ALIGN = 0
- RIGHT_ALIGN = 1
- RIGHT_FILL = 2
- JUSTIFY = 3
-
- # Word split modes (only applies when #hard_margins is true).
- SPLIT_FIXED = 1
- SPLIT_CONTINUATION = 2
- SPLIT_HYPHENATION = 4
- SPLIT_CONTINUATION_FIXED = SPLIT_CONTINUATION | SPLIT_FIXED
- SPLIT_HYPHENATION_FIXED = SPLIT_HYPHENATION | SPLIT_FIXED
- SPLIT_HYPHENATION_CONTINUATION = SPLIT_HYPHENATION | SPLIT_CONTINUATION
- SPLIT_ALL = SPLIT_HYPHENATION | SPLIT_CONTINUATION | SPLIT_FIXED
-
- # Words forcibly split by Text::Format will be stored as split words.
- # This class represents a word forcibly split.
- class SplitWord
- # The word that was split.
- attr_reader :word
- # The first part of the word that was split.
- attr_reader :first
- # The remainder of the word that was split.
- attr_reader :rest
-
- def initialize(word, first, rest) #:nodoc:
- @word = word
- @first = first
- @rest = rest
- end
- end
-
- private
- LEQ_RE = /[.?!]['"]?$/
-
- def brk_re(i) #:nodoc:
- %r/((?:\S+\s+){#{i}})(.+)/
- end
-
- def posint(p) #:nodoc:
- p.to_i.abs
- end
-
- public
- # Compares two Text::Format objects. All settings of the objects are
- # compared *except* #hyphenator. Generated results (e.g., #split_words)
- # are not compared, either.
- def ==(o)
- (@text == o.text) &&
- (@columns == o.columns) &&
- (@left_margin == o.left_margin) &&
- (@right_margin == o.right_margin) &&
- (@hard_margins == o.hard_margins) &&
- (@split_rules == o.split_rules) &&
- (@first_indent == o.first_indent) &&
- (@body_indent == o.body_indent) &&
- (@tag_text == o.tag_text) &&
- (@tabstop == o.tabstop) &&
- (@format_style == o.format_style) &&
- (@extra_space == o.extra_space) &&
- (@tag_paragraph == o.tag_paragraph) &&
- (@nobreak == o.nobreak) &&
- (@abbreviations == o.abbreviations) &&
- (@nobreak_regex == o.nobreak_regex)
- end
-
- # The text to be manipulated. Note that value is optional, but if the
- # formatting functions are called without values, this text is what will
- # be formatted.
- #
- # *Default*:: <tt>[]</tt>
- # <b>Used in</b>:: All methods
- attr_accessor :text
-
- # The total width of the format area. The margins, indentation, and text
- # are formatted into this space.
- #
- # COLUMNS
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin indent text is formatted into here right margin
- #
- # *Default*:: <tt>72</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
- # <tt>#center</tt>
- attr_reader :columns
-
- # The total width of the format area. The margins, indentation, and text
- # are formatted into this space. The value provided is silently
- # converted to a positive integer.
- #
- # COLUMNS
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin indent text is formatted into here right margin
- #
- # *Default*:: <tt>72</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
- # <tt>#center</tt>
- def columns=(c)
- @columns = posint(c)
- end
-
- # The number of spaces used for the left margin.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # LEFT MARGIN indent text is formatted into here right margin
- #
- # *Default*:: <tt>0</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
- # <tt>#center</tt>
- attr_reader :left_margin
-
- # The number of spaces used for the left margin. The value provided is
- # silently converted to a positive integer value.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # LEFT MARGIN indent text is formatted into here right margin
- #
- # *Default*:: <tt>0</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
- # <tt>#center</tt>
- def left_margin=(left)
- @left_margin = posint(left)
- end
-
- # The number of spaces used for the right margin.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin indent text is formatted into here RIGHT MARGIN
- #
- # *Default*:: <tt>0</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
- # <tt>#center</tt>
- attr_reader :right_margin
-
- # The number of spaces used for the right margin. The value provided is
- # silently converted to a positive integer value.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin indent text is formatted into here RIGHT MARGIN
- #
- # *Default*:: <tt>0</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
- # <tt>#center</tt>
- def right_margin=(r)
- @right_margin = posint(r)
- end
-
- # The number of spaces to indent the first line of a paragraph.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin INDENT text is formatted into here right margin
- #
- # *Default*:: <tt>4</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_reader :first_indent
-
- # The number of spaces to indent the first line of a paragraph. The
- # value provided is silently converted to a positive integer value.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin INDENT text is formatted into here right margin
- #
- # *Default*:: <tt>4</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def first_indent=(f)
- @first_indent = posint(f)
- end
-
- # The number of spaces to indent all lines after the first line of a
- # paragraph.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin INDENT text is formatted into here right margin
- #
- # *Default*:: <tt>0</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_reader :body_indent
-
- # The number of spaces to indent all lines after the first line of
- # a paragraph. The value provided is silently converted to a
- # positive integer value.
- #
- # columns
- # <-------------------------------------------------------------->
- # <-----------><------><---------------------------><------------>
- # left margin INDENT text is formatted into here right margin
- #
- # *Default*:: <tt>0</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def body_indent=(b)
- @body_indent = posint(b)
- end
-
- # Normally, words larger than the format area will be placed on a line
- # by themselves. Setting this to +true+ will force words larger than the
- # format area to be split into one or more "words" each at most the size
- # of the format area. The first line and the original word will be
- # placed into <tt>#split_words</tt>. Note that this will cause the
- # output to look *similar* to a #format_style of JUSTIFY. (Lines will be
- # filled as much as possible.)
- #
- # *Default*:: +false+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_accessor :hard_margins
-
- # An array of words split during formatting if #hard_margins is set to
- # +true+.
- # #split_words << Text::Format::SplitWord.new(word, first, rest)
- attr_reader :split_words
-
- # The object responsible for hyphenating. It must respond to
- # #hyphenate_to(word, size) or #hyphenate_to(word, size, formatter) and
- # return an array of the word split into two parts; if there is a
- # hyphenation mark to be applied, responsibility belongs to the
- # hyphenator object. The size is the MAXIMUM size permitted, including
- # any hyphenation marks. If the #hyphenate_to method has an arity of 3,
- # the formatter will be provided to the method. This allows the
- # hyphenator to make decisions about the hyphenation based on the
- # formatting rules.
- #
- # *Default*:: +nil+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_reader :hyphenator
-
- # The object responsible for hyphenating. It must respond to
- # #hyphenate_to(word, size) and return an array of the word hyphenated
- # into two parts. The size is the MAXIMUM size permitted, including any
- # hyphenation marks.
- #
- # *Default*:: +nil+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def hyphenator=(h)
- raise ArgumentError, "#{h.inspect} is not a valid hyphenator." unless h.respond_to?(:hyphenate_to)
- arity = h.method(:hyphenate_to).arity
- raise ArgumentError, "#{h.inspect} must have exactly two or three arguments." unless [2, 3].include?(arity)
- @hyphenator = h
- @hyphenator_arity = arity
- end
-
- # Specifies the split mode; used only when #hard_margins is set to
- # +true+. Allowable values are:
- # [+SPLIT_FIXED+] The word will be split at the number of
- # characters needed, with no marking at all.
- # repre
- # senta
- # ion
- # [+SPLIT_CONTINUATION+] The word will be split at the number of
- # characters needed, with a C-style continuation
- # character. If a word is the only item on a
- # line and it cannot be split into an
- # appropriate size, SPLIT_FIXED will be used.
- # repr\
- # esen\
- # tati\
- # on
- # [+SPLIT_HYPHENATION+] The word will be split according to the
- # hyphenator specified in #hyphenator. If there
- # is no #hyphenator specified, works like
- # SPLIT_CONTINUATION. The example is using
- # TeX::Hyphen. If a word is the only item on a
- # line and it cannot be split into an
- # appropriate size, SPLIT_CONTINUATION mode will
- # be used.
- # rep-
- # re-
- # sen-
- # ta-
- # tion
- #
- # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_reader :split_rules
-
- # Specifies the split mode; used only when #hard_margins is set to
- # +true+. Allowable values are:
- # [+SPLIT_FIXED+] The word will be split at the number of
- # characters needed, with no marking at all.
- # repre
- # senta
- # ion
- # [+SPLIT_CONTINUATION+] The word will be split at the number of
- # characters needed, with a C-style continuation
- # character.
- # repr\
- # esen\
- # tati\
- # on
- # [+SPLIT_HYPHENATION+] The word will be split according to the
- # hyphenator specified in #hyphenator. If there
- # is no #hyphenator specified, works like
- # SPLIT_CONTINUATION. The example is using
- # TeX::Hyphen as the #hyphenator.
- # rep-
- # re-
- # sen-
- # ta-
- # tion
- #
- # These values can be bitwise ORed together (e.g., <tt>SPLIT_FIXED |
- # SPLIT_CONTINUATION</tt>) to provide fallback split methods. In the
- # example given, an attempt will be made to split the word using the
- # rules of SPLIT_CONTINUATION; if there is not enough room, the word
- # will be split with the rules of SPLIT_FIXED. These combinations are
- # also available as the following values:
- # * +SPLIT_CONTINUATION_FIXED+
- # * +SPLIT_HYPHENATION_FIXED+
- # * +SPLIT_HYPHENATION_CONTINUATION+
- # * +SPLIT_ALL+
- #
- # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def split_rules=(s)
- raise ArgumentError, "Invalid value provided for split_rules." if ((s < SPLIT_FIXED) || (s > SPLIT_ALL))
- @split_rules = s
- end
-
- # Indicates whether sentence terminators should be followed by a single
- # space (+false+), or two spaces (+true+).
- #
- # *Default*:: +false+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_accessor :extra_space
-
- # Defines the current abbreviations as an array. This is only used if
- # extra_space is turned on.
- #
- # If one is abbreviating "President" as "Pres." (abbreviations =
- # ["Pres"]), then the results of formatting will be as illustrated in
- # the table below:
- #
- # extra_space | include? | !include?
- # true | Pres. Lincoln | Pres. Lincoln
- # false | Pres. Lincoln | Pres. Lincoln
- #
- # *Default*:: <tt>{}</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_accessor :abbreviations
-
- # Indicates whether the formatting of paragraphs should be done with
- # tagged paragraphs. Useful only with <tt>#tag_text</tt>.
- #
- # *Default*:: +false+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_accessor :tag_paragraph
-
- # The array of text to be placed before each paragraph when
- # <tt>#tag_paragraph</tt> is +true+. When <tt>#format()</tt> is called,
- # only the first element of the array is used. When <tt>#paragraphs</tt>
- # is called, then each entry in the array will be used once, with
- # corresponding paragraphs. If the tag elements are exhausted before the
- # text is exhausted, then the remaining paragraphs will not be tagged.
- # Regardless of indentation settings, a blank line will be inserted
- # between all paragraphs when <tt>#tag_paragraph</tt> is +true+.
- #
- # *Default*:: <tt>[]</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_accessor :tag_text
-
- # Indicates whether or not the non-breaking space feature should be
- # used.
- #
- # *Default*:: +false+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_accessor :nobreak
-
- # A hash which holds the regular expressions on which spaces should not
- # be broken. The hash is set up such that the key is the first word and
- # the value is the second word.
- #
- # For example, if +nobreak_regex+ contains the following hash:
- #
- # { '^Mrs?\.$' => '\S+$', '^\S+$' => '^(?:S|J)r\.$'}
- #
- # Then "Mr. Jones", "Mrs. Jones", and "Jones Jr." would not be broken.
- # If this simple matching algorithm indicates that there should not be a
- # break at the current end of line, then a backtrack is done until there
- # are two words on which line breaking is permitted. If two such words
- # are not found, then the end of the line will be broken *regardless*.
- # If there is a single word on the current line, then no backtrack is
- # done and the word is stuck on the end.
- #
- # *Default*:: <tt>{}</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_accessor :nobreak_regex
-
- # Indicates the number of spaces that a single tab represents.
- #
- # *Default*:: <tt>8</tt>
- # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
- # <tt>#paragraphs</tt>
- attr_reader :tabstop
-
- # Indicates the number of spaces that a single tab represents.
- #
- # *Default*:: <tt>8</tt>
- # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
- # <tt>#paragraphs</tt>
- def tabstop=(t)
- @tabstop = posint(t)
- end
-
- # Specifies the format style. Allowable values are:
- # [+LEFT_ALIGN+] Left justified, ragged right.
- # |A paragraph that is|
- # |left aligned.|
- # [+RIGHT_ALIGN+] Right justified, ragged left.
- # |A paragraph that is|
- # | right aligned.|
- # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
- # spaces. (Essentially the same as +LEFT_ALIGN+ except
- # that lines are padded on the right.)
- # |A paragraph that is|
- # |left aligned. |
- # [+JUSTIFY+] Fully justified, words filled to width by spaces,
- # except the last line.
- # |A paragraph that|
- # |is justified.|
- #
- # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- attr_reader :format_style
-
- # Specifies the format style. Allowable values are:
- # [+LEFT_ALIGN+] Left justified, ragged right.
- # |A paragraph that is|
- # |left aligned.|
- # [+RIGHT_ALIGN+] Right justified, ragged left.
- # |A paragraph that is|
- # | right aligned.|
- # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
- # spaces. (Essentially the same as +LEFT_ALIGN+ except
- # that lines are padded on the right.)
- # |A paragraph that is|
- # |left aligned. |
- # [+JUSTIFY+] Fully justified, words filled to width by spaces.
- # |A paragraph that|
- # |is justified.|
- #
- # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def format_style=(fs)
- raise ArgumentError, "Invalid value provided for format_style." if ((fs < LEFT_ALIGN) || (fs > JUSTIFY))
- @format_style = fs
- end
-
- # Indicates that the format style is left alignment.
- #
- # *Default*:: +true+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def left_align?
- return @format_style == LEFT_ALIGN
- end
-
- # Indicates that the format style is right alignment.
- #
- # *Default*:: +false+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def right_align?
- return @format_style == RIGHT_ALIGN
- end
-
- # Indicates that the format style is right fill.
- #
- # *Default*:: +false+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def right_fill?
- return @format_style == RIGHT_FILL
- end
-
- # Indicates that the format style is full justification.
- #
- # *Default*:: +false+
- # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
- def justify?
- return @format_style == JUSTIFY
- end
-
- # The default implementation of #hyphenate_to implements
- # SPLIT_CONTINUATION.
- def hyphenate_to(word, size)
- [word[0 .. (size - 2)] + "\\", word[(size - 1) .. -1]]
- end
-
- private
- def __do_split_word(word, size) #:nodoc:
- [word[0 .. (size - 1)], word[size .. -1]]
- end
-
- def __format(to_wrap) #:nodoc:
- words = to_wrap.split(/\s+/).compact
- words.shift if words[0].nil? or words[0].empty?
- to_wrap = []
-
- abbrev = false
- width = @columns - @first_indent - @left_margin - @right_margin
- indent_str = ' ' * @first_indent
- first_line = true
- line = words.shift
- abbrev = __is_abbrev(line) unless line.nil? || line.empty?
-
- while w = words.shift
- if (w.size + line.size < (width - 1)) ||
- ((line !~ LEQ_RE || abbrev) && (w.size + line.size < width))
- line << " " if (line =~ LEQ_RE) && (not abbrev)
- line << " #{w}"
- else
- line, w = __do_break(line, w) if @nobreak
- line, w = __do_hyphenate(line, w, width) if @hard_margins
- if w.index(/\s+/)
- w, *w2 = w.split(/\s+/)
- words.unshift(w2)
- words.flatten!
- end
- to_wrap << __make_line(line, indent_str, width, w.nil?) unless line.nil?
- if first_line
- first_line = false
- width = @columns - @body_indent - @left_margin - @right_margin
- indent_str = ' ' * @body_indent
- end
- line = w
- end
-
- abbrev = __is_abbrev(w) unless w.nil?
- end
-
- loop do
- break if line.nil? or line.empty?
- line, w = __do_hyphenate(line, w, width) if @hard_margins
- to_wrap << __make_line(line, indent_str, width, w.nil?)
- line = w
- end
-
- if (@tag_paragraph && (to_wrap.size > 0)) then
- clr = %r{`(\w+)'}.match([caller(1)].flatten[0])[1]
- clr = "" if clr.nil?
-
- if ((not @tag_text[0].nil?) && (@tag_cur.size < 1) &&
- (clr != "__paragraphs")) then
- @tag_cur = @tag_text[0]
- end
-
- fchar = /(\S)/.match(to_wrap[0])[1]
- white = to_wrap[0].index(fchar)
- if ((white - @left_margin - 1) > @tag_cur.size) then
- white = @tag_cur.size + @left_margin
- to_wrap[0].gsub!(/^ {#{white}}/, "#{' ' * @left_margin}#{@tag_cur}")
- else
- to_wrap.unshift("#{' ' * @left_margin}#{@tag_cur}\n")
- end
- end
- to_wrap.join('')
- end
-
- # format lines in text into paragraphs with each element of @wrap a
- # paragraph; uses Text::Format.format for the formatting
- def __paragraphs(to_wrap) #:nodoc:
- if ((@first_indent == @body_indent) || @tag_paragraph) then
- p_end = "\n"
- else
- p_end = ''
- end
-
- cnt = 0
- ret = []
- to_wrap.each do |tw|
- @tag_cur = @tag_text[cnt] if @tag_paragraph
- @tag_cur = '' if @tag_cur.nil?
- line = __format(tw)
- ret << "#{line}#{p_end}" if (not line.nil?) && (line.size > 0)
- cnt += 1
- end
-
- ret[-1].chomp! unless ret.empty?
- ret.join('')
- end
-
- # center text using spaces on left side to pad it out empty lines
- # are preserved
- def __center(to_center) #:nodoc:
- tabs = 0
- width = @columns - @left_margin - @right_margin
- centered = []
- to_center.each do |tc|
- s = tc.strip
- tabs = s.count("\t")
- tabs = 0 if tabs.nil?
- ct = ((width - s.size - (tabs * @tabstop) + tabs) / 2)
- ct = (width - @left_margin - @right_margin) - ct
- centered << "#{s.rjust(ct)}\n"
- end
- centered.join('')
- end
-
- # expand tabs to spaces should be similar to Text::Tabs::expand
- def __expand(to_expand) #:nodoc:
- expanded = []
- to_expand.split("\n").each { |te| expanded << te.gsub(/\t/, ' ' * @tabstop) }
- expanded.join('')
- end
-
- def __unexpand(to_unexpand) #:nodoc:
- unexpanded = []
- to_unexpand.split("\n").each { |tu| unexpanded << tu.gsub(/ {#{@tabstop}}/, "\t") }
- unexpanded.join('')
- end
-
- def __is_abbrev(word) #:nodoc:
- # remove period if there is one.
- w = word.gsub(/\.$/, '') unless word.nil?
- return true if (!@extra_space || ABBREV.include?(w) || @abbreviations.include?(w))
- false
- end
-
- def __make_line(line, indent, width, last = false) #:nodoc:
- lmargin = " " * @left_margin
- fill = " " * (width - line.size) if right_fill? && (line.size <= width)
-
- if (justify? && ((not line.nil?) && (not line.empty?)) && line =~ /\S+\s+\S+/ && !last)
- spaces = width - line.size
- words = line.split(/(\s+)/)
- ws = spaces / (words.size / 2)
- spaces = spaces % (words.size / 2) if ws > 0
- words.reverse.each do |rw|
- next if (rw =~ /^\S/)
- rw.sub!(/^/, " " * ws)
- next unless (spaces > 0)
- rw.sub!(/^/, " ")
- spaces -= 1
- end
- line = words.join('')
- end
- line = "#{lmargin}#{indent}#{line}#{fill}\n" unless line.nil?
- if right_align? && (not line.nil?)
- line.sub(/^/, " " * (@columns - @right_margin - (line.size - 1)))
- else
- line
- end
- end
-
- def __do_hyphenate(line, next_line, width) #:nodoc:
- rline = line.dup rescue line
- rnext = next_line.dup rescue next_line
- loop do
- if rline.size == width
- break
- elsif rline.size > width
- words = rline.strip.split(/\s+/)
- word = words[-1].dup
- size = width - rline.size + word.size
- if (size <= 0)
- words[-1] = nil
- rline = words.join(' ').strip
- rnext = "#{word} #{rnext}".strip
- next
- end
-
- first = rest = nil
-
- if ((@split_rules & SPLIT_HYPHENATION) != 0)
- if @hyphenator_arity == 2
- first, rest = @hyphenator.hyphenate_to(word, size)
- else
- first, rest = @hyphenator.hyphenate_to(word, size, self)
- end
- end
-
- if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
- first, rest = self.hyphenate_to(word, size)
- end
-
- if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
- first.nil? or @split_rules == SPLIT_FIXED
- first, rest = __do_split_word(word, size)
- end
-
- if first.nil?
- words[-1] = nil
- rest = word
- else
- words[-1] = first
- @split_words << SplitWord.new(word, first, rest)
- end
- rline = words.join(' ').strip
- rnext = "#{rest} #{rnext}".strip
- break
- else
- break if rnext.nil? or rnext.empty? or rline.nil? or rline.empty?
- words = rnext.split(/\s+/)
- word = words.shift
- size = width - rline.size - 1
-
- if (size <= 0)
- rnext = "#{word} #{words.join(' ')}".strip
- break
- end
-
- first = rest = nil
-
- if ((@split_rules & SPLIT_HYPHENATION) != 0)
- if @hyphenator_arity == 2
- first, rest = @hyphenator.hyphenate_to(word, size)
- else
- first, rest = @hyphenator.hyphenate_to(word, size, self)
- end
- end
-
- first, rest = self.hyphenate_to(word, size) if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
-
- first, rest = __do_split_word(word, size) if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
-
- if (rline.size + (first ? first.size : 0)) < width
- @split_words << SplitWord.new(word, first, rest)
- rline = "#{rline} #{first}".strip
- rnext = "#{rest} #{words.join(' ')}".strip
- end
- break
- end
- end
- [rline, rnext]
- end
-
- def __do_break(line, next_line) #:nodoc:
- no_brk = false
- words = []
- words = line.split(/\s+/) unless line.nil?
- last_word = words[-1]
-
- @nobreak_regex.each { |k, v| no_brk = ((last_word =~ /#{k}/) and (next_line =~ /#{v}/)) }
-
- if no_brk && words.size > 1
- i = words.size
- while i > 0
- no_brk = false
- @nobreak_regex.each { |k, v| no_brk = ((words[i + 1] =~ /#{k}/) && (words[i] =~ /#{v}/)) }
- i -= 1
- break if not no_brk
- end
- if i > 0
- l = brk_re(i).match(line)
- line.sub!(brk_re(i), l[1])
- next_line = "#{l[2]} #{next_line}"
- line.sub!(/\s+$/, '')
- end
- end
- [line, next_line]
- end
-
- def __create(arg = nil, &block) #:nodoc:
- # Format::Text.new(text-to-wrap)
- @text = arg unless arg.nil?
- # Defaults
- @columns = 72
- @tabstop = 8
- @first_indent = 4
- @body_indent = 0
- @format_style = LEFT_ALIGN
- @left_margin = 0
- @right_margin = 0
- @extra_space = false
- @text = Array.new if @text.nil?
- @tag_paragraph = false
- @tag_text = Array.new
- @tag_cur = ""
- @abbreviations = Array.new
- @nobreak = false
- @nobreak_regex = Hash.new
- @split_words = Array.new
- @hard_margins = false
- @split_rules = SPLIT_FIXED
- @hyphenator = self
- @hyphenator_arity = self.method(:hyphenate_to).arity
-
- instance_eval(&block) unless block.nil?
- end
-
- public
- # Formats text into a nice paragraph format. The text is separated
- # into words and then reassembled a word at a time using the settings
- # of this Format object. If a word is larger than the number of
- # columns available for formatting, then that word will appear on the
- # line by itself.
- #
- # If +to_wrap+ is +nil+, then the value of <tt>#text</tt> will be
- # worked on.
- def format(to_wrap = nil)
- to_wrap = @text if to_wrap.nil?
- if to_wrap.class == Array
- __format(to_wrap[0])
- else
- __format(to_wrap)
- end
- end
-
- # Considers each element of text (provided or internal) as a paragraph.
- # If <tt>#first_indent</tt> is the same as <tt>#body_indent</tt>, then
- # paragraphs will be separated by a single empty line in the result;
- # otherwise, the paragraphs will follow immediately after each other.
- # Uses <tt>#format</tt> to do the heavy lifting.
- def paragraphs(to_wrap = nil)
- to_wrap = @text if to_wrap.nil?
- __paragraphs([to_wrap].flatten)
- end
-
- # Centers the text, preserving empty lines and tabs.
- def center(to_center = nil)
- to_center = @text if to_center.nil?
- __center([to_center].flatten)
- end
-
- # Replaces all tab characters in the text with <tt>#tabstop</tt> spaces.
- def expand(to_expand = nil)
- to_expand = @text if to_expand.nil?
- if to_expand.class == Array
- to_expand.collect { |te| __expand(te) }
- else
- __expand(to_expand)
- end
- end
-
- # Replaces all occurrences of <tt>#tabstop</tt> consecutive spaces
- # with a tab character.
- def unexpand(to_unexpand = nil)
- to_unexpand = @text if to_unexpand.nil?
- if to_unexpand.class == Array
- to_unexpand.collect { |te| v << __unexpand(te) }
- else
- __unexpand(to_unexpand)
- end
- end
-
- # This constructor takes advantage of a technique for Ruby object
- # construction introduced by Andy Hunt and Dave Thomas (see reference),
- # where optional values are set using commands in a block.
- #
- # Text::Format.new {
- # columns = 72
- # left_margin = 0
- # right_margin = 0
- # first_indent = 4
- # body_indent = 0
- # format_style = Text::Format::LEFT_ALIGN
- # extra_space = false
- # abbreviations = {}
- # tag_paragraph = false
- # tag_text = []
- # nobreak = false
- # nobreak_regex = {}
- # tabstop = 8
- # text = nil
- # }
- #
- # As shown above, +arg+ is optional. If +arg+ is specified and is a
- # +String+, then arg is used as the default value of <tt>#text</tt>.
- # Alternately, an existing Text::Format object can be used or a Hash can
- # be used. With all forms, a block can be specified.
- #
- # *Reference*:: "Object Construction and Blocks"
- # <http://www.pragmaticprogrammer.com/ruby/articles/insteval.html>
- #
- def initialize(arg = nil, &block)
- case arg
- when Text::Format
- __create(arg.text) do
- @columns = arg.columns
- @tabstop = arg.tabstop
- @first_indent = arg.first_indent
- @body_indent = arg.body_indent
- @format_style = arg.format_style
- @left_margin = arg.left_margin
- @right_margin = arg.right_margin
- @extra_space = arg.extra_space
- @tag_paragraph = arg.tag_paragraph
- @tag_text = arg.tag_text
- @abbreviations = arg.abbreviations
- @nobreak = arg.nobreak
- @nobreak_regex = arg.nobreak_regex
- @text = arg.text
- @hard_margins = arg.hard_margins
- @split_words = arg.split_words
- @split_rules = arg.split_rules
- @hyphenator = arg.hyphenator
- end
- instance_eval(&block) unless block.nil?
- when Hash
- __create do
- @columns = arg[:columns] || arg['columns'] || @columns
- @tabstop = arg[:tabstop] || arg['tabstop'] || @tabstop
- @first_indent = arg[:first_indent] || arg['first_indent'] || @first_indent
- @body_indent = arg[:body_indent] || arg['body_indent'] || @body_indent
- @format_style = arg[:format_style] || arg['format_style'] || @format_style
- @left_margin = arg[:left_margin] || arg['left_margin'] || @left_margin
- @right_margin = arg[:right_margin] || arg['right_margin'] || @right_margin
- @extra_space = arg[:extra_space] || arg['extra_space'] || @extra_space
- @text = arg[:text] || arg['text'] || @text
- @tag_paragraph = arg[:tag_paragraph] || arg['tag_paragraph'] || @tag_paragraph
- @tag_text = arg[:tag_text] || arg['tag_text'] || @tag_text
- @abbreviations = arg[:abbreviations] || arg['abbreviations'] || @abbreviations
- @nobreak = arg[:nobreak] || arg['nobreak'] || @nobreak
- @nobreak_regex = arg[:nobreak_regex] || arg['nobreak_regex'] || @nobreak_regex
- @hard_margins = arg[:hard_margins] || arg['hard_margins'] || @hard_margins
- @split_rules = arg[:split_rules] || arg['split_rules'] || @split_rules
- @hyphenator = arg[:hyphenator] || arg['hyphenator'] || @hyphenator
- end
- instance_eval(&block) unless block.nil?
- when String
- __create(arg, &block)
- when NilClass
- __create(&block)
- else
- raise TypeError
- end
- end
- end
-end
-
-if __FILE__ == $0
- require 'test/unit'
-
- class TestText__Format < Test::Unit::TestCase #:nodoc:
- attr_accessor :format_o
-
- GETTYSBURG = <<-'EOS'
- Four score and seven years ago our fathers brought forth on this
- continent a new nation, conceived in liberty and dedicated to the
- proposition that all men are created equal. Now we are engaged in
- a great civil war, testing whether that nation or any nation so
- conceived and so dedicated can long endure. We are met on a great
- battlefield of that war. We have come to dedicate a portion of
- that field as a final resting-place for those who here gave their
- lives that that nation might live. It is altogether fitting and
- proper that we should do this. But in a larger sense, we cannot
- dedicate, we cannot consecrate, we cannot hallow this ground.
- The brave men, living and dead who struggled here have consecrated
- it far above our poor power to add or detract. The world will
- little note nor long remember what we say here, but it can never
- forget what they did here. It is for us the living rather to be
- dedicated here to the unfinished work which they who fought here
- have thus far so nobly advanced. It is rather for us to be here
- dedicated to the great task remaining before us--that from these
- honored dead we take increased devotion to that cause for which
- they gave the last full measure of devotion--that we here highly
- resolve that these dead shall not have died in vain, that this
- nation under God shall have a new birth of freedom, and that
- government of the people, by the people, for the people shall
- not perish from the earth.
-
- -- Pres. Abraham Lincoln, 19 November 1863
- EOS
-
- FIVE_COL = "Four \nscore\nand s\neven \nyears\nago o\nur fa\nthers\nbroug\nht fo\nrth o\nn thi\ns con\ntinen\nt a n\new na\ntion,\nconce\nived \nin li\nberty\nand d\nedica\nted t\no the\npropo\nsitio\nn tha\nt all\nmen a\nre cr\neated\nequal\n. Now\nwe ar\ne eng\naged \nin a \ngreat\ncivil\nwar, \ntesti\nng wh\nether\nthat \nnatio\nn or \nany n\nation\nso co\nnceiv\ned an\nd so \ndedic\nated \ncan l\nong e\nndure\n. We \nare m\net on\na gre\nat ba\nttlef\nield \nof th\nat wa\nr. We\nhave \ncome \nto de\ndicat\ne a p\nortio\nn of \nthat \nfield\nas a \nfinal\nresti\nng-pl\nace f\nor th\nose w\nho he\nre ga\nve th\neir l\nives \nthat \nthat \nnatio\nn mig\nht li\nve. I\nt is \naltog\nether\nfitti\nng an\nd pro\nper t\nhat w\ne sho\nuld d\no thi\ns. Bu\nt in \na lar\nger s\nense,\nwe ca\nnnot \ndedic\nate, \nwe ca\nnnot \nconse\ncrate\n, we \ncanno\nt hal\nlow t\nhis g\nround\n. The\nbrave\nmen, \nlivin\ng and\ndead \nwho s\ntrugg\nled h\nere h\nave c\nonsec\nrated\nit fa\nr abo\nve ou\nr poo\nr pow\ner to\nadd o\nr det\nract.\nThe w\norld \nwill \nlittl\ne not\ne nor\nlong \nremem\nber w\nhat w\ne say\nhere,\nbut i\nt can\nnever\nforge\nt wha\nt the\ny did\nhere.\nIt is\nfor u\ns the\nlivin\ng rat\nher t\no be \ndedic\nated \nhere \nto th\ne unf\ninish\ned wo\nrk wh\nich t\nhey w\nho fo\nught \nhere \nhave \nthus \nfar s\no nob\nly ad\nvance\nd. It\nis ra\nther \nfor u\ns to \nbe he\nre de\ndicat\ned to\nthe g\nreat \ntask \nremai\nning \nbefor\ne us-\n-that\nfrom \nthese\nhonor\ned de\nad we\ntake \nincre\nased \ndevot\nion t\no tha\nt cau\nse fo\nr whi\nch th\ney ga\nve th\ne las\nt ful\nl mea\nsure \nof de\nvotio\nn--th\nat we\nhere \nhighl\ny res\nolve \nthat \nthese\ndead \nshall\nnot h\nave d\nied i\nn vai\nn, th\nat th\nis na\ntion \nunder\nGod s\nhall \nhave \na new\nbirth\nof fr\needom\n, and\nthat \ngover\nnment\nof th\ne peo\nple, \nby th\ne peo\nple, \nfor t\nhe pe\nople \nshall\nnot p\nerish\nfrom \nthe e\narth.\n-- Pr\nes. A\nbraha\nm Lin\ncoln,\n19 No\nvembe\nr 186\n3 \n"
-
- FIVE_CNT = "Four \nscore\nand \nseven\nyears\nago \nour \nfath\\\ners \nbrou\\\nght \nforth\non t\\\nhis \ncont\\\ninent\na new\nnati\\\non, \nconc\\\neived\nin l\\\niber\\\nty a\\\nnd d\\\nedic\\\nated \nto t\\\nhe p\\\nropo\\\nsiti\\\non t\\\nhat \nall \nmen \nare \ncrea\\\nted \nequa\\\nl. N\\\now we\nare \nenga\\\nged \nin a \ngreat\ncivil\nwar, \ntest\\\ning \nwhet\\\nher \nthat \nnati\\\non or\nany \nnati\\\non so\nconc\\\neived\nand \nso d\\\nedic\\\nated \ncan \nlong \nendu\\\nre. \nWe a\\\nre m\\\net on\na gr\\\neat \nbatt\\\nlefi\\\neld \nof t\\\nhat \nwar. \nWe h\\\nave \ncome \nto d\\\nedic\\\nate a\nport\\\nion \nof t\\\nhat \nfield\nas a \nfinal\nrest\\\ning-\\\nplace\nfor \nthose\nwho \nhere \ngave \ntheir\nlives\nthat \nthat \nnati\\\non m\\\night \nlive.\nIt is\nalto\\\ngeth\\\ner f\\\nitti\\\nng a\\\nnd p\\\nroper\nthat \nwe s\\\nhould\ndo t\\\nhis. \nBut \nin a \nlarg\\\ner s\\\nense,\nwe c\\\nannot\ndedi\\\ncate,\nwe c\\\nannot\ncons\\\necra\\\nte, \nwe c\\\nannot\nhall\\\now t\\\nhis \ngrou\\\nnd. \nThe \nbrave\nmen, \nlivi\\\nng a\\\nnd d\\\nead \nwho \nstru\\\nggled\nhere \nhave \ncons\\\necra\\\nted \nit f\\\nar a\\\nbove \nour \npoor \npower\nto a\\\ndd or\ndetr\\\nact. \nThe \nworld\nwill \nlitt\\\nle n\\\note \nnor \nlong \nreme\\\nmber \nwhat \nwe s\\\nay h\\\nere, \nbut \nit c\\\nan n\\\never \nforg\\\net w\\\nhat \nthey \ndid \nhere.\nIt is\nfor \nus t\\\nhe l\\\niving\nrath\\\ner to\nbe d\\\nedic\\\nated \nhere \nto t\\\nhe u\\\nnfin\\\nished\nwork \nwhich\nthey \nwho \nfoug\\\nht h\\\nere \nhave \nthus \nfar \nso n\\\nobly \nadva\\\nnced.\nIt is\nrath\\\ner f\\\nor us\nto be\nhere \ndedi\\\ncated\nto t\\\nhe g\\\nreat \ntask \nrema\\\nining\nbefo\\\nre u\\\ns--t\\\nhat \nfrom \nthese\nhono\\\nred \ndead \nwe t\\\nake \nincr\\\neased\ndevo\\\ntion \nto t\\\nhat \ncause\nfor \nwhich\nthey \ngave \nthe \nlast \nfull \nmeas\\\nure \nof d\\\nevot\\\nion-\\\n-that\nwe h\\\nere \nhigh\\\nly r\\\nesol\\\nve t\\\nhat \nthese\ndead \nshall\nnot \nhave \ndied \nin v\\\nain, \nthat \nthis \nnati\\\non u\\\nnder \nGod \nshall\nhave \na new\nbirth\nof f\\\nreed\\\nom, \nand \nthat \ngove\\\nrnme\\\nnt of\nthe \npeop\\\nle, \nby t\\\nhe p\\\neopl\\\ne, f\\\nor t\\\nhe p\\\neople\nshall\nnot \nperi\\\nsh f\\\nrom \nthe \neart\\\nh. --\nPres.\nAbra\\\nham \nLinc\\\noln, \n19 N\\\novem\\\nber \n1863 \n"
-
- # Tests both abbreviations and abbreviations=
- def test_abbreviations
- abbr = [" Pres. Abraham Lincoln\n", " Pres. Abraham Lincoln\n"]
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal([], @format_o.abbreviations)
- assert_nothing_raised { @format_o.abbreviations = [ 'foo', 'bar' ] }
- assert_equal([ 'foo', 'bar' ], @format_o.abbreviations)
- assert_equal(abbr[0], @format_o.format(abbr[0]))
- assert_nothing_raised { @format_o.extra_space = true }
- assert_equal(abbr[1], @format_o.format(abbr[0]))
- assert_nothing_raised { @format_o.abbreviations = [ "Pres" ] }
- assert_equal([ "Pres" ], @format_o.abbreviations)
- assert_equal(abbr[0], @format_o.format(abbr[0]))
- assert_nothing_raised { @format_o.extra_space = false }
- assert_equal(abbr[0], @format_o.format(abbr[0]))
- end
-
- # Tests both body_indent and body_indent=
- def test_body_indent
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(0, @format_o.body_indent)
- assert_nothing_raised { @format_o.body_indent = 7 }
- assert_equal(7, @format_o.body_indent)
- assert_nothing_raised { @format_o.body_indent = -3 }
- assert_equal(3, @format_o.body_indent)
- assert_nothing_raised { @format_o.body_indent = "9" }
- assert_equal(9, @format_o.body_indent)
- assert_nothing_raised { @format_o.body_indent = "-2" }
- assert_equal(2, @format_o.body_indent)
- assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[1])
- end
-
- # Tests both columns and columns=
- def test_columns
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(72, @format_o.columns)
- assert_nothing_raised { @format_o.columns = 7 }
- assert_equal(7, @format_o.columns)
- assert_nothing_raised { @format_o.columns = -3 }
- assert_equal(3, @format_o.columns)
- assert_nothing_raised { @format_o.columns = "9" }
- assert_equal(9, @format_o.columns)
- assert_nothing_raised { @format_o.columns = "-2" }
- assert_equal(2, @format_o.columns)
- assert_nothing_raised { @format_o.columns = 40 }
- assert_equal(40, @format_o.columns)
- assert_match(/this continent$/,
- @format_o.format(GETTYSBURG).split("\n")[1])
- end
-
- # Tests both extra_space and extra_space=
- def test_extra_space
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(!@format_o.extra_space)
- assert_nothing_raised { @format_o.extra_space = true }
- assert(@format_o.extra_space)
- # The behaviour of extra_space is tested in test_abbreviations. There
- # is no need to reproduce it here.
- end
-
- # Tests both first_indent and first_indent=
- def test_first_indent
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(4, @format_o.first_indent)
- assert_nothing_raised { @format_o.first_indent = 7 }
- assert_equal(7, @format_o.first_indent)
- assert_nothing_raised { @format_o.first_indent = -3 }
- assert_equal(3, @format_o.first_indent)
- assert_nothing_raised { @format_o.first_indent = "9" }
- assert_equal(9, @format_o.first_indent)
- assert_nothing_raised { @format_o.first_indent = "-2" }
- assert_equal(2, @format_o.first_indent)
- assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[0])
- end
-
- def test_format_style
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(Text::Format::LEFT_ALIGN, @format_o.format_style)
- assert_match(/^November 1863$/,
- @format_o.format(GETTYSBURG).split("\n")[-1])
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_ALIGN
- }
- assert_equal(Text::Format::RIGHT_ALIGN, @format_o.format_style)
- assert_match(/^ +November 1863$/,
- @format_o.format(GETTYSBURG).split("\n")[-1])
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_FILL
- }
- assert_equal(Text::Format::RIGHT_FILL, @format_o.format_style)
- assert_match(/^November 1863 +$/,
- @format_o.format(GETTYSBURG).split("\n")[-1])
- assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
- assert_equal(Text::Format::JUSTIFY, @format_o.format_style)
- assert_match(/^of freedom, and that government of the people, by the people, for the$/,
- @format_o.format(GETTYSBURG).split("\n")[-3])
- assert_raise(ArgumentError) { @format_o.format_style = 33 }
- end
-
- def test_tag_paragraph
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(!@format_o.tag_paragraph)
- assert_nothing_raised { @format_o.tag_paragraph = true }
- assert(@format_o.tag_paragraph)
- assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
- Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
- end
-
- def test_tag_text
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal([], @format_o.tag_text)
- assert_equal(@format_o.format(GETTYSBURG),
- Text::Format.new.format(GETTYSBURG))
- assert_nothing_raised {
- @format_o.tag_paragraph = true
- @format_o.tag_text = ["Gettysburg Address", "---"]
- }
- assert_not_equal(@format_o.format(GETTYSBURG),
- Text::Format.new.format(GETTYSBURG))
- assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
- Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
- assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG,
- GETTYSBURG]),
- Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG,
- GETTYSBURG]))
- end
-
- def test_justify?
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(!@format_o.justify?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_ALIGN
- }
- assert(!@format_o.justify?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_FILL
- }
- assert(!@format_o.justify?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::JUSTIFY
- }
- assert(@format_o.justify?)
- # The format testing is done in test_format_style
- end
-
- def test_left_align?
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(@format_o.left_align?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_ALIGN
- }
- assert(!@format_o.left_align?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_FILL
- }
- assert(!@format_o.left_align?)
- assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
- assert(!@format_o.left_align?)
- # The format testing is done in test_format_style
- end
-
- def test_left_margin
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(0, @format_o.left_margin)
- assert_nothing_raised { @format_o.left_margin = -3 }
- assert_equal(3, @format_o.left_margin)
- assert_nothing_raised { @format_o.left_margin = "9" }
- assert_equal(9, @format_o.left_margin)
- assert_nothing_raised { @format_o.left_margin = "-2" }
- assert_equal(2, @format_o.left_margin)
- assert_nothing_raised { @format_o.left_margin = 7 }
- assert_equal(7, @format_o.left_margin)
- assert_nothing_raised {
- ft = @format_o.format(GETTYSBURG).split("\n")
- assert_match(/^ {11}Four score/, ft[0])
- assert_match(/^ {7}November/, ft[-1])
- }
- end
-
- def test_hard_margins
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(!@format_o.hard_margins)
- assert_nothing_raised {
- @format_o.hard_margins = true
- @format_o.columns = 5
- @format_o.first_indent = 0
- @format_o.format_style = Text::Format::RIGHT_FILL
- }
- assert(@format_o.hard_margins)
- assert_equal(FIVE_COL, @format_o.format(GETTYSBURG))
- assert_nothing_raised {
- @format_o.split_rules |= Text::Format::SPLIT_CONTINUATION
- assert_equal(Text::Format::SPLIT_CONTINUATION_FIXED,
- @format_o.split_rules)
- }
- assert_equal(FIVE_CNT, @format_o.format(GETTYSBURG))
- end
-
- # Tests both nobreak and nobreak_regex, since one is only useful
- # with the other.
- def test_nobreak
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(!@format_o.nobreak)
- assert(@format_o.nobreak_regex.empty?)
- assert_nothing_raised {
- @format_o.nobreak = true
- @format_o.nobreak_regex = { '^this$' => '^continent$' }
- @format_o.columns = 77
- }
- assert(@format_o.nobreak)
- assert_equal({ '^this$' => '^continent$' }, @format_o.nobreak_regex)
- assert_match(/^this continent/,
- @format_o.format(GETTYSBURG).split("\n")[1])
- end
-
- def test_right_align?
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(!@format_o.right_align?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_ALIGN
- }
- assert(@format_o.right_align?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_FILL
- }
- assert(!@format_o.right_align?)
- assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
- assert(!@format_o.right_align?)
- # The format testing is done in test_format_style
- end
-
- def test_right_fill?
- assert_nothing_raised { @format_o = Text::Format.new }
- assert(!@format_o.right_fill?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_ALIGN
- }
- assert(!@format_o.right_fill?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::RIGHT_FILL
- }
- assert(@format_o.right_fill?)
- assert_nothing_raised {
- @format_o.format_style = Text::Format::JUSTIFY
- }
- assert(!@format_o.right_fill?)
- # The format testing is done in test_format_style
- end
-
- def test_right_margin
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(0, @format_o.right_margin)
- assert_nothing_raised { @format_o.right_margin = -3 }
- assert_equal(3, @format_o.right_margin)
- assert_nothing_raised { @format_o.right_margin = "9" }
- assert_equal(9, @format_o.right_margin)
- assert_nothing_raised { @format_o.right_margin = "-2" }
- assert_equal(2, @format_o.right_margin)
- assert_nothing_raised { @format_o.right_margin = 7 }
- assert_equal(7, @format_o.right_margin)
- assert_nothing_raised {
- ft = @format_o.format(GETTYSBURG).split("\n")
- assert_match(/^ {4}Four score.*forth on$/, ft[0])
- assert_match(/^November/, ft[-1])
- }
- end
-
- def test_tabstop
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(8, @format_o.tabstop)
- assert_nothing_raised { @format_o.tabstop = 7 }
- assert_equal(7, @format_o.tabstop)
- assert_nothing_raised { @format_o.tabstop = -3 }
- assert_equal(3, @format_o.tabstop)
- assert_nothing_raised { @format_o.tabstop = "9" }
- assert_equal(9, @format_o.tabstop)
- assert_nothing_raised { @format_o.tabstop = "-2" }
- assert_equal(2, @format_o.tabstop)
- end
-
- def test_text
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal([], @format_o.text)
- assert_nothing_raised { @format_o.text = "Test Text" }
- assert_equal("Test Text", @format_o.text)
- assert_nothing_raised { @format_o.text = ["Line 1", "Line 2"] }
- assert_equal(["Line 1", "Line 2"], @format_o.text)
- end
-
- def test_s_new
- # new(NilClass) { block }
- assert_nothing_raised do
- @format_o = Text::Format.new {
- self.text = "Test 1, 2, 3"
- }
- end
- assert_equal("Test 1, 2, 3", @format_o.text)
-
- # new(Hash Symbols)
- assert_nothing_raised { @format_o = Text::Format.new(:columns => 72) }
- assert_equal(72, @format_o.columns)
-
- # new(Hash String)
- assert_nothing_raised { @format_o = Text::Format.new('columns' => 72) }
- assert_equal(72, @format_o.columns)
-
- # new(Hash) { block }
- assert_nothing_raised do
- @format_o = Text::Format.new('columns' => 80) {
- self.text = "Test 4, 5, 6"
- }
- end
- assert_equal("Test 4, 5, 6", @format_o.text)
- assert_equal(80, @format_o.columns)
-
- # new(Text::Format)
- assert_nothing_raised do
- fo = Text::Format.new(@format_o)
- assert(fo == @format_o)
- end
-
- # new(Text::Format) { block }
- assert_nothing_raised do
- fo = Text::Format.new(@format_o) { self.columns = 79 }
- assert(fo != @format_o)
- end
-
- # new(String)
- assert_nothing_raised { @format_o = Text::Format.new("Test A, B, C") }
- assert_equal("Test A, B, C", @format_o.text)
-
- # new(String) { block }
- assert_nothing_raised do
- @format_o = Text::Format.new("Test X, Y, Z") { self.columns = -5 }
- end
- assert_equal("Test X, Y, Z", @format_o.text)
- assert_equal(5, @format_o.columns)
- end
-
- def test_center
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_nothing_raised do
- ct = @format_o.center(GETTYSBURG.split("\n")).split("\n")
- assert_match(/^ Four score and seven years ago our fathers brought forth on this/, ct[0])
- assert_match(/^ not perish from the earth./, ct[-3])
- end
- end
-
- def test_expand
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal(" ", @format_o.expand("\t "))
- assert_nothing_raised { @format_o.tabstop = 4 }
- assert_equal(" ", @format_o.expand("\t "))
- end
-
- def test_unexpand
- assert_nothing_raised { @format_o = Text::Format.new }
- assert_equal("\t ", @format_o.unexpand(" "))
- assert_nothing_raised { @format_o.tabstop = 4 }
- assert_equal("\t ", @format_o.unexpand(" "))
- end
-
- def test_space_only
- assert_equal("", Text::Format.new.format(" "))
- assert_equal("", Text::Format.new.format("\n"))
- assert_equal("", Text::Format.new.format(" "))
- assert_equal("", Text::Format.new.format(" \n"))
- assert_equal("", Text::Format.new.paragraphs("\n"))
- assert_equal("", Text::Format.new.paragraphs(" "))
- assert_equal("", Text::Format.new.paragraphs(" "))
- assert_equal("", Text::Format.new.paragraphs(" \n"))
- assert_equal("", Text::Format.new.paragraphs(["\n"]))
- assert_equal("", Text::Format.new.paragraphs([" "]))
- assert_equal("", Text::Format.new.paragraphs([" "]))
- assert_equal("", Text::Format.new.paragraphs([" \n"]))
- end
-
- def test_splendiferous
- h = nil
- test = "This is a splendiferous test"
- assert_nothing_raised { @format_o = Text::Format.new(:columns => 6, :left_margin => 0, :indent => 0, :first_indent => 0) }
- assert_match(/^splendiferous$/, @format_o.format(test))
- assert_nothing_raised { @format_o.hard_margins = true }
- assert_match(/^lendif$/, @format_o.format(test))
- assert_nothing_raised { h = Object.new }
- assert_nothing_raised do
- @format_o.split_rules = Text::Format::SPLIT_HYPHENATION
- class << h #:nodoc:
- def hyphenate_to(word, size)
- return ["", word] if size < 2
- [word[0 ... size], word[size .. -1]]
- end
- end
- @format_o.hyphenator = h
- end
- assert_match(/^iferou$/, @format_o.format(test))
- assert_nothing_raised { h = Object.new }
- assert_nothing_raised do
- class << h #:nodoc:
- def hyphenate_to(word, size, formatter)
- return ["", word] if word.size < formatter.columns
- [word[0 ... size], word[size .. -1]]
- end
- end
- @format_o.hyphenator = h
- end
- assert_match(/^ferous$/, @format_o.format(test))
- end
- end
-end
+#--
+# Text::Format for Ruby
+# Version 0.63
+#
+# Copyright (c) 2002 - 2003 Austin Ziegler
+#
+# $Id: format.rb,v 1.1.1.1 2004/10/14 11:59:57 webster132 Exp $
+#
+# ==========================================================================
+# Revision History ::
+# YYYY.MM.DD Change ID Developer
+# Description
+# --------------------------------------------------------------------------
+# 2002.10.18 Austin Ziegler
+# Fixed a minor problem with tabs not being counted. Changed
+# abbreviations from Hash to Array to better suit Ruby's
+# capabilities. Fixed problems with the way that Array arguments
+# are handled in calls to the major object types, excepting in
+# Text::Format#expand and Text::Format#unexpand (these will
+# probably need to be fixed).
+# 2002.10.30 Austin Ziegler
+# Fixed the ordering of the <=> for binary tests. Fixed
+# Text::Format#expand and Text::Format#unexpand to handle array
+# arguments better.
+# 2003.01.24 Austin Ziegler
+# Fixed a problem with Text::Format::RIGHT_FILL handling where a
+# single word is larger than #columns. Removed Comparable
+# capabilities (<=> doesn't make sense; == does). Added Symbol
+# equivalents for the Hash initialization. Hash initialization has
+# been modified so that values are set as follows (Symbols are
+# highest priority; strings are middle; defaults are lowest):
+# @columns = arg[:columns] || arg['columns'] || @columns
+# Added #hard_margins, #split_rules, #hyphenator, and #split_words.
+# 2003.02.07 Austin Ziegler
+# Fixed the installer for proper case-sensitive handling.
+# 2003.03.28 Austin Ziegler
+# Added the ability for a hyphenator to receive the formatter
+# object. Fixed a bug for strings matching /\A\s*\Z/ failing
+# entirely. Fixed a test case failing under 1.6.8.
+# 2003.04.04 Austin Ziegler
+# Handle the case of hyphenators returning nil for first/rest.
+# 2003.09.17 Austin Ziegler
+# Fixed a problem where #paragraphs(" ") was raising
+# NoMethodError.
+#
+# ==========================================================================
+#++
+
+module Text #:nodoc:
+ # Text::Format for Ruby is copyright 2002 - 2005 by Austin Ziegler. It
+ # is available under Ruby's licence, the Perl Artistic licence, or the
+ # GNU GPL version 2 (or at your option, any later version). As a
+ # special exception, for use with official Rails (provided by the
+ # rubyonrails.org development team) and any project created with
+ # official Rails, the following alternative MIT-style licence may be
+ # used:
+ #
+ # == Text::Format Licence for Rails and Rails Applications
+ # 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 names of its contributors may not be used to endorse or
+ # promote products derived from this software without specific prior
+ # written permission.
+ #
+ # 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.
+ class Format
+ VERSION = '0.63'
+
+ # Local abbreviations. More can be added with Text::Format.abbreviations
+ ABBREV = [ 'Mr', 'Mrs', 'Ms', 'Jr', 'Sr' ]
+
+ # Formatting values
+ LEFT_ALIGN = 0
+ RIGHT_ALIGN = 1
+ RIGHT_FILL = 2
+ JUSTIFY = 3
+
+ # Word split modes (only applies when #hard_margins is true).
+ SPLIT_FIXED = 1
+ SPLIT_CONTINUATION = 2
+ SPLIT_HYPHENATION = 4
+ SPLIT_CONTINUATION_FIXED = SPLIT_CONTINUATION | SPLIT_FIXED
+ SPLIT_HYPHENATION_FIXED = SPLIT_HYPHENATION | SPLIT_FIXED
+ SPLIT_HYPHENATION_CONTINUATION = SPLIT_HYPHENATION | SPLIT_CONTINUATION
+ SPLIT_ALL = SPLIT_HYPHENATION | SPLIT_CONTINUATION | SPLIT_FIXED
+
+ # Words forcibly split by Text::Format will be stored as split words.
+ # This class represents a word forcibly split.
+ class SplitWord
+ # The word that was split.
+ attr_reader :word
+ # The first part of the word that was split.
+ attr_reader :first
+ # The remainder of the word that was split.
+ attr_reader :rest
+
+ def initialize(word, first, rest) #:nodoc:
+ @word = word
+ @first = first
+ @rest = rest
+ end
+ end
+
+ private
+ LEQ_RE = /[.?!]['"]?$/
+
+ def brk_re(i) #:nodoc:
+ %r/((?:\S+\s+){#{i}})(.+)/
+ end
+
+ def posint(p) #:nodoc:
+ p.to_i.abs
+ end
+
+ public
+ # Compares two Text::Format objects. All settings of the objects are
+ # compared *except* #hyphenator. Generated results (e.g., #split_words)
+ # are not compared, either.
+ def ==(o)
+ (@text == o.text) &&
+ (@columns == o.columns) &&
+ (@left_margin == o.left_margin) &&
+ (@right_margin == o.right_margin) &&
+ (@hard_margins == o.hard_margins) &&
+ (@split_rules == o.split_rules) &&
+ (@first_indent == o.first_indent) &&
+ (@body_indent == o.body_indent) &&
+ (@tag_text == o.tag_text) &&
+ (@tabstop == o.tabstop) &&
+ (@format_style == o.format_style) &&
+ (@extra_space == o.extra_space) &&
+ (@tag_paragraph == o.tag_paragraph) &&
+ (@nobreak == o.nobreak) &&
+ (@abbreviations == o.abbreviations) &&
+ (@nobreak_regex == o.nobreak_regex)
+ end
+
+ # The text to be manipulated. Note that value is optional, but if the
+ # formatting functions are called without values, this text is what will
+ # be formatted.
+ #
+ # *Default*:: <tt>[]</tt>
+ # <b>Used in</b>:: All methods
+ attr_accessor :text
+
+ # The total width of the format area. The margins, indentation, and text
+ # are formatted into this space.
+ #
+ # COLUMNS
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>72</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ attr_reader :columns
+
+ # The total width of the format area. The margins, indentation, and text
+ # are formatted into this space. The value provided is silently
+ # converted to a positive integer.
+ #
+ # COLUMNS
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>72</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ def columns=(c)
+ @columns = posint(c)
+ end
+
+ # The number of spaces used for the left margin.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # LEFT MARGIN indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ attr_reader :left_margin
+
+ # The number of spaces used for the left margin. The value provided is
+ # silently converted to a positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # LEFT MARGIN indent text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ def left_margin=(left)
+ @left_margin = posint(left)
+ end
+
+ # The number of spaces used for the right margin.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here RIGHT MARGIN
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ attr_reader :right_margin
+
+ # The number of spaces used for the right margin. The value provided is
+ # silently converted to a positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin indent text is formatted into here RIGHT MARGIN
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
+ # <tt>#center</tt>
+ def right_margin=(r)
+ @right_margin = posint(r)
+ end
+
+ # The number of spaces to indent the first line of a paragraph.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>4</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :first_indent
+
+ # The number of spaces to indent the first line of a paragraph. The
+ # value provided is silently converted to a positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>4</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def first_indent=(f)
+ @first_indent = posint(f)
+ end
+
+ # The number of spaces to indent all lines after the first line of a
+ # paragraph.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :body_indent
+
+ # The number of spaces to indent all lines after the first line of
+ # a paragraph. The value provided is silently converted to a
+ # positive integer value.
+ #
+ # columns
+ # <-------------------------------------------------------------->
+ # <-----------><------><---------------------------><------------>
+ # left margin INDENT text is formatted into here right margin
+ #
+ # *Default*:: <tt>0</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def body_indent=(b)
+ @body_indent = posint(b)
+ end
+
+ # Normally, words larger than the format area will be placed on a line
+ # by themselves. Setting this to +true+ will force words larger than the
+ # format area to be split into one or more "words" each at most the size
+ # of the format area. The first line and the original word will be
+ # placed into <tt>#split_words</tt>. Note that this will cause the
+ # output to look *similar* to a #format_style of JUSTIFY. (Lines will be
+ # filled as much as possible.)
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :hard_margins
+
+ # An array of words split during formatting if #hard_margins is set to
+ # +true+.
+ # #split_words << Text::Format::SplitWord.new(word, first, rest)
+ attr_reader :split_words
+
+ # The object responsible for hyphenating. It must respond to
+ # #hyphenate_to(word, size) or #hyphenate_to(word, size, formatter) and
+ # return an array of the word split into two parts; if there is a
+ # hyphenation mark to be applied, responsibility belongs to the
+ # hyphenator object. The size is the MAXIMUM size permitted, including
+ # any hyphenation marks. If the #hyphenate_to method has an arity of 3,
+ # the formatter will be provided to the method. This allows the
+ # hyphenator to make decisions about the hyphenation based on the
+ # formatting rules.
+ #
+ # *Default*:: +nil+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :hyphenator
+
+ # The object responsible for hyphenating. It must respond to
+ # #hyphenate_to(word, size) and return an array of the word hyphenated
+ # into two parts. The size is the MAXIMUM size permitted, including any
+ # hyphenation marks.
+ #
+ # *Default*:: +nil+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def hyphenator=(h)
+ raise ArgumentError, "#{h.inspect} is not a valid hyphenator." unless h.respond_to?(:hyphenate_to)
+ arity = h.method(:hyphenate_to).arity
+ raise ArgumentError, "#{h.inspect} must have exactly two or three arguments." unless [2, 3].include?(arity)
+ @hyphenator = h
+ @hyphenator_arity = arity
+ end
+
+ # Specifies the split mode; used only when #hard_margins is set to
+ # +true+. Allowable values are:
+ # [+SPLIT_FIXED+] The word will be split at the number of
+ # characters needed, with no marking at all.
+ # repre
+ # senta
+ # ion
+ # [+SPLIT_CONTINUATION+] The word will be split at the number of
+ # characters needed, with a C-style continuation
+ # character. If a word is the only item on a
+ # line and it cannot be split into an
+ # appropriate size, SPLIT_FIXED will be used.
+ # repr\
+ # esen\
+ # tati\
+ # on
+ # [+SPLIT_HYPHENATION+] The word will be split according to the
+ # hyphenator specified in #hyphenator. If there
+ # is no #hyphenator specified, works like
+ # SPLIT_CONTINUATION. The example is using
+ # TeX::Hyphen. If a word is the only item on a
+ # line and it cannot be split into an
+ # appropriate size, SPLIT_CONTINUATION mode will
+ # be used.
+ # rep-
+ # re-
+ # sen-
+ # ta-
+ # tion
+ #
+ # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :split_rules
+
+ # Specifies the split mode; used only when #hard_margins is set to
+ # +true+. Allowable values are:
+ # [+SPLIT_FIXED+] The word will be split at the number of
+ # characters needed, with no marking at all.
+ # repre
+ # senta
+ # ion
+ # [+SPLIT_CONTINUATION+] The word will be split at the number of
+ # characters needed, with a C-style continuation
+ # character.
+ # repr\
+ # esen\
+ # tati\
+ # on
+ # [+SPLIT_HYPHENATION+] The word will be split according to the
+ # hyphenator specified in #hyphenator. If there
+ # is no #hyphenator specified, works like
+ # SPLIT_CONTINUATION. The example is using
+ # TeX::Hyphen as the #hyphenator.
+ # rep-
+ # re-
+ # sen-
+ # ta-
+ # tion
+ #
+ # These values can be bitwise ORed together (e.g., <tt>SPLIT_FIXED |
+ # SPLIT_CONTINUATION</tt>) to provide fallback split methods. In the
+ # example given, an attempt will be made to split the word using the
+ # rules of SPLIT_CONTINUATION; if there is not enough room, the word
+ # will be split with the rules of SPLIT_FIXED. These combinations are
+ # also available as the following values:
+ # * +SPLIT_CONTINUATION_FIXED+
+ # * +SPLIT_HYPHENATION_FIXED+
+ # * +SPLIT_HYPHENATION_CONTINUATION+
+ # * +SPLIT_ALL+
+ #
+ # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def split_rules=(s)
+ raise ArgumentError, "Invalid value provided for split_rules." if ((s < SPLIT_FIXED) || (s > SPLIT_ALL))
+ @split_rules = s
+ end
+
+ # Indicates whether sentence terminators should be followed by a single
+ # space (+false+), or two spaces (+true+).
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :extra_space
+
+ # Defines the current abbreviations as an array. This is only used if
+ # extra_space is turned on.
+ #
+ # If one is abbreviating "President" as "Pres." (abbreviations =
+ # ["Pres"]), then the results of formatting will be as illustrated in
+ # the table below:
+ #
+ # extra_space | include? | !include?
+ # true | Pres. Lincoln | Pres. Lincoln
+ # false | Pres. Lincoln | Pres. Lincoln
+ #
+ # *Default*:: <tt>{}</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :abbreviations
+
+ # Indicates whether the formatting of paragraphs should be done with
+ # tagged paragraphs. Useful only with <tt>#tag_text</tt>.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :tag_paragraph
+
+ # The array of text to be placed before each paragraph when
+ # <tt>#tag_paragraph</tt> is +true+. When <tt>#format()</tt> is called,
+ # only the first element of the array is used. When <tt>#paragraphs</tt>
+ # is called, then each entry in the array will be used once, with
+ # corresponding paragraphs. If the tag elements are exhausted before the
+ # text is exhausted, then the remaining paragraphs will not be tagged.
+ # Regardless of indentation settings, a blank line will be inserted
+ # between all paragraphs when <tt>#tag_paragraph</tt> is +true+.
+ #
+ # *Default*:: <tt>[]</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :tag_text
+
+ # Indicates whether or not the non-breaking space feature should be
+ # used.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :nobreak
+
+ # A hash which holds the regular expressions on which spaces should not
+ # be broken. The hash is set up such that the key is the first word and
+ # the value is the second word.
+ #
+ # For example, if +nobreak_regex+ contains the following hash:
+ #
+ # { '^Mrs?\.$' => '\S+$', '^\S+$' => '^(?:S|J)r\.$'}
+ #
+ # Then "Mr. Jones", "Mrs. Jones", and "Jones Jr." would not be broken.
+ # If this simple matching algorithm indicates that there should not be a
+ # break at the current end of line, then a backtrack is done until there
+ # are two words on which line breaking is permitted. If two such words
+ # are not found, then the end of the line will be broken *regardless*.
+ # If there is a single word on the current line, then no backtrack is
+ # done and the word is stuck on the end.
+ #
+ # *Default*:: <tt>{}</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_accessor :nobreak_regex
+
+ # Indicates the number of spaces that a single tab represents.
+ #
+ # *Default*:: <tt>8</tt>
+ # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
+ # <tt>#paragraphs</tt>
+ attr_reader :tabstop
+
+ # Indicates the number of spaces that a single tab represents.
+ #
+ # *Default*:: <tt>8</tt>
+ # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
+ # <tt>#paragraphs</tt>
+ def tabstop=(t)
+ @tabstop = posint(t)
+ end
+
+ # Specifies the format style. Allowable values are:
+ # [+LEFT_ALIGN+] Left justified, ragged right.
+ # |A paragraph that is|
+ # |left aligned.|
+ # [+RIGHT_ALIGN+] Right justified, ragged left.
+ # |A paragraph that is|
+ # | right aligned.|
+ # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
+ # spaces. (Essentially the same as +LEFT_ALIGN+ except
+ # that lines are padded on the right.)
+ # |A paragraph that is|
+ # |left aligned. |
+ # [+JUSTIFY+] Fully justified, words filled to width by spaces,
+ # except the last line.
+ # |A paragraph that|
+ # |is justified.|
+ #
+ # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ attr_reader :format_style
+
+ # Specifies the format style. Allowable values are:
+ # [+LEFT_ALIGN+] Left justified, ragged right.
+ # |A paragraph that is|
+ # |left aligned.|
+ # [+RIGHT_ALIGN+] Right justified, ragged left.
+ # |A paragraph that is|
+ # | right aligned.|
+ # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
+ # spaces. (Essentially the same as +LEFT_ALIGN+ except
+ # that lines are padded on the right.)
+ # |A paragraph that is|
+ # |left aligned. |
+ # [+JUSTIFY+] Fully justified, words filled to width by spaces.
+ # |A paragraph that|
+ # |is justified.|
+ #
+ # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def format_style=(fs)
+ raise ArgumentError, "Invalid value provided for format_style." if ((fs < LEFT_ALIGN) || (fs > JUSTIFY))
+ @format_style = fs
+ end
+
+ # Indicates that the format style is left alignment.
+ #
+ # *Default*:: +true+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def left_align?
+ return @format_style == LEFT_ALIGN
+ end
+
+ # Indicates that the format style is right alignment.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def right_align?
+ return @format_style == RIGHT_ALIGN
+ end
+
+ # Indicates that the format style is right fill.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def right_fill?
+ return @format_style == RIGHT_FILL
+ end
+
+ # Indicates that the format style is full justification.
+ #
+ # *Default*:: +false+
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
+ def justify?
+ return @format_style == JUSTIFY
+ end
+
+ # The default implementation of #hyphenate_to implements
+ # SPLIT_CONTINUATION.
+ def hyphenate_to(word, size)
+ [word[0 .. (size - 2)] + "\\", word[(size - 1) .. -1]]
+ end
+
+ private
+ def __do_split_word(word, size) #:nodoc:
+ [word[0 .. (size - 1)], word[size .. -1]]
+ end
+
+ def __format(to_wrap) #:nodoc:
+ words = to_wrap.split(/\s+/).compact
+ words.shift if words[0].nil? or words[0].empty?
+ to_wrap = []
+
+ abbrev = false
+ width = @columns - @first_indent - @left_margin - @right_margin
+ indent_str = ' ' * @first_indent
+ first_line = true
+ line = words.shift
+ abbrev = __is_abbrev(line) unless line.nil? || line.empty?
+
+ while w = words.shift
+ if (w.size + line.size < (width - 1)) ||
+ ((line !~ LEQ_RE || abbrev) && (w.size + line.size < width))
+ line << " " if (line =~ LEQ_RE) && (not abbrev)
+ line << " #{w}"
+ else
+ line, w = __do_break(line, w) if @nobreak
+ line, w = __do_hyphenate(line, w, width) if @hard_margins
+ if w.index(/\s+/)
+ w, *w2 = w.split(/\s+/)
+ words.unshift(w2)
+ words.flatten!
+ end
+ to_wrap << __make_line(line, indent_str, width, w.nil?) unless line.nil?
+ if first_line
+ first_line = false
+ width = @columns - @body_indent - @left_margin - @right_margin
+ indent_str = ' ' * @body_indent
+ end
+ line = w
+ end
+
+ abbrev = __is_abbrev(w) unless w.nil?
+ end
+
+ loop do
+ break if line.nil? or line.empty?
+ line, w = __do_hyphenate(line, w, width) if @hard_margins
+ to_wrap << __make_line(line, indent_str, width, w.nil?)
+ line = w
+ end
+
+ if (@tag_paragraph && (to_wrap.size > 0)) then
+ clr = %r{`(\w+)'}.match([caller(1)].flatten[0])[1]
+ clr = "" if clr.nil?
+
+ if ((not @tag_text[0].nil?) && (@tag_cur.size < 1) &&
+ (clr != "__paragraphs")) then
+ @tag_cur = @tag_text[0]
+ end
+
+ fchar = /(\S)/.match(to_wrap[0])[1]
+ white = to_wrap[0].index(fchar)
+ if ((white - @left_margin - 1) > @tag_cur.size) then
+ white = @tag_cur.size + @left_margin
+ to_wrap[0].gsub!(/^ {#{white}}/, "#{' ' * @left_margin}#{@tag_cur}")
+ else
+ to_wrap.unshift("#{' ' * @left_margin}#{@tag_cur}\n")
+ end
+ end
+ to_wrap.join('')
+ end
+
+ # format lines in text into paragraphs with each element of @wrap a
+ # paragraph; uses Text::Format.format for the formatting
+ def __paragraphs(to_wrap) #:nodoc:
+ if ((@first_indent == @body_indent) || @tag_paragraph) then
+ p_end = "\n"
+ else
+ p_end = ''
+ end
+
+ cnt = 0
+ ret = []
+ to_wrap.each do |tw|
+ @tag_cur = @tag_text[cnt] if @tag_paragraph
+ @tag_cur = '' if @tag_cur.nil?
+ line = __format(tw)
+ ret << "#{line}#{p_end}" if (not line.nil?) && (line.size > 0)
+ cnt += 1
+ end
+
+ ret[-1].chomp! unless ret.empty?
+ ret.join('')
+ end
+
+ # center text using spaces on left side to pad it out empty lines
+ # are preserved
+ def __center(to_center) #:nodoc:
+ tabs = 0
+ width = @columns - @left_margin - @right_margin
+ centered = []
+ to_center.each do |tc|
+ s = tc.strip
+ tabs = s.count("\t")
+ tabs = 0 if tabs.nil?
+ ct = ((width - s.size - (tabs * @tabstop) + tabs) / 2)
+ ct = (width - @left_margin - @right_margin) - ct
+ centered << "#{s.rjust(ct)}\n"
+ end
+ centered.join('')
+ end
+
+ # expand tabs to spaces should be similar to Text::Tabs::expand
+ def __expand(to_expand) #:nodoc:
+ expanded = []
+ to_expand.split("\n").each { |te| expanded << te.gsub(/\t/, ' ' * @tabstop) }
+ expanded.join('')
+ end
+
+ def __unexpand(to_unexpand) #:nodoc:
+ unexpanded = []
+ to_unexpand.split("\n").each { |tu| unexpanded << tu.gsub(/ {#{@tabstop}}/, "\t") }
+ unexpanded.join('')
+ end
+
+ def __is_abbrev(word) #:nodoc:
+ # remove period if there is one.
+ w = word.gsub(/\.$/, '') unless word.nil?
+ return true if (!@extra_space || ABBREV.include?(w) || @abbreviations.include?(w))
+ false
+ end
+
+ def __make_line(line, indent, width, last = false) #:nodoc:
+ lmargin = " " * @left_margin
+ fill = " " * (width - line.size) if right_fill? && (line.size <= width)
+
+ if (justify? && ((not line.nil?) && (not line.empty?)) && line =~ /\S+\s+\S+/ && !last)
+ spaces = width - line.size
+ words = line.split(/(\s+)/)
+ ws = spaces / (words.size / 2)
+ spaces = spaces % (words.size / 2) if ws > 0
+ words.reverse.each do |rw|
+ next if (rw =~ /^\S/)
+ rw.sub!(/^/, " " * ws)
+ next unless (spaces > 0)
+ rw.sub!(/^/, " ")
+ spaces -= 1
+ end
+ line = words.join('')
+ end
+ line = "#{lmargin}#{indent}#{line}#{fill}\n" unless line.nil?
+ if right_align? && (not line.nil?)
+ line.sub(/^/, " " * (@columns - @right_margin - (line.size - 1)))
+ else
+ line
+ end
+ end
+
+ def __do_hyphenate(line, next_line, width) #:nodoc:
+ rline = line.dup rescue line
+ rnext = next_line.dup rescue next_line
+ loop do
+ if rline.size == width
+ break
+ elsif rline.size > width
+ words = rline.strip.split(/\s+/)
+ word = words[-1].dup
+ size = width - rline.size + word.size
+ if (size <= 0)
+ words[-1] = nil
+ rline = words.join(' ').strip
+ rnext = "#{word} #{rnext}".strip
+ next
+ end
+
+ first = rest = nil
+
+ if ((@split_rules & SPLIT_HYPHENATION) != 0)
+ if @hyphenator_arity == 2
+ first, rest = @hyphenator.hyphenate_to(word, size)
+ else
+ first, rest = @hyphenator.hyphenate_to(word, size, self)
+ end
+ end
+
+ if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
+ first, rest = self.hyphenate_to(word, size)
+ end
+
+ if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
+ first.nil? or @split_rules == SPLIT_FIXED
+ first, rest = __do_split_word(word, size)
+ end
+
+ if first.nil?
+ words[-1] = nil
+ rest = word
+ else
+ words[-1] = first
+ @split_words << SplitWord.new(word, first, rest)
+ end
+ rline = words.join(' ').strip
+ rnext = "#{rest} #{rnext}".strip
+ break
+ else
+ break if rnext.nil? or rnext.empty? or rline.nil? or rline.empty?
+ words = rnext.split(/\s+/)
+ word = words.shift
+ size = width - rline.size - 1
+
+ if (size <= 0)
+ rnext = "#{word} #{words.join(' ')}".strip
+ break
+ end
+
+ first = rest = nil
+
+ if ((@split_rules & SPLIT_HYPHENATION) != 0)
+ if @hyphenator_arity == 2
+ first, rest = @hyphenator.hyphenate_to(word, size)
+ else
+ first, rest = @hyphenator.hyphenate_to(word, size, self)
+ end
+ end
+
+ first, rest = self.hyphenate_to(word, size) if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
+
+ first, rest = __do_split_word(word, size) if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
+
+ if (rline.size + (first ? first.size : 0)) < width
+ @split_words << SplitWord.new(word, first, rest)
+ rline = "#{rline} #{first}".strip
+ rnext = "#{rest} #{words.join(' ')}".strip
+ end
+ break
+ end
+ end
+ [rline, rnext]
+ end
+
+ def __do_break(line, next_line) #:nodoc:
+ no_brk = false
+ words = []
+ words = line.split(/\s+/) unless line.nil?
+ last_word = words[-1]
+
+ @nobreak_regex.each { |k, v| no_brk = ((last_word =~ /#{k}/) and (next_line =~ /#{v}/)) }
+
+ if no_brk && words.size > 1
+ i = words.size
+ while i > 0
+ no_brk = false
+ @nobreak_regex.each { |k, v| no_brk = ((words[i + 1] =~ /#{k}/) && (words[i] =~ /#{v}/)) }
+ i -= 1
+ break if not no_brk
+ end
+ if i > 0
+ l = brk_re(i).match(line)
+ line.sub!(brk_re(i), l[1])
+ next_line = "#{l[2]} #{next_line}"
+ line.sub!(/\s+$/, '')
+ end
+ end
+ [line, next_line]
+ end
+
+ def __create(arg = nil, &block) #:nodoc:
+ # Format::Text.new(text-to-wrap)
+ @text = arg unless arg.nil?
+ # Defaults
+ @columns = 72
+ @tabstop = 8
+ @first_indent = 4
+ @body_indent = 0
+ @format_style = LEFT_ALIGN
+ @left_margin = 0
+ @right_margin = 0
+ @extra_space = false
+ @text = Array.new if @text.nil?
+ @tag_paragraph = false
+ @tag_text = Array.new
+ @tag_cur = ""
+ @abbreviations = Array.new
+ @nobreak = false
+ @nobreak_regex = Hash.new
+ @split_words = Array.new
+ @hard_margins = false
+ @split_rules = SPLIT_FIXED
+ @hyphenator = self
+ @hyphenator_arity = self.method(:hyphenate_to).arity
+
+ instance_eval(&block) unless block.nil?
+ end
+
+ public
+ # Formats text into a nice paragraph format. The text is separated
+ # into words and then reassembled a word at a time using the settings
+ # of this Format object. If a word is larger than the number of
+ # columns available for formatting, then that word will appear on the
+ # line by itself.
+ #
+ # If +to_wrap+ is +nil+, then the value of <tt>#text</tt> will be
+ # worked on.
+ def format(to_wrap = nil)
+ to_wrap = @text if to_wrap.nil?
+ if to_wrap.class == Array
+ __format(to_wrap[0])
+ else
+ __format(to_wrap)
+ end
+ end
+
+ # Considers each element of text (provided or internal) as a paragraph.
+ # If <tt>#first_indent</tt> is the same as <tt>#body_indent</tt>, then
+ # paragraphs will be separated by a single empty line in the result;
+ # otherwise, the paragraphs will follow immediately after each other.
+ # Uses <tt>#format</tt> to do the heavy lifting.
+ def paragraphs(to_wrap = nil)
+ to_wrap = @text if to_wrap.nil?
+ __paragraphs([to_wrap].flatten)
+ end
+
+ # Centers the text, preserving empty lines and tabs.
+ def center(to_center = nil)
+ to_center = @text if to_center.nil?
+ __center([to_center].flatten)
+ end
+
+ # Replaces all tab characters in the text with <tt>#tabstop</tt> spaces.
+ def expand(to_expand = nil)
+ to_expand = @text if to_expand.nil?
+ if to_expand.class == Array
+ to_expand.collect { |te| __expand(te) }
+ else
+ __expand(to_expand)
+ end
+ end
+
+ # Replaces all occurrences of <tt>#tabstop</tt> consecutive spaces
+ # with a tab character.
+ def unexpand(to_unexpand = nil)
+ to_unexpand = @text if to_unexpand.nil?
+ if to_unexpand.class == Array
+ to_unexpand.collect { |te| v << __unexpand(te) }
+ else
+ __unexpand(to_unexpand)
+ end
+ end
+
+ # This constructor takes advantage of a technique for Ruby object
+ # construction introduced by Andy Hunt and Dave Thomas (see reference),
+ # where optional values are set using commands in a block.
+ #
+ # Text::Format.new {
+ # columns = 72
+ # left_margin = 0
+ # right_margin = 0
+ # first_indent = 4
+ # body_indent = 0
+ # format_style = Text::Format::LEFT_ALIGN
+ # extra_space = false
+ # abbreviations = {}
+ # tag_paragraph = false
+ # tag_text = []
+ # nobreak = false
+ # nobreak_regex = {}
+ # tabstop = 8
+ # text = nil
+ # }
+ #
+ # As shown above, +arg+ is optional. If +arg+ is specified and is a
+ # +String+, then arg is used as the default value of <tt>#text</tt>.
+ # Alternately, an existing Text::Format object can be used or a Hash can
+ # be used. With all forms, a block can be specified.
+ #
+ # *Reference*:: "Object Construction and Blocks"
+ # <http://www.pragmaticprogrammer.com/ruby/articles/insteval.html>
+ #
+ def initialize(arg = nil, &block)
+ @text = nil
+ case arg
+ when Text::Format
+ __create(arg.text) do
+ @columns = arg.columns
+ @tabstop = arg.tabstop
+ @first_indent = arg.first_indent
+ @body_indent = arg.body_indent
+ @format_style = arg.format_style
+ @left_margin = arg.left_margin
+ @right_margin = arg.right_margin
+ @extra_space = arg.extra_space
+ @tag_paragraph = arg.tag_paragraph
+ @tag_text = arg.tag_text
+ @abbreviations = arg.abbreviations
+ @nobreak = arg.nobreak
+ @nobreak_regex = arg.nobreak_regex
+ @text = arg.text
+ @hard_margins = arg.hard_margins
+ @split_words = arg.split_words
+ @split_rules = arg.split_rules
+ @hyphenator = arg.hyphenator
+ end
+ instance_eval(&block) unless block.nil?
+ when Hash
+ __create do
+ @columns = arg[:columns] || arg['columns'] || @columns
+ @tabstop = arg[:tabstop] || arg['tabstop'] || @tabstop
+ @first_indent = arg[:first_indent] || arg['first_indent'] || @first_indent
+ @body_indent = arg[:body_indent] || arg['body_indent'] || @body_indent
+ @format_style = arg[:format_style] || arg['format_style'] || @format_style
+ @left_margin = arg[:left_margin] || arg['left_margin'] || @left_margin
+ @right_margin = arg[:right_margin] || arg['right_margin'] || @right_margin
+ @extra_space = arg[:extra_space] || arg['extra_space'] || @extra_space
+ @text = arg[:text] || arg['text'] || @text
+ @tag_paragraph = arg[:tag_paragraph] || arg['tag_paragraph'] || @tag_paragraph
+ @tag_text = arg[:tag_text] || arg['tag_text'] || @tag_text
+ @abbreviations = arg[:abbreviations] || arg['abbreviations'] || @abbreviations
+ @nobreak = arg[:nobreak] || arg['nobreak'] || @nobreak
+ @nobreak_regex = arg[:nobreak_regex] || arg['nobreak_regex'] || @nobreak_regex
+ @hard_margins = arg[:hard_margins] || arg['hard_margins'] || @hard_margins
+ @split_rules = arg[:split_rules] || arg['split_rules'] || @split_rules
+ @hyphenator = arg[:hyphenator] || arg['hyphenator'] || @hyphenator
+ end
+ instance_eval(&block) unless block.nil?
+ when String
+ __create(arg, &block)
+ when NilClass
+ __create(&block)
+ else
+ raise TypeError
+ end
+ end
+ end
+end
+
+if __FILE__ == $0
+ require 'test/unit'
+
+ class TestText__Format < Test::Unit::TestCase #:nodoc:
+ attr_accessor :format_o
+
+ GETTYSBURG = <<-'EOS'
+ Four score and seven years ago our fathers brought forth on this
+ continent a new nation, conceived in liberty and dedicated to the
+ proposition that all men are created equal. Now we are engaged in
+ a great civil war, testing whether that nation or any nation so
+ conceived and so dedicated can long endure. We are met on a great
+ battlefield of that war. We have come to dedicate a portion of
+ that field as a final resting-place for those who here gave their
+ lives that that nation might live. It is altogether fitting and
+ proper that we should do this. But in a larger sense, we cannot
+ dedicate, we cannot consecrate, we cannot hallow this ground.
+ The brave men, living and dead who struggled here have consecrated
+ it far above our poor power to add or detract. The world will
+ little note nor long remember what we say here, but it can never
+ forget what they did here. It is for us the living rather to be
+ dedicated here to the unfinished work which they who fought here
+ have thus far so nobly advanced. It is rather for us to be here
+ dedicated to the great task remaining before us--that from these
+ honored dead we take increased devotion to that cause for which
+ they gave the last full measure of devotion--that we here highly
+ resolve that these dead shall not have died in vain, that this
+ nation under God shall have a new birth of freedom, and that
+ government of the people, by the people, for the people shall
+ not perish from the earth.
+
+ -- Pres. Abraham Lincoln, 19 November 1863
+ EOS
+
+ FIVE_COL = "Four \nscore\nand s\neven \nyears\nago o\nur fa\nthers\nbroug\nht fo\nrth o\nn thi\ns con\ntinen\nt a n\new na\ntion,\nconce\nived \nin li\nberty\nand d\nedica\nted t\no the\npropo\nsitio\nn tha\nt all\nmen a\nre cr\neated\nequal\n. Now\nwe ar\ne eng\naged \nin a \ngreat\ncivil\nwar, \ntesti\nng wh\nether\nthat \nnatio\nn or \nany n\nation\nso co\nnceiv\ned an\nd so \ndedic\nated \ncan l\nong e\nndure\n. We \nare m\net on\na gre\nat ba\nttlef\nield \nof th\nat wa\nr. We\nhave \ncome \nto de\ndicat\ne a p\nortio\nn of \nthat \nfield\nas a \nfinal\nresti\nng-pl\nace f\nor th\nose w\nho he\nre ga\nve th\neir l\nives \nthat \nthat \nnatio\nn mig\nht li\nve. I\nt is \naltog\nether\nfitti\nng an\nd pro\nper t\nhat w\ne sho\nuld d\no thi\ns. Bu\nt in \na lar\nger s\nense,\nwe ca\nnnot \ndedic\nate, \nwe ca\nnnot \nconse\ncrate\n, we \ncanno\nt hal\nlow t\nhis g\nround\n. The\nbrave\nmen, \nlivin\ng and\ndead \nwho s\ntrugg\nled h\nere h\nave c\nonsec\nrated\nit fa\nr abo\nve ou\nr poo\nr pow\ner to\nadd o\nr det\nract.\nThe w\norld \nwill \nlittl\ne not\ne nor\nlong \nremem\nber w\nhat w\ne say\nhere,\nbut i\nt can\nnever\nforge\nt wha\nt the\ny did\nhere.\nIt is\nfor u\ns the\nlivin\ng rat\nher t\no be \ndedic\nated \nhere \nto th\ne unf\ninish\ned wo\nrk wh\nich t\nhey w\nho fo\nught \nhere \nhave \nthus \nfar s\no nob\nly ad\nvance\nd. It\nis ra\nther \nfor u\ns to \nbe he\nre de\ndicat\ned to\nthe g\nreat \ntask \nremai\nning \nbefor\ne us-\n-that\nfrom \nthese\nhonor\ned de\nad we\ntake \nincre\nased \ndevot\nion t\no tha\nt cau\nse fo\nr whi\nch th\ney ga\nve th\ne las\nt ful\nl mea\nsure \nof de\nvotio\nn--th\nat we\nhere \nhighl\ny res\nolve \nthat \nthese\ndead \nshall\nnot h\nave d\nied i\nn vai\nn, th\nat th\nis na\ntion \nunder\nGod s\nhall \nhave \na new\nbirth\nof fr\needom\n, and\nthat \ngover\nnment\nof th\ne peo\nple, \nby th\ne peo\nple, \nfor t\nhe pe\nople \nshall\nnot p\nerish\nfrom \nthe e\narth.\n-- Pr\nes. A\nbraha\nm Lin\ncoln,\n19 No\nvembe\nr 186\n3 \n"
+
+ FIVE_CNT = "Four \nscore\nand \nseven\nyears\nago \nour \nfath\\\ners \nbrou\\\nght \nforth\non t\\\nhis \ncont\\\ninent\na new\nnati\\\non, \nconc\\\neived\nin l\\\niber\\\nty a\\\nnd d\\\nedic\\\nated \nto t\\\nhe p\\\nropo\\\nsiti\\\non t\\\nhat \nall \nmen \nare \ncrea\\\nted \nequa\\\nl. N\\\now we\nare \nenga\\\nged \nin a \ngreat\ncivil\nwar, \ntest\\\ning \nwhet\\\nher \nthat \nnati\\\non or\nany \nnati\\\non so\nconc\\\neived\nand \nso d\\\nedic\\\nated \ncan \nlong \nendu\\\nre. \nWe a\\\nre m\\\net on\na gr\\\neat \nbatt\\\nlefi\\\neld \nof t\\\nhat \nwar. \nWe h\\\nave \ncome \nto d\\\nedic\\\nate a\nport\\\nion \nof t\\\nhat \nfield\nas a \nfinal\nrest\\\ning-\\\nplace\nfor \nthose\nwho \nhere \ngave \ntheir\nlives\nthat \nthat \nnati\\\non m\\\night \nlive.\nIt is\nalto\\\ngeth\\\ner f\\\nitti\\\nng a\\\nnd p\\\nroper\nthat \nwe s\\\nhould\ndo t\\\nhis. \nBut \nin a \nlarg\\\ner s\\\nense,\nwe c\\\nannot\ndedi\\\ncate,\nwe c\\\nannot\ncons\\\necra\\\nte, \nwe c\\\nannot\nhall\\\now t\\\nhis \ngrou\\\nnd. \nThe \nbrave\nmen, \nlivi\\\nng a\\\nnd d\\\nead \nwho \nstru\\\nggled\nhere \nhave \ncons\\\necra\\\nted \nit f\\\nar a\\\nbove \nour \npoor \npower\nto a\\\ndd or\ndetr\\\nact. \nThe \nworld\nwill \nlitt\\\nle n\\\note \nnor \nlong \nreme\\\nmber \nwhat \nwe s\\\nay h\\\nere, \nbut \nit c\\\nan n\\\never \nforg\\\net w\\\nhat \nthey \ndid \nhere.\nIt is\nfor \nus t\\\nhe l\\\niving\nrath\\\ner to\nbe d\\\nedic\\\nated \nhere \nto t\\\nhe u\\\nnfin\\\nished\nwork \nwhich\nthey \nwho \nfoug\\\nht h\\\nere \nhave \nthus \nfar \nso n\\\nobly \nadva\\\nnced.\nIt is\nrath\\\ner f\\\nor us\nto be\nhere \ndedi\\\ncated\nto t\\\nhe g\\\nreat \ntask \nrema\\\nining\nbefo\\\nre u\\\ns--t\\\nhat \nfrom \nthese\nhono\\\nred \ndead \nwe t\\\nake \nincr\\\neased\ndevo\\\ntion \nto t\\\nhat \ncause\nfor \nwhich\nthey \ngave \nthe \nlast \nfull \nmeas\\\nure \nof d\\\nevot\\\nion-\\\n-that\nwe h\\\nere \nhigh\\\nly r\\\nesol\\\nve t\\\nhat \nthese\ndead \nshall\nnot \nhave \ndied \nin v\\\nain, \nthat \nthis \nnati\\\non u\\\nnder \nGod \nshall\nhave \na new\nbirth\nof f\\\nreed\\\nom, \nand \nthat \ngove\\\nrnme\\\nnt of\nthe \npeop\\\nle, \nby t\\\nhe p\\\neopl\\\ne, f\\\nor t\\\nhe p\\\neople\nshall\nnot \nperi\\\nsh f\\\nrom \nthe \neart\\\nh. --\nPres.\nAbra\\\nham \nLinc\\\noln, \n19 N\\\novem\\\nber \n1863 \n"
+
+ # Tests both abbreviations and abbreviations=
+ def test_abbreviations
+ abbr = [" Pres. Abraham Lincoln\n", " Pres. Abraham Lincoln\n"]
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal([], @format_o.abbreviations)
+ assert_nothing_raised { @format_o.abbreviations = [ 'foo', 'bar' ] }
+ assert_equal([ 'foo', 'bar' ], @format_o.abbreviations)
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
+ assert_nothing_raised { @format_o.extra_space = true }
+ assert_equal(abbr[1], @format_o.format(abbr[0]))
+ assert_nothing_raised { @format_o.abbreviations = [ "Pres" ] }
+ assert_equal([ "Pres" ], @format_o.abbreviations)
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
+ assert_nothing_raised { @format_o.extra_space = false }
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
+ end
+
+ # Tests both body_indent and body_indent=
+ def test_body_indent
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(0, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = 7 }
+ assert_equal(7, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = -3 }
+ assert_equal(3, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = "9" }
+ assert_equal(9, @format_o.body_indent)
+ assert_nothing_raised { @format_o.body_indent = "-2" }
+ assert_equal(2, @format_o.body_indent)
+ assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[1])
+ end
+
+ # Tests both columns and columns=
+ def test_columns
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(72, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = 7 }
+ assert_equal(7, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = -3 }
+ assert_equal(3, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = "9" }
+ assert_equal(9, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = "-2" }
+ assert_equal(2, @format_o.columns)
+ assert_nothing_raised { @format_o.columns = 40 }
+ assert_equal(40, @format_o.columns)
+ assert_match(/this continent$/,
+ @format_o.format(GETTYSBURG).split("\n")[1])
+ end
+
+ # Tests both extra_space and extra_space=
+ def test_extra_space
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.extra_space)
+ assert_nothing_raised { @format_o.extra_space = true }
+ assert(@format_o.extra_space)
+ # The behaviour of extra_space is tested in test_abbreviations. There
+ # is no need to reproduce it here.
+ end
+
+ # Tests both first_indent and first_indent=
+ def test_first_indent
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(4, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = 7 }
+ assert_equal(7, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = -3 }
+ assert_equal(3, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = "9" }
+ assert_equal(9, @format_o.first_indent)
+ assert_nothing_raised { @format_o.first_indent = "-2" }
+ assert_equal(2, @format_o.first_indent)
+ assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[0])
+ end
+
+ def test_format_style
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(Text::Format::LEFT_ALIGN, @format_o.format_style)
+ assert_match(/^November 1863$/,
+ @format_o.format(GETTYSBURG).split("\n")[-1])
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert_equal(Text::Format::RIGHT_ALIGN, @format_o.format_style)
+ assert_match(/^ +November 1863$/,
+ @format_o.format(GETTYSBURG).split("\n")[-1])
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert_equal(Text::Format::RIGHT_FILL, @format_o.format_style)
+ assert_match(/^November 1863 +$/,
+ @format_o.format(GETTYSBURG).split("\n")[-1])
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
+ assert_equal(Text::Format::JUSTIFY, @format_o.format_style)
+ assert_match(/^of freedom, and that government of the people, by the people, for the$/,
+ @format_o.format(GETTYSBURG).split("\n")[-3])
+ assert_raise(ArgumentError) { @format_o.format_style = 33 }
+ end
+
+ def test_tag_paragraph
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.tag_paragraph)
+ assert_nothing_raised { @format_o.tag_paragraph = true }
+ assert(@format_o.tag_paragraph)
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
+ end
+
+ def test_tag_text
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal([], @format_o.tag_text)
+ assert_equal(@format_o.format(GETTYSBURG),
+ Text::Format.new.format(GETTYSBURG))
+ assert_nothing_raised {
+ @format_o.tag_paragraph = true
+ @format_o.tag_text = ["Gettysburg Address", "---"]
+ }
+ assert_not_equal(@format_o.format(GETTYSBURG),
+ Text::Format.new.format(GETTYSBURG))
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG,
+ GETTYSBURG]),
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG,
+ GETTYSBURG]))
+ end
+
+ def test_justify?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.justify?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(!@format_o.justify?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(!@format_o.justify?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::JUSTIFY
+ }
+ assert(@format_o.justify?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_left_align?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(@format_o.left_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(!@format_o.left_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(!@format_o.left_align?)
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
+ assert(!@format_o.left_align?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_left_margin
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(0, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = -3 }
+ assert_equal(3, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = "9" }
+ assert_equal(9, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = "-2" }
+ assert_equal(2, @format_o.left_margin)
+ assert_nothing_raised { @format_o.left_margin = 7 }
+ assert_equal(7, @format_o.left_margin)
+ assert_nothing_raised {
+ ft = @format_o.format(GETTYSBURG).split("\n")
+ assert_match(/^ {11}Four score/, ft[0])
+ assert_match(/^ {7}November/, ft[-1])
+ }
+ end
+
+ def test_hard_margins
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.hard_margins)
+ assert_nothing_raised {
+ @format_o.hard_margins = true
+ @format_o.columns = 5
+ @format_o.first_indent = 0
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(@format_o.hard_margins)
+ assert_equal(FIVE_COL, @format_o.format(GETTYSBURG))
+ assert_nothing_raised {
+ @format_o.split_rules |= Text::Format::SPLIT_CONTINUATION
+ assert_equal(Text::Format::SPLIT_CONTINUATION_FIXED,
+ @format_o.split_rules)
+ }
+ assert_equal(FIVE_CNT, @format_o.format(GETTYSBURG))
+ end
+
+ # Tests both nobreak and nobreak_regex, since one is only useful
+ # with the other.
+ def test_nobreak
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.nobreak)
+ assert(@format_o.nobreak_regex.empty?)
+ assert_nothing_raised {
+ @format_o.nobreak = true
+ @format_o.nobreak_regex = { '^this$' => '^continent$' }
+ @format_o.columns = 77
+ }
+ assert(@format_o.nobreak)
+ assert_equal({ '^this$' => '^continent$' }, @format_o.nobreak_regex)
+ assert_match(/^this continent/,
+ @format_o.format(GETTYSBURG).split("\n")[1])
+ end
+
+ def test_right_align?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.right_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(@format_o.right_align?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(!@format_o.right_align?)
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
+ assert(!@format_o.right_align?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_right_fill?
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert(!@format_o.right_fill?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
+ }
+ assert(!@format_o.right_fill?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::RIGHT_FILL
+ }
+ assert(@format_o.right_fill?)
+ assert_nothing_raised {
+ @format_o.format_style = Text::Format::JUSTIFY
+ }
+ assert(!@format_o.right_fill?)
+ # The format testing is done in test_format_style
+ end
+
+ def test_right_margin
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(0, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = -3 }
+ assert_equal(3, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = "9" }
+ assert_equal(9, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = "-2" }
+ assert_equal(2, @format_o.right_margin)
+ assert_nothing_raised { @format_o.right_margin = 7 }
+ assert_equal(7, @format_o.right_margin)
+ assert_nothing_raised {
+ ft = @format_o.format(GETTYSBURG).split("\n")
+ assert_match(/^ {4}Four score.*forth on$/, ft[0])
+ assert_match(/^November/, ft[-1])
+ }
+ end
+
+ def test_tabstop
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(8, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = 7 }
+ assert_equal(7, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = -3 }
+ assert_equal(3, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = "9" }
+ assert_equal(9, @format_o.tabstop)
+ assert_nothing_raised { @format_o.tabstop = "-2" }
+ assert_equal(2, @format_o.tabstop)
+ end
+
+ def test_text
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal([], @format_o.text)
+ assert_nothing_raised { @format_o.text = "Test Text" }
+ assert_equal("Test Text", @format_o.text)
+ assert_nothing_raised { @format_o.text = ["Line 1", "Line 2"] }
+ assert_equal(["Line 1", "Line 2"], @format_o.text)
+ end
+
+ def test_s_new
+ # new(NilClass) { block }
+ assert_nothing_raised do
+ @format_o = Text::Format.new {
+ self.text = "Test 1, 2, 3"
+ }
+ end
+ assert_equal("Test 1, 2, 3", @format_o.text)
+
+ # new(Hash Symbols)
+ assert_nothing_raised { @format_o = Text::Format.new(:columns => 72) }
+ assert_equal(72, @format_o.columns)
+
+ # new(Hash String)
+ assert_nothing_raised { @format_o = Text::Format.new('columns' => 72) }
+ assert_equal(72, @format_o.columns)
+
+ # new(Hash) { block }
+ assert_nothing_raised do
+ @format_o = Text::Format.new('columns' => 80) {
+ self.text = "Test 4, 5, 6"
+ }
+ end
+ assert_equal("Test 4, 5, 6", @format_o.text)
+ assert_equal(80, @format_o.columns)
+
+ # new(Text::Format)
+ assert_nothing_raised do
+ fo = Text::Format.new(@format_o)
+ assert(fo == @format_o)
+ end
+
+ # new(Text::Format) { block }
+ assert_nothing_raised do
+ fo = Text::Format.new(@format_o) { self.columns = 79 }
+ assert(fo != @format_o)
+ end
+
+ # new(String)
+ assert_nothing_raised { @format_o = Text::Format.new("Test A, B, C") }
+ assert_equal("Test A, B, C", @format_o.text)
+
+ # new(String) { block }
+ assert_nothing_raised do
+ @format_o = Text::Format.new("Test X, Y, Z") { self.columns = -5 }
+ end
+ assert_equal("Test X, Y, Z", @format_o.text)
+ assert_equal(5, @format_o.columns)
+ end
+
+ def test_center
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_nothing_raised do
+ ct = @format_o.center(GETTYSBURG.split("\n")).split("\n")
+ assert_match(/^ Four score and seven years ago our fathers brought forth on this/, ct[0])
+ assert_match(/^ not perish from the earth./, ct[-3])
+ end
+ end
+
+ def test_expand
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal(" ", @format_o.expand("\t "))
+ assert_nothing_raised { @format_o.tabstop = 4 }
+ assert_equal(" ", @format_o.expand("\t "))
+ end
+
+ def test_unexpand
+ assert_nothing_raised { @format_o = Text::Format.new }
+ assert_equal("\t ", @format_o.unexpand(" "))
+ assert_nothing_raised { @format_o.tabstop = 4 }
+ assert_equal("\t ", @format_o.unexpand(" "))
+ end
+
+ def test_space_only
+ assert_equal("", Text::Format.new.format(" "))
+ assert_equal("", Text::Format.new.format("\n"))
+ assert_equal("", Text::Format.new.format(" "))
+ assert_equal("", Text::Format.new.format(" \n"))
+ assert_equal("", Text::Format.new.paragraphs("\n"))
+ assert_equal("", Text::Format.new.paragraphs(" "))
+ assert_equal("", Text::Format.new.paragraphs(" "))
+ assert_equal("", Text::Format.new.paragraphs(" \n"))
+ assert_equal("", Text::Format.new.paragraphs(["\n"]))
+ assert_equal("", Text::Format.new.paragraphs([" "]))
+ assert_equal("", Text::Format.new.paragraphs([" "]))
+ assert_equal("", Text::Format.new.paragraphs([" \n"]))
+ end
+
+ def test_splendiferous
+ h = nil
+ test = "This is a splendiferous test"
+ assert_nothing_raised { @format_o = Text::Format.new(:columns => 6, :left_margin => 0, :indent => 0, :first_indent => 0) }
+ assert_match(/^splendiferous$/, @format_o.format(test))
+ assert_nothing_raised { @format_o.hard_margins = true }
+ assert_match(/^lendif$/, @format_o.format(test))
+ assert_nothing_raised { h = Object.new }
+ assert_nothing_raised do
+ @format_o.split_rules = Text::Format::SPLIT_HYPHENATION
+ class << h #:nodoc:
+ def hyphenate_to(word, size)
+ return ["", word] if size < 2
+ [word[0 ... size], word[size .. -1]]
+ end
+ end
+ @format_o.hyphenator = h
+ end
+ assert_match(/^iferou$/, @format_o.format(test))
+ assert_nothing_raised { h = Object.new }
+ assert_nothing_raised do
+ class << h #:nodoc:
+ def hyphenate_to(word, size, formatter)
+ return ["", word] if word.size < formatter.columns
+ [word[0 ... size], word[size .. -1]]
+ end
+ end
+ @format_o.hyphenator = h
+ end
+ assert_match(/^ferous$/, @format_o.format(test))
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb
deleted file mode 100644
index 18003659a6..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-require 'tmail/version'
-require 'tmail/mail'
-require 'tmail/mailbox'
-require 'tmail/core_extensions'
-require 'tmail/net'
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb
deleted file mode 100644
index 982ad5b661..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb
+++ /dev/null
@@ -1,426 +0,0 @@
-=begin rdoc
-
-= Address handling class
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-require 'tmail/encode'
-require 'tmail/parser'
-
-
-module TMail
-
- # = Class Address
- #
- # Provides a complete handling library for email addresses. Can parse a string of an
- # address directly or take in preformatted addresses themselves. Allows you to add
- # and remove phrases from the front of the address and provides a compare function for
- # email addresses.
- #
- # == Parsing and Handling a Valid Address:
- #
- # Just pass the email address in as a string to Address.parse:
- #
- # email = TMail::Address.parse('Mikel Lindsaar <mikel@lindsaar.net>)
- # #=> #<TMail::Address mikel@lindsaar.net>
- # email.address
- # #=> "mikel@lindsaar.net"
- # email.local
- # #=> "mikel"
- # email.domain
- # #=> "lindsaar.net"
- # email.name # Aliased as phrase as well
- # #=> "Mikel Lindsaar"
- #
- # == Detecting an Invalid Address
- #
- # If you want to check the syntactical validity of an email address, just pass it to
- # Address.parse and catch any SyntaxError:
- #
- # begin
- # TMail::Mail.parse("mikel 2@@@@@ me .com")
- # rescue TMail::SyntaxError
- # puts("Invalid Email Address Detected")
- # else
- # puts("Address is valid")
- # end
- # #=> "Invalid Email Address Detected"
- class Address
-
- include TextUtils #:nodoc:
-
- # Sometimes you need to parse an address, TMail can do it for you and provide you with
- # a fairly robust method of detecting a valid address.
- #
- # Takes in a string, returns a TMail::Address object.
- #
- # Raises a TMail::SyntaxError on invalid email format
- def Address.parse( str )
- Parser.parse :ADDRESS, special_quote_address(str)
- end
-
- def Address.special_quote_address(str) #:nodoc:
- # Takes a string which is an address and adds quotation marks to special
- # edge case methods that the RACC parser can not handle.
- #
- # Right now just handles two edge cases:
- #
- # Full stop as the last character of the display name:
- # Mikel L. <mikel@me.com>
- # Returns:
- # "Mikel L." <mikel@me.com>
- #
- # Unquoted @ symbol in the display name:
- # mikel@me.com <mikel@me.com>
- # Returns:
- # "mikel@me.com" <mikel@me.com>
- #
- # Any other address not matching these patterns just gets returned as is.
- case
- # This handles the missing "" in an older version of Apple Mail.app
- # around the display name when the display name contains a '@'
- # like 'mikel@me.com <mikel@me.com>'
- # Just quotes it to: '"mikel@me.com" <mikel@me.com>'
- when str =~ /\A([^"].+@.+[^"])\s(<.*?>)\Z/
- return "\"#{$1}\" #{$2}"
- # This handles cases where 'Mikel A. <mikel@me.com>' which is a trailing
- # full stop before the address section. Just quotes it to
- # '"Mikel A. <mikel@me.com>"
- when str =~ /\A(.*?\.)\s(<.*?>)\Z/
- return "\"#{$1}\" #{$2}"
- else
- str
- end
- end
-
- def address_group? #:nodoc:
- false
- end
-
- # Address.new(local, domain)
- #
- # Accepts:
- #
- # * local - Left of the at symbol
- #
- # * domain - Array of the domain split at the periods.
- #
- # For example:
- #
- # Address.new("mikel", ["lindsaar", "net"])
- # #=> "#<TMail::Address mikel@lindsaar.net>"
- def initialize( local, domain )
- if domain
- domain.each do |s|
- raise SyntaxError, 'empty word in domain' if s.empty?
- end
- end
-
- # This is to catch an unquoted "@" symbol in the local part of the
- # address. Handles addresses like <"@"@me.com> and makes sure they
- # stay like <"@"@me.com> (previously were becoming <@@me.com>)
- if local && (local.join == '@' || local.join =~ /\A[^"].*?@.*?[^"]\Z/)
- @local = "\"#{local.join}\""
- else
- @local = local
- end
-
- @domain = domain
- @name = nil
- @routes = []
- end
-
- # Provides the name or 'phrase' of the email address.
- #
- # For Example:
- #
- # email = TMail::Address.parse("Mikel Lindsaar <mikel@lindsaar.net>")
- # email.name
- # #=> "Mikel Lindsaar"
- def name
- @name
- end
-
- # Setter method for the name or phrase of the email
- #
- # For Example:
- #
- # email = TMail::Address.parse("mikel@lindsaar.net")
- # email.name
- # #=> nil
- # email.name = "Mikel Lindsaar"
- # email.to_s
- # #=> "Mikel Lindsaar <mikel@me.com>"
- def name=( str )
- @name = str
- @name = nil if str and str.empty?
- end
-
- #:stopdoc:
- alias phrase name
- alias phrase= name=
- #:startdoc:
-
- # This is still here from RFC 822, and is now obsolete per RFC2822 Section 4.
- #
- # "When interpreting addresses, the route portion SHOULD be ignored."
- #
- # It is still here, so you can access it.
- #
- # Routes return the route portion at the front of the email address, if any.
- #
- # For Example:
- # email = TMail::Address.parse( "<@sa,@another:Mikel@me.com>")
- # => #<TMail::Address Mikel@me.com>
- # email.to_s
- # => "<@sa,@another:Mikel@me.com>"
- # email.routes
- # => ["sa", "another"]
- def routes
- @routes
- end
-
- def inspect #:nodoc:
- "#<#{self.class} #{address()}>"
- end
-
- # Returns the local part of the email address
- #
- # For Example:
- #
- # email = TMail::Address.parse("mikel@lindsaar.net")
- # email.local
- # #=> "mikel"
- def local
- return nil unless @local
- return '""' if @local.size == 1 and @local[0].empty?
- # Check to see if it is an array before trying to map it
- if @local.respond_to?(:map)
- @local.map {|i| quote_atom(i) }.join('.')
- else
- quote_atom(@local)
- end
- end
-
- # Returns the domain part of the email address
- #
- # For Example:
- #
- # email = TMail::Address.parse("mikel@lindsaar.net")
- # email.local
- # #=> "lindsaar.net"
- def domain
- return nil unless @domain
- join_domain(@domain)
- end
-
- # Returns the full specific address itself
- #
- # For Example:
- #
- # email = TMail::Address.parse("mikel@lindsaar.net")
- # email.address
- # #=> "mikel@lindsaar.net"
- def spec
- s = self.local
- d = self.domain
- if s and d
- s + '@' + d
- else
- s
- end
- end
-
- alias address spec
-
- # Provides == function to the email. Only checks the actual address
- # and ignores the name/phrase component
- #
- # For Example
- #
- # addr1 = TMail::Address.parse("My Address <mikel@lindsaar.net>")
- # #=> "#<TMail::Address mikel@lindsaar.net>"
- # addr2 = TMail::Address.parse("Another <mikel@lindsaar.net>")
- # #=> "#<TMail::Address mikel@lindsaar.net>"
- # addr1 == addr2
- # #=> true
- def ==( other )
- other.respond_to? :spec and self.spec == other.spec
- end
-
- alias eql? ==
-
- # Provides a unique hash value for this record against the local and domain
- # parts, ignores the name/phrase value
- #
- # email = TMail::Address.parse("mikel@lindsaar.net")
- # email.hash
- # #=> 18767598
- def hash
- @local.hash ^ @domain.hash
- end
-
- # Duplicates a TMail::Address object returning the duplicate
- #
- # addr1 = TMail::Address.parse("mikel@lindsaar.net")
- # addr2 = addr1.dup
- # addr1.id == addr2.id
- # #=> false
- def dup
- obj = self.class.new(@local.dup, @domain.dup)
- obj.name = @name.dup if @name
- obj.routes.replace @routes
- obj
- end
-
- include StrategyInterface #:nodoc:
-
- def accept( strategy, dummy1 = nil, dummy2 = nil ) #:nodoc:
- unless @local
- strategy.meta '<>' # empty return-path
- return
- end
-
- spec_p = (not @name and @routes.empty?)
- if @name
- strategy.phrase @name
- strategy.space
- end
- tmp = spec_p ? '' : '<'
- unless @routes.empty?
- tmp << @routes.map {|i| '@' + i }.join(',') << ':'
- end
- tmp << self.spec
- tmp << '>' unless spec_p
- strategy.meta tmp
- strategy.lwsp ''
- end
-
- end
-
-
- class AddressGroup
-
- include Enumerable
-
- def address_group?
- true
- end
-
- def initialize( name, addrs )
- @name = name
- @addresses = addrs
- end
-
- attr_reader :name
-
- def ==( other )
- other.respond_to? :to_a and @addresses == other.to_a
- end
-
- alias eql? ==
-
- def hash
- map {|i| i.hash }.hash
- end
-
- def []( idx )
- @addresses[idx]
- end
-
- def size
- @addresses.size
- end
-
- def empty?
- @addresses.empty?
- end
-
- def each( &block )
- @addresses.each(&block)
- end
-
- def to_a
- @addresses.dup
- end
-
- alias to_ary to_a
-
- def include?( a )
- @addresses.include? a
- end
-
- def flatten
- set = []
- @addresses.each do |a|
- if a.respond_to? :flatten
- set.concat a.flatten
- else
- set.push a
- end
- end
- set
- end
-
- def each_address( &block )
- flatten.each(&block)
- end
-
- def add( a )
- @addresses.push a
- end
-
- alias push add
-
- def delete( a )
- @addresses.delete a
- end
-
- include StrategyInterface
-
- def accept( strategy, dummy1 = nil, dummy2 = nil )
- strategy.phrase @name
- strategy.meta ':'
- strategy.space
- first = true
- each do |mbox|
- if first
- first = false
- else
- strategy.meta ','
- end
- strategy.space
- mbox.accept strategy
- end
- strategy.meta ';'
- strategy.lwsp ''
- end
-
- end
-
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb
deleted file mode 100644
index 5dc5efae5e..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-=begin rdoc
-
-= Attachment handling file
-
-=end
-
-require 'stringio'
-
-module TMail
- class Attachment < StringIO
- attr_accessor :original_filename, :content_type
- end
-
- class Mail
- def has_attachments?
- multipart? && parts.any? { |part| attachment?(part) }
- end
-
- def attachment?(part)
- part.disposition_is_attachment? || part.content_type_is_text?
- end
-
- def attachments
- if multipart?
- parts.collect { |part|
- if part.multipart?
- part.attachments
- elsif attachment?(part)
- content = part.body # unquoted automatically by TMail#body
- file_name = (part['content-location'] &&
- part['content-location'].body) ||
- part.sub_header("content-type", "name") ||
- part.sub_header("content-disposition", "filename")
-
- next if file_name.blank? || content.blank?
-
- attachment = Attachment.new(content)
- attachment.original_filename = file_name.strip
- attachment.content_type = part.content_type
- attachment
- end
- }.flatten.compact
- end
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb
deleted file mode 100644
index e294c62960..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-#:stopdoc:
-module TMail
- module Base64
-
- module_function
-
- def folding_encode( str, eol = "\n", limit = 60 )
- [str].pack('m')
- end
-
- def encode( str )
- [str].pack('m').tr( "\r\n", '' )
- end
-
- def decode( str, strict = false )
- str.unpack('m').first
- end
-
- end
-end
-#:startdoc:
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb
deleted file mode 100644
index 1275df79a6..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-#:stopdoc:
-unless Enumerable.method_defined?(:map)
- module Enumerable #:nodoc:
- alias map collect
- end
-end
-
-unless Enumerable.method_defined?(:select)
- module Enumerable #:nodoc:
- alias select find_all
- end
-end
-
-unless Enumerable.method_defined?(:reject)
- module Enumerable #:nodoc:
- def reject
- result = []
- each do |i|
- result.push i unless yield(i)
- end
- result
- end
- end
-end
-
-unless Enumerable.method_defined?(:sort_by)
- module Enumerable #:nodoc:
- def sort_by
- map {|i| [yield(i), i] }.sort.map {|val, i| i }
- end
- end
-end
-
-unless File.respond_to?(:read)
- def File.read(fname) #:nodoc:
- File.open(fname) {|f|
- return f.read
- }
- end
-end
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb
deleted file mode 100644
index 3a876dcdbd..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-#:stopdoc:
-module TMail
-
- class Config
-
- def initialize( strict )
- @strict_parse = strict
- @strict_base64decode = strict
- end
-
- def strict_parse?
- @strict_parse
- end
-
- attr_writer :strict_parse
-
- def strict_base64decode?
- @strict_base64decode
- end
-
- attr_writer :strict_base64decode
-
- def new_body_port( mail )
- StringPort.new
- end
-
- alias new_preamble_port new_body_port
- alias new_part_port new_body_port
-
- end
-
- DEFAULT_CONFIG = Config.new(false)
- DEFAULT_STRICT_CONFIG = Config.new(true)
-
- def Config.to_config( arg )
- return DEFAULT_STRICT_CONFIG if arg == true
- return DEFAULT_CONFIG if arg == false
- arg or DEFAULT_CONFIG
- end
-
-end
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb
deleted file mode 100644
index da62c33bbf..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb
+++ /dev/null
@@ -1,63 +0,0 @@
-#:stopdoc:
-unless Object.respond_to?(:blank?)
- class Object
- # Check first to see if we are in a Rails environment, no need to
- # define these methods if we are
-
- # An object is blank if it's nil, empty, or a whitespace string.
- # For example, "", " ", nil, [], and {} are blank.
- #
- # This simplifies
- # if !address.nil? && !address.empty?
- # to
- # if !address.blank?
- def blank?
- if respond_to?(:empty?) && respond_to?(:strip)
- empty? or strip.empty?
- elsif respond_to?(:empty?)
- empty?
- else
- !self
- end
- end
- end
-
- class NilClass
- def blank?
- true
- end
- end
-
- class FalseClass
- def blank?
- true
- end
- end
-
- class TrueClass
- def blank?
- false
- end
- end
-
- class Array
- alias_method :blank?, :empty?
- end
-
- class Hash
- alias_method :blank?, :empty?
- end
-
- class String
- def blank?
- empty? || strip.empty?
- end
- end
-
- class Numeric
- def blank?
- false
- end
- end
-end
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb
deleted file mode 100644
index 458dbbfe6a..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb
+++ /dev/null
@@ -1,581 +0,0 @@
-#--
-# = COPYRIGHT:
-#
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-#:stopdoc:
-require 'nkf'
-require 'tmail/base64'
-require 'tmail/stringio'
-require 'tmail/utils'
-#:startdoc:
-
-
-module TMail
-
- #:stopdoc:
- class << self
- attr_accessor :KCODE
- end
- self.KCODE = 'NONE'
-
- module StrategyInterface
-
- def create_dest( obj )
- case obj
- when nil
- StringOutput.new
- when String
- StringOutput.new(obj)
- when IO, StringOutput
- obj
- else
- raise TypeError, 'cannot handle this type of object for dest'
- end
- end
- module_function :create_dest
-
- #:startdoc:
- # Returns the TMail object encoded and ready to be sent via SMTP etc.
- # You should call this before you are packaging up your email to
- # correctly escape all the values that need escaping in the email, line
- # wrap the email etc.
- #
- # It is also a good idea to call this before you marshal or serialize
- # a TMail object.
- #
- # For Example:
- #
- # email = TMail::Load(my_email_file)
- # email_to_send = email.encoded
- def encoded( eol = "\r\n", charset = 'j', dest = nil )
- accept_strategy Encoder, eol, charset, dest
- end
-
- # Returns the TMail object decoded and ready to be used by you, your
- # program etc.
- #
- # You should call this before you are packaging up your email to
- # correctly escape all the values that need escaping in the email, line
- # wrap the email etc.
- #
- # For Example:
- #
- # email = TMail::Load(my_email_file)
- # email_to_send = email.encoded
- def decoded( eol = "\n", charset = 'e', dest = nil )
- # Turn the E-Mail into a string and return it with all
- # encoded characters decoded. alias for to_s
- accept_strategy Decoder, eol, charset, dest
- end
-
- alias to_s decoded
-
- def accept_strategy( klass, eol, charset, dest = nil ) #:nodoc:
- dest ||= ''
- accept klass.new( create_dest(dest), charset, eol )
- dest
- end
-
- end
-
- #:stopdoc:
-
- ###
- ### MIME B encoding decoder
- ###
-
- class Decoder
-
- include TextUtils
-
- encoded = '=\?(?:iso-2022-jp|euc-jp|shift_jis)\?[QB]\?[a-z0-9+/=]+\?='
- ENCODED_WORDS = /#{encoded}(?:\s+#{encoded})*/i
-
- OUTPUT_ENCODING = {
- 'EUC' => 'e',
- 'SJIS' => 's',
- }
-
- def self.decode( str, encoding = nil )
- encoding ||= (OUTPUT_ENCODING[TMail.KCODE] || 'j')
- opt = '-mS' + encoding
- str.gsub(ENCODED_WORDS) {|s| NKF.nkf(opt, s) }
- end
-
- def initialize( dest, encoding = nil, eol = "\n" )
- @f = StrategyInterface.create_dest(dest)
- @encoding = (/\A[ejs]/ === encoding) ? encoding[0,1] : nil
- @eol = eol
- end
-
- def decode( str )
- self.class.decode(str, @encoding)
- end
- private :decode
-
- def terminate
- end
-
- def header_line( str )
- @f << decode(str)
- end
-
- def header_name( nm )
- @f << nm << ': '
- end
-
- def header_body( str )
- @f << decode(str)
- end
-
- def space
- @f << ' '
- end
-
- alias spc space
-
- def lwsp( str )
- @f << str
- end
-
- def meta( str )
- @f << str
- end
-
- def text( str )
- @f << decode(str)
- end
-
- def phrase( str )
- @f << quote_phrase(decode(str))
- end
-
- def kv_pair( k, v )
- v = dquote(v) unless token_safe?(v)
- @f << k << '=' << v
- end
-
- def puts( str = nil )
- @f << str if str
- @f << @eol
- end
-
- def write( str )
- @f << str
- end
-
- end
-
-
- ###
- ### MIME B-encoding encoder
- ###
-
- #
- # FIXME: This class can handle only (euc-jp/shift_jis -> iso-2022-jp).
- #
- class Encoder
-
- include TextUtils
-
- BENCODE_DEBUG = false unless defined?(BENCODE_DEBUG)
-
- def Encoder.encode( str )
- e = new()
- e.header_body str
- e.terminate
- e.dest.string
- end
-
- SPACER = "\t"
- MAX_LINE_LEN = 78
- RFC_2822_MAX_LENGTH = 998
-
- OPTIONS = {
- 'EUC' => '-Ej -m0',
- 'SJIS' => '-Sj -m0',
- 'UTF8' => nil, # FIXME
- 'NONE' => nil
- }
-
- def initialize( dest = nil, encoding = nil, eol = "\r\n", limit = nil )
- @f = StrategyInterface.create_dest(dest)
- @opt = OPTIONS[TMail.KCODE]
- @eol = eol
- @folded = false
- @preserve_quotes = true
- reset
- end
-
- def preserve_quotes=( bool )
- @preserve_quotes
- end
-
- def preserve_quotes
- @preserve_quotes
- end
-
- def normalize_encoding( str )
- if @opt
- then NKF.nkf(@opt, str)
- else str
- end
- end
-
- def reset
- @text = ''
- @lwsp = ''
- @curlen = 0
- end
-
- def terminate
- add_lwsp ''
- reset
- end
-
- def dest
- @f
- end
-
- def puts( str = nil )
- @f << str if str
- @f << @eol
- end
-
- def write( str )
- @f << str
- end
-
- #
- # add
- #
-
- def header_line( line )
- scanadd line
- end
-
- def header_name( name )
- add_text name.split(/-/).map {|i| i.capitalize }.join('-')
- add_text ':'
- add_lwsp ' '
- end
-
- def header_body( str )
- scanadd normalize_encoding(str)
- end
-
- def space
- add_lwsp ' '
- end
-
- alias spc space
-
- def lwsp( str )
- add_lwsp str.sub(/[\r\n]+[^\r\n]*\z/, '')
- end
-
- def meta( str )
- add_text str
- end
-
- def text( str )
- scanadd normalize_encoding(str)
- end
-
- def phrase( str )
- str = normalize_encoding(str)
- if CONTROL_CHAR === str
- scanadd str
- else
- add_text quote_phrase(str)
- end
- end
-
- # FIXME: implement line folding
- #
- def kv_pair( k, v )
- return if v.nil?
- v = normalize_encoding(v)
- if token_safe?(v)
- add_text k + '=' + v
- elsif not CONTROL_CHAR === v
- add_text k + '=' + quote_token(v)
- else
- # apply RFC2231 encoding
- kv = k + '*=' + "iso-2022-jp'ja'" + encode_value(v)
- add_text kv
- end
- end
-
- def encode_value( str )
- str.gsub(TOKEN_UNSAFE) {|s| '%%%02x' % s[0] }
- end
-
- private
-
- def scanadd( str, force = false )
- types = ''
- strs = []
- if str.respond_to?(:encoding)
- enc = str.encoding
- str.force_encoding(Encoding::ASCII_8BIT)
- end
- until str.empty?
- if m = /\A[^\e\t\r\n ]+/.match(str)
- types << (force ? 'j' : 'a')
- if str.respond_to?(:encoding)
- strs.push m[0].force_encoding(enc)
- else
- strs.push m[0]
- end
- elsif m = /\A[\t\r\n ]+/.match(str)
- types << 's'
- if str.respond_to?(:encoding)
- strs.push m[0].force_encoding(enc)
- else
- strs.push m[0]
- end
-
- elsif m = /\A\e../.match(str)
- esc = m[0]
- str = m.post_match
- if esc != "\e(B" and m = /\A[^\e]+/.match(str)
- types << 'j'
- if str.respond_to?(:encoding)
- strs.push m[0].force_encoding(enc)
- else
- strs.push m[0]
- end
- end
-
- else
- raise 'TMail FATAL: encoder scan fail'
- end
- (str = m.post_match) unless m.nil?
- end
-
- do_encode types, strs
- end
-
- def do_encode( types, strs )
- #
- # result : (A|E)(S(A|E))*
- # E : W(SW)*
- # W : (J|A)+ but must contain J # (J|A)*J(J|A)*
- # A : <<A character string not to be encoded>>
- # J : <<A character string to be encoded>>
- # S : <<LWSP>>
- #
- # An encoding unit is `E'.
- # Input (parameter `types') is (J|A)(J|A|S)*(J|A)
- #
- if BENCODE_DEBUG
- puts
- puts '-- do_encode ------------'
- puts types.split(//).join(' ')
- p strs
- end
-
- e = /[ja]*j[ja]*(?:s[ja]*j[ja]*)*/
-
- while m = e.match(types)
- pre = m.pre_match
- concat_A_S pre, strs[0, pre.size] unless pre.empty?
- concat_E m[0], strs[m.begin(0) ... m.end(0)]
- types = m.post_match
- strs.slice! 0, m.end(0)
- end
- concat_A_S types, strs
- end
-
- def concat_A_S( types, strs )
- if RUBY_VERSION < '1.9'
- a = ?a; s = ?s
- else
- a = 'a'.ord; s = 's'.ord
- end
- i = 0
- types.each_byte do |t|
- case t
- when a then add_text strs[i]
- when s then add_lwsp strs[i]
- else
- raise "TMail FATAL: unknown flag: #{t.chr}"
- end
- i += 1
- end
- end
-
- METHOD_ID = {
- ?j => :extract_J,
- ?e => :extract_E,
- ?a => :extract_A,
- ?s => :extract_S
- }
-
- def concat_E( types, strs )
- if BENCODE_DEBUG
- puts '---- concat_E'
- puts "types=#{types.split(//).join(' ')}"
- puts "strs =#{strs.inspect}"
- end
-
- flush() unless @text.empty?
-
- chunk = ''
- strs.each_with_index do |s,i|
- mid = METHOD_ID[types[i]]
- until s.empty?
- unless c = __send__(mid, chunk.size, s)
- add_with_encode chunk unless chunk.empty?
- flush
- chunk = ''
- fold
- c = __send__(mid, 0, s)
- raise 'TMail FATAL: extract fail' unless c
- end
- chunk << c
- end
- end
- add_with_encode chunk unless chunk.empty?
- end
-
- def extract_J( chunksize, str )
- size = max_bytes(chunksize, str.size) - 6
- size = (size % 2 == 0) ? (size) : (size - 1)
- return nil if size <= 0
- if str.respond_to?(:encoding)
- enc = str.encoding
- str.force_encoding(Encoding::ASCII_8BIT)
- "\e$B#{str.slice!(0, size)}\e(B".force_encoding(enc)
- else
- "\e$B#{str.slice!(0, size)}\e(B"
- end
- end
-
- def extract_A( chunksize, str )
- size = max_bytes(chunksize, str.size)
- return nil if size <= 0
- str.slice!(0, size)
- end
-
- alias extract_S extract_A
-
- def max_bytes( chunksize, ssize )
- (restsize() - '=?iso-2022-jp?B??='.size) / 4 * 3 - chunksize
- end
-
- #
- # free length buffer
- #
-
- def add_text( str )
- @text << str
- # puts '---- text -------------------------------------'
- # puts "+ #{str.inspect}"
- # puts "txt >>>#{@text.inspect}<<<"
- end
-
- def add_with_encode( str )
- @text << "=?iso-2022-jp?B?#{Base64.encode(str)}?="
- end
-
- def add_lwsp( lwsp )
- # puts '---- lwsp -------------------------------------'
- # puts "+ #{lwsp.inspect}"
- fold if restsize() <= 0
- flush(@folded)
- @lwsp = lwsp
- end
-
- def flush(folded = false)
- # puts '---- flush ----'
- # puts "spc >>>#{@lwsp.inspect}<<<"
- # puts "txt >>>#{@text.inspect}<<<"
- @f << @lwsp << @text
- if folded
- @curlen = 0
- else
- @curlen += (@lwsp.size + @text.size)
- end
- @text = ''
- @lwsp = ''
- end
-
- def fold
- # puts '---- fold ----'
- unless @f.string =~ /^.*?:$/
- @f << @eol
- @lwsp = SPACER
- else
- fold_header
- @folded = true
- end
- @curlen = 0
- end
-
- def fold_header
- # Called because line is too long - so we need to wrap.
- # First look for whitespace in the text
- # if it has text, fold there
- # check the remaining text, if too long, fold again
- # if it doesn't, then don't fold unless the line goes beyond 998 chars
-
- # Check the text to see if there is whitespace, or if not
- @wrapped_text = []
- until @text.blank?
- fold_the_string
- end
- @text = @wrapped_text.join("#{@eol}#{SPACER}")
- end
-
- def fold_the_string
- whitespace_location = @text =~ /\s/ || @text.length
- # Is the location of the whitespace shorter than the RCF_2822_MAX_LENGTH?
- # if there is no whitespace in the string, then this
- unless mazsize(whitespace_location) <= 0
- @text.strip!
- @wrapped_text << @text.slice!(0...whitespace_location)
- # If it is not less, we have to wrap it destructively
- else
- slice_point = RFC_2822_MAX_LENGTH - @curlen - @lwsp.length
- @text.strip!
- @wrapped_text << @text.slice!(0...slice_point)
- end
- end
-
- def restsize
- MAX_LINE_LEN - (@curlen + @lwsp.size + @text.size)
- end
-
- def mazsize(whitespace_location)
- # Per RFC2822, the maximum length of a line is 998 chars
- RFC_2822_MAX_LENGTH - (@curlen + @lwsp.size + whitespace_location)
- end
-
- end
- #:startdoc:
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb
deleted file mode 100644
index dbdefcf979..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb
+++ /dev/null
@@ -1,960 +0,0 @@
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-require 'tmail/encode'
-require 'tmail/address'
-require 'tmail/parser'
-require 'tmail/config'
-require 'tmail/utils'
-
-#:startdoc:
-module TMail
-
- # Provides methods to handle and manipulate headers in the email
- class HeaderField
-
- include TextUtils
-
- class << self
-
- alias newobj new
-
- def new( name, body, conf = DEFAULT_CONFIG )
- klass = FNAME_TO_CLASS[name.downcase] || UnstructuredHeader
- klass.newobj body, conf
- end
-
- # Returns a HeaderField object matching the header you specify in the "name" param.
- # Requires an initialized TMail::Port to be passed in.
- #
- # The method searches the header of the Port you pass into it to find a match on
- # the header line you pass. Once a match is found, it will unwrap the matching line
- # as needed to return an initialized HeaderField object.
- #
- # If you want to get the Envelope sender of the email object, pass in "EnvelopeSender",
- # if you want the From address of the email itself, pass in 'From'.
- #
- # This is because a mailbox doesn't have the : after the From that designates the
- # beginning of the envelope sender (which can be different to the from address of
- # the email)
- #
- # Other fields can be passed as normal, "Reply-To", "Received" etc.
- #
- # Note: Change of behaviour in 1.2.1 => returns nil if it does not find the specified
- # header field, otherwise returns an instantiated object of the correct header class
- #
- # For example:
- # port = TMail::FilePort.new("/test/fixtures/raw_email_simple")
- # h = TMail::HeaderField.new_from_port(port, "From")
- # h.addrs.to_s #=> "Mikel Lindsaar <mikel@nowhere.com>"
- # h = TMail::HeaderField.new_from_port(port, "EvelopeSender")
- # h.addrs.to_s #=> "mike@anotherplace.com.au"
- # h = TMail::HeaderField.new_from_port(port, "SomeWeirdHeaderField")
- # h #=> nil
- def new_from_port( port, name, conf = DEFAULT_CONFIG )
- if name == "EnvelopeSender"
- name = "From"
- re = Regexp.new('\A(From) ', 'i')
- else
- re = Regexp.new('\A(' + Regexp.quote(name) + '):', 'i')
- end
- str = nil
- port.ropen {|f|
- f.each do |line|
- if m = re.match(line) then str = m.post_match.strip
- elsif str and /\A[\t ]/ === line then str << ' ' << line.strip
- elsif /\A-*\s*\z/ === line then break
- elsif str then break
- end
- end
- }
- new(name, str, Config.to_config(conf)) if str
- end
-
- def internal_new( name, conf )
- FNAME_TO_CLASS[name].newobj('', conf, true)
- end
-
- end # class << self
-
- def initialize( body, conf, intern = false )
- @body = body
- @config = conf
-
- @illegal = false
- @parsed = false
-
- if intern
- @parsed = true
- parse_init
- end
- end
-
- def inspect
- "#<#{self.class} #{@body.inspect}>"
- end
-
- def illegal?
- @illegal
- end
-
- def empty?
- ensure_parsed
- return true if @illegal
- isempty?
- end
-
- private
-
- def ensure_parsed
- return if @parsed
- @parsed = true
- parse
- end
-
- # defabstract parse
- # end
-
- def clear_parse_status
- @parsed = false
- @illegal = false
- end
-
- public
-
- def body
- ensure_parsed
- v = Decoder.new(s = '')
- do_accept v
- v.terminate
- s
- end
-
- def body=( str )
- @body = str
- clear_parse_status
- end
-
- include StrategyInterface
-
- def accept( strategy )
- ensure_parsed
- do_accept strategy
- strategy.terminate
- end
-
- # abstract do_accept
-
- end
-
-
- class UnstructuredHeader < HeaderField
-
- def body
- ensure_parsed
- @body
- end
-
- def body=( arg )
- ensure_parsed
- @body = arg
- end
-
- private
-
- def parse_init
- end
-
- def parse
- @body = Decoder.decode(@body.gsub(/\n|\r\n|\r/, ''))
- end
-
- def isempty?
- not @body
- end
-
- def do_accept( strategy )
- strategy.text @body
- end
-
- end
-
-
- class StructuredHeader < HeaderField
-
- def comments
- ensure_parsed
- if @comments[0]
- [Decoder.decode(@comments[0])]
- else
- @comments
- end
- end
-
- private
-
- def parse
- save = nil
-
- begin
- parse_init
- do_parse
- rescue SyntaxError
- if not save and mime_encoded? @body
- save = @body
- @body = Decoder.decode(save)
- retry
- elsif save
- @body = save
- end
-
- @illegal = true
- raise if @config.strict_parse?
- end
- end
-
- def parse_init
- @comments = []
- init
- end
-
- def do_parse
- quote_boundary
- obj = Parser.parse(self.class::PARSE_TYPE, @body, @comments)
- set obj if obj
- end
-
- end
-
-
- class DateTimeHeader < StructuredHeader
-
- PARSE_TYPE = :DATETIME
-
- def date
- ensure_parsed
- @date
- end
-
- def date=( arg )
- ensure_parsed
- @date = arg
- end
-
- private
-
- def init
- @date = nil
- end
-
- def set( t )
- @date = t
- end
-
- def isempty?
- not @date
- end
-
- def do_accept( strategy )
- strategy.meta time2str(@date)
- end
-
- end
-
-
- class AddressHeader < StructuredHeader
-
- PARSE_TYPE = :MADDRESS
-
- def addrs
- ensure_parsed
- @addrs
- end
-
- private
-
- def init
- @addrs = []
- end
-
- def set( a )
- @addrs = a
- end
-
- def isempty?
- @addrs.empty?
- end
-
- def do_accept( strategy )
- first = true
- @addrs.each do |a|
- if first
- first = false
- else
- strategy.meta ','
- strategy.space
- end
- a.accept strategy
- end
-
- @comments.each do |c|
- strategy.space
- strategy.meta '('
- strategy.text c
- strategy.meta ')'
- end
- end
-
- end
-
-
- class ReturnPathHeader < AddressHeader
-
- PARSE_TYPE = :RETPATH
-
- def addr
- addrs()[0]
- end
-
- def spec
- a = addr() or return nil
- a.spec
- end
-
- def routes
- a = addr() or return nil
- a.routes
- end
-
- private
-
- def do_accept( strategy )
- a = addr()
-
- strategy.meta '<'
- unless a.routes.empty?
- strategy.meta a.routes.map {|i| '@' + i }.join(',')
- strategy.meta ':'
- end
- spec = a.spec
- strategy.meta spec if spec
- strategy.meta '>'
- end
-
- end
-
-
- class SingleAddressHeader < AddressHeader
-
- def addr
- addrs()[0]
- end
-
- private
-
- def do_accept( strategy )
- a = addr()
- a.accept strategy
- @comments.each do |c|
- strategy.space
- strategy.meta '('
- strategy.text c
- strategy.meta ')'
- end
- end
-
- end
-
-
- class MessageIdHeader < StructuredHeader
-
- def id
- ensure_parsed
- @id
- end
-
- def id=( arg )
- ensure_parsed
- @id = arg
- end
-
- private
-
- def init
- @id = nil
- end
-
- def isempty?
- not @id
- end
-
- def do_parse
- @id = @body.slice(MESSAGE_ID) or
- raise SyntaxError, "wrong Message-ID format: #{@body}"
- end
-
- def do_accept( strategy )
- strategy.meta @id
- end
-
- end
-
-
- class ReferencesHeader < StructuredHeader
-
- def refs
- ensure_parsed
- @refs
- end
-
- def each_id
- self.refs.each do |i|
- yield i if MESSAGE_ID === i
- end
- end
-
- def ids
- ensure_parsed
- @ids
- end
-
- def each_phrase
- self.refs.each do |i|
- yield i unless MESSAGE_ID === i
- end
- end
-
- def phrases
- ret = []
- each_phrase {|i| ret.push i }
- ret
- end
-
- private
-
- def init
- @refs = []
- @ids = []
- end
-
- def isempty?
- @ids.empty?
- end
-
- def do_parse
- str = @body
- while m = MESSAGE_ID.match(str)
- pre = m.pre_match.strip
- @refs.push pre unless pre.empty?
- @refs.push s = m[0]
- @ids.push s
- str = m.post_match
- end
- str = str.strip
- @refs.push str unless str.empty?
- end
-
- def do_accept( strategy )
- first = true
- @ids.each do |i|
- if first
- first = false
- else
- strategy.space
- end
- strategy.meta i
- end
- end
-
- end
-
-
- class ReceivedHeader < StructuredHeader
-
- PARSE_TYPE = :RECEIVED
-
- def from
- ensure_parsed
- @from
- end
-
- def from=( arg )
- ensure_parsed
- @from = arg
- end
-
- def by
- ensure_parsed
- @by
- end
-
- def by=( arg )
- ensure_parsed
- @by = arg
- end
-
- def via
- ensure_parsed
- @via
- end
-
- def via=( arg )
- ensure_parsed
- @via = arg
- end
-
- def with
- ensure_parsed
- @with
- end
-
- def id
- ensure_parsed
- @id
- end
-
- def id=( arg )
- ensure_parsed
- @id = arg
- end
-
- def _for
- ensure_parsed
- @_for
- end
-
- def _for=( arg )
- ensure_parsed
- @_for = arg
- end
-
- def date
- ensure_parsed
- @date
- end
-
- def date=( arg )
- ensure_parsed
- @date = arg
- end
-
- private
-
- def init
- @from = @by = @via = @with = @id = @_for = nil
- @with = []
- @date = nil
- end
-
- def set( args )
- @from, @by, @via, @with, @id, @_for, @date = *args
- end
-
- def isempty?
- @with.empty? and not (@from or @by or @via or @id or @_for or @date)
- end
-
- def do_accept( strategy )
- list = []
- list.push 'from ' + @from if @from
- list.push 'by ' + @by if @by
- list.push 'via ' + @via if @via
- @with.each do |i|
- list.push 'with ' + i
- end
- list.push 'id ' + @id if @id
- list.push 'for <' + @_for + '>' if @_for
-
- first = true
- list.each do |i|
- strategy.space unless first
- strategy.meta i
- first = false
- end
- if @date
- strategy.meta ';'
- strategy.space
- strategy.meta time2str(@date)
- end
- end
-
- end
-
-
- class KeywordsHeader < StructuredHeader
-
- PARSE_TYPE = :KEYWORDS
-
- def keys
- ensure_parsed
- @keys
- end
-
- private
-
- def init
- @keys = []
- end
-
- def set( a )
- @keys = a
- end
-
- def isempty?
- @keys.empty?
- end
-
- def do_accept( strategy )
- first = true
- @keys.each do |i|
- if first
- first = false
- else
- strategy.meta ','
- end
- strategy.meta i
- end
- end
-
- end
-
-
- class EncryptedHeader < StructuredHeader
-
- PARSE_TYPE = :ENCRYPTED
-
- def encrypter
- ensure_parsed
- @encrypter
- end
-
- def encrypter=( arg )
- ensure_parsed
- @encrypter = arg
- end
-
- def keyword
- ensure_parsed
- @keyword
- end
-
- def keyword=( arg )
- ensure_parsed
- @keyword = arg
- end
-
- private
-
- def init
- @encrypter = nil
- @keyword = nil
- end
-
- def set( args )
- @encrypter, @keyword = args
- end
-
- def isempty?
- not (@encrypter or @keyword)
- end
-
- def do_accept( strategy )
- if @key
- strategy.meta @encrypter + ','
- strategy.space
- strategy.meta @keyword
- else
- strategy.meta @encrypter
- end
- end
-
- end
-
-
- class MimeVersionHeader < StructuredHeader
-
- PARSE_TYPE = :MIMEVERSION
-
- def major
- ensure_parsed
- @major
- end
-
- def major=( arg )
- ensure_parsed
- @major = arg
- end
-
- def minor
- ensure_parsed
- @minor
- end
-
- def minor=( arg )
- ensure_parsed
- @minor = arg
- end
-
- def version
- sprintf('%d.%d', major, minor)
- end
-
- private
-
- def init
- @major = nil
- @minor = nil
- end
-
- def set( args )
- @major, @minor = *args
- end
-
- def isempty?
- not (@major or @minor)
- end
-
- def do_accept( strategy )
- strategy.meta sprintf('%d.%d', @major, @minor)
- end
-
- end
-
-
- class ContentTypeHeader < StructuredHeader
-
- PARSE_TYPE = :CTYPE
-
- def main_type
- ensure_parsed
- @main
- end
-
- def main_type=( arg )
- ensure_parsed
- @main = arg.downcase
- end
-
- def sub_type
- ensure_parsed
- @sub
- end
-
- def sub_type=( arg )
- ensure_parsed
- @sub = arg.downcase
- end
-
- def content_type
- ensure_parsed
- @sub ? sprintf('%s/%s', @main, @sub) : @main
- end
-
- def params
- ensure_parsed
- unless @params.blank?
- @params.each do |k, v|
- @params[k] = unquote(v)
- end
- end
- @params
- end
-
- def []( key )
- ensure_parsed
- @params and unquote(@params[key])
- end
-
- def []=( key, val )
- ensure_parsed
- (@params ||= {})[key] = val
- end
-
- private
-
- def init
- @main = @sub = @params = nil
- end
-
- def set( args )
- @main, @sub, @params = *args
- end
-
- def isempty?
- not (@main or @sub)
- end
-
- def do_accept( strategy )
- if @sub
- strategy.meta sprintf('%s/%s', @main, @sub)
- else
- strategy.meta @main
- end
- @params.each do |k,v|
- if v
- strategy.meta ';'
- strategy.space
- strategy.kv_pair k, v
- end
- end
- end
-
- end
-
-
- class ContentTransferEncodingHeader < StructuredHeader
-
- PARSE_TYPE = :CENCODING
-
- def encoding
- ensure_parsed
- @encoding
- end
-
- def encoding=( arg )
- ensure_parsed
- @encoding = arg
- end
-
- private
-
- def init
- @encoding = nil
- end
-
- def set( s )
- @encoding = s
- end
-
- def isempty?
- not @encoding
- end
-
- def do_accept( strategy )
- strategy.meta @encoding.capitalize
- end
-
- end
-
-
- class ContentDispositionHeader < StructuredHeader
-
- PARSE_TYPE = :CDISPOSITION
-
- def disposition
- ensure_parsed
- @disposition
- end
-
- def disposition=( str )
- ensure_parsed
- @disposition = str.downcase
- end
-
- def params
- ensure_parsed
- unless @params.blank?
- @params.each do |k, v|
- @params[k] = unquote(v)
- end
- end
- @params
- end
-
- def []( key )
- ensure_parsed
- @params and unquote(@params[key])
- end
-
- def []=( key, val )
- ensure_parsed
- (@params ||= {})[key] = val
- end
-
- private
-
- def init
- @disposition = @params = nil
- end
-
- def set( args )
- @disposition, @params = *args
- end
-
- def isempty?
- not @disposition and (not @params or @params.empty?)
- end
-
- def do_accept( strategy )
- strategy.meta @disposition
- @params.each do |k,v|
- strategy.meta ';'
- strategy.space
- strategy.kv_pair k, unquote(v)
- end
- end
-
- end
-
-
- class HeaderField # redefine
-
- FNAME_TO_CLASS = {
- 'date' => DateTimeHeader,
- 'resent-date' => DateTimeHeader,
- 'to' => AddressHeader,
- 'cc' => AddressHeader,
- 'bcc' => AddressHeader,
- 'from' => AddressHeader,
- 'reply-to' => AddressHeader,
- 'resent-to' => AddressHeader,
- 'resent-cc' => AddressHeader,
- 'resent-bcc' => AddressHeader,
- 'resent-from' => AddressHeader,
- 'resent-reply-to' => AddressHeader,
- 'sender' => SingleAddressHeader,
- 'resent-sender' => SingleAddressHeader,
- 'return-path' => ReturnPathHeader,
- 'message-id' => MessageIdHeader,
- 'resent-message-id' => MessageIdHeader,
- 'in-reply-to' => ReferencesHeader,
- 'received' => ReceivedHeader,
- 'references' => ReferencesHeader,
- 'keywords' => KeywordsHeader,
- 'encrypted' => EncryptedHeader,
- 'mime-version' => MimeVersionHeader,
- 'content-type' => ContentTypeHeader,
- 'content-transfer-encoding' => ContentTransferEncodingHeader,
- 'content-disposition' => ContentDispositionHeader,
- 'content-id' => MessageIdHeader,
- 'subject' => UnstructuredHeader,
- 'comments' => UnstructuredHeader,
- 'content-description' => UnstructuredHeader
- }
-
- end
-
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb
deleted file mode 100644
index 554e2fd696..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-#:stopdoc:
-# This is here for Rolls.
-# Rolls uses this instead of lib/tmail.rb.
-
-require 'tmail/version'
-require 'tmail/mail'
-require 'tmail/mailbox'
-require 'tmail/core_extensions'
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb
deleted file mode 100644
index 2fc2dbdfc7..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb
+++ /dev/null
@@ -1,1130 +0,0 @@
-=begin rdoc
-
-= interface.rb Provides an interface to the TMail object
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-# TMail::Mail objects get accessed primarily through the methods in this file.
-#
-#
-
-require 'tmail/utils'
-
-module TMail
-
- class Mail
-
- # Allows you to query the mail object with a string to get the contents
- # of the field you want.
- #
- # Returns a string of the exact contents of the field
- #
- # mail.from = "mikel <mikel@lindsaar.net>"
- # mail.header_string("From") #=> "mikel <mikel@lindsaar.net>"
- def header_string( name, default = nil )
- h = @header[name.downcase] or return default
- h.to_s
- end
-
- #:stopdoc:
- #--
- #== Attributes
-
- include TextUtils
-
- def set_string_array_attr( key, strs )
- strs.flatten!
- if strs.empty?
- @header.delete key.downcase
- else
- store key, strs.join(', ')
- end
- strs
- end
- private :set_string_array_attr
-
- def set_string_attr( key, str )
- if str
- store key, str
- else
- @header.delete key.downcase
- end
- str
- end
- private :set_string_attr
-
- def set_addrfield( name, arg )
- if arg
- h = HeaderField.internal_new(name, @config)
- h.addrs.replace [arg].flatten
- @header[name] = h
- else
- @header.delete name
- end
- arg
- end
- private :set_addrfield
-
- def addrs2specs( addrs )
- return nil unless addrs
- list = addrs.map {|addr|
- if addr.address_group?
- then addr.map {|a| a.spec }
- else addr.spec
- end
- }.flatten
- return nil if list.empty?
- list
- end
- private :addrs2specs
-
- #:startdoc:
-
- #== Date and Time methods
-
- # Returns the date of the email message as per the "date" header value or returns
- # nil by default (if no date field exists).
- #
- # You can also pass whatever default you want into this method and it will return
- # that instead of nil if there is no date already set.
- def date( default = nil )
- if h = @header['date']
- h.date
- else
- default
- end
- end
-
- # Destructively sets the date of the mail object with the passed Time instance,
- # returns a Time instance set to the date/time of the mail
- #
- # Example:
- #
- # now = Time.now
- # mail.date = now
- # mail.date #=> Sat Nov 03 18:47:50 +1100 2007
- # mail.date.class #=> Time
- def date=( time )
- if time
- store 'Date', time2str(time)
- else
- @header.delete 'date'
- end
- time
- end
-
- # Returns the time of the mail message formatted to your taste using a
- # strftime format string. If no date set returns nil by default or whatever value
- # you pass as the second optional parameter.
- #
- # time = Time.now # (on Nov 16 2007)
- # mail.date = time
- # mail.strftime("%D") #=> "11/16/07"
- def strftime( fmt, default = nil )
- if t = date
- t.strftime(fmt)
- else
- default
- end
- end
-
- #== Destination methods
-
- # Return a TMail::Addresses instance for each entry in the "To:" field of the mail object header.
- #
- # If the "To:" field does not exist, will return nil by default or the value you
- # pass as the optional parameter.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.to_addrs #=> nil
- # mail.to_addrs([]) #=> []
- # mail.to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def to_addrs( default = nil )
- if h = @header['to']
- h.addrs
- else
- default
- end
- end
-
- # Return a TMail::Addresses instance for each entry in the "Cc:" field of the mail object header.
- #
- # If the "Cc:" field does not exist, will return nil by default or the value you
- # pass as the optional parameter.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.cc_addrs #=> nil
- # mail.cc_addrs([]) #=> []
- # mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.cc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def cc_addrs( default = nil )
- if h = @header['cc']
- h.addrs
- else
- default
- end
- end
-
- # Return a TMail::Addresses instance for each entry in the "Bcc:" field of the mail object header.
- #
- # If the "Bcc:" field does not exist, will return nil by default or the value you
- # pass as the optional parameter.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.bcc_addrs #=> nil
- # mail.bcc_addrs([]) #=> []
- # mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.bcc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def bcc_addrs( default = nil )
- if h = @header['bcc']
- h.addrs
- else
- default
- end
- end
-
- # Destructively set the to field of the "To:" header to equal the passed in string.
- #
- # TMail will parse your contents and turn each valid email address into a TMail::Address
- # object before assigning it to the mail message.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def to_addrs=( arg )
- set_addrfield 'to', arg
- end
-
- # Destructively set the to field of the "Cc:" header to equal the passed in string.
- #
- # TMail will parse your contents and turn each valid email address into a TMail::Address
- # object before assigning it to the mail message.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.cc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def cc_addrs=( arg )
- set_addrfield 'cc', arg
- end
-
- # Destructively set the to field of the "Bcc:" header to equal the passed in string.
- #
- # TMail will parse your contents and turn each valid email address into a TMail::Address
- # object before assigning it to the mail message.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.bcc_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def bcc_addrs=( arg )
- set_addrfield 'bcc', arg
- end
-
- # Returns who the email is to as an Array of email addresses as opposed to an Array of
- # TMail::Address objects which is what Mail#to_addrs returns
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.to #=> ["mikel@me.org", "mikel@you.org"]
- def to( default = nil )
- addrs2specs(to_addrs(nil)) || default
- end
-
- # Returns who the email cc'd as an Array of email addresses as opposed to an Array of
- # TMail::Address objects which is what Mail#to_addrs returns
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.cc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.cc #=> ["mikel@me.org", "mikel@you.org"]
- def cc( default = nil )
- addrs2specs(cc_addrs(nil)) || default
- end
-
- # Returns who the email bcc'd as an Array of email addresses as opposed to an Array of
- # TMail::Address objects which is what Mail#to_addrs returns
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.bcc = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.bcc #=> ["mikel@me.org", "mikel@you.org"]
- def bcc( default = nil )
- addrs2specs(bcc_addrs(nil)) || default
- end
-
- # Destructively sets the "To:" field to the passed array of strings (which should be valid
- # email addresses)
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.to = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
- # mail.to #=> ["mikel@abc.org", "mikel@xyz.org"]
- # mail['to'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
- def to=( *strs )
- set_string_array_attr 'To', strs
- end
-
- # Destructively sets the "Cc:" field to the passed array of strings (which should be valid
- # email addresses)
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.cc = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
- # mail.cc #=> ["mikel@abc.org", "mikel@xyz.org"]
- # mail['cc'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
- def cc=( *strs )
- set_string_array_attr 'Cc', strs
- end
-
- # Destructively sets the "Bcc:" field to the passed array of strings (which should be valid
- # email addresses)
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.bcc = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
- # mail.bcc #=> ["mikel@abc.org", "mikel@xyz.org"]
- # mail['bcc'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
- def bcc=( *strs )
- set_string_array_attr 'Bcc', strs
- end
-
- #== Originator methods
-
- # Return a TMail::Addresses instance for each entry in the "From:" field of the mail object header.
- #
- # If the "From:" field does not exist, will return nil by default or the value you
- # pass as the optional parameter.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.from_addrs #=> nil
- # mail.from_addrs([]) #=> []
- # mail.from = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.from_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def from_addrs( default = nil )
- if h = @header['from']
- h.addrs
- else
- default
- end
- end
-
- # Destructively set the to value of the "From:" header to equal the passed in string.
- #
- # TMail will parse your contents and turn each valid email address into a TMail::Address
- # object before assigning it to the mail message.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.from_addrs = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.from_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def from_addrs=( arg )
- set_addrfield 'from', arg
- end
-
- # Returns who the email is from as an Array of email address strings instead to an Array of
- # TMail::Address objects which is what Mail#from_addrs returns
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.from = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.from #=> ["mikel@me.org", "mikel@you.org"]
- def from( default = nil )
- addrs2specs(from_addrs(nil)) || default
- end
-
- # Destructively sets the "From:" field to the passed array of strings (which should be valid
- # email addresses)
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.from = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
- # mail.from #=> ["mikel@abc.org", "mikel@xyz.org"]
- # mail['from'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
- def from=( *strs )
- set_string_array_attr 'From', strs
- end
-
- # Returns the "friendly" human readable part of the address
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.from = "Mikel Lindsaar <mikel@abc.com>"
- # mail.friendly_from #=> "Mikel Lindsaar"
- def friendly_from( default = nil )
- h = @header['from']
- a, = h.addrs
- return default unless a
- return a.phrase if a.phrase
- return h.comments.join(' ') unless h.comments.empty?
- a.spec
- end
-
- # Return a TMail::Addresses instance for each entry in the "Reply-To:" field of the mail object header.
- #
- # If the "Reply-To:" field does not exist, will return nil by default or the value you
- # pass as the optional parameter.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.reply_to_addrs #=> nil
- # mail.reply_to_addrs([]) #=> []
- # mail.reply_to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.reply_to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def reply_to_addrs( default = nil )
- if h = @header['reply-to']
- h.addrs.blank? ? default : h.addrs
- else
- default
- end
- end
-
- # Destructively set the to value of the "Reply-To:" header to equal the passed in argument.
- #
- # TMail will parse your contents and turn each valid email address into a TMail::Address
- # object before assigning it to the mail message.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.reply_to_addrs = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.reply_to_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def reply_to_addrs=( arg )
- set_addrfield 'reply-to', arg
- end
-
- # Returns who the email is from as an Array of email address strings instead to an Array of
- # TMail::Address objects which is what Mail#reply_to_addrs returns
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.reply_to = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.reply_to #=> ["mikel@me.org", "mikel@you.org"]
- def reply_to( default = nil )
- addrs2specs(reply_to_addrs(nil)) || default
- end
-
- # Destructively sets the "Reply-To:" field to the passed array of strings (which should be valid
- # email addresses)
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.reply_to = ["mikel@abc.com", "Mikel <mikel@xyz.com>"]
- # mail.reply_to #=> ["mikel@abc.org", "mikel@xyz.org"]
- # mail['reply_to'].to_s #=> "mikel@abc.com, Mikel <mikel@xyz.com>"
- def reply_to=( *strs )
- set_string_array_attr 'Reply-To', strs
- end
-
- # Return a TMail::Addresses instance of the "Sender:" field of the mail object header.
- #
- # If the "Sender:" field does not exist, will return nil by default or the value you
- # pass as the optional parameter.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.sender #=> nil
- # mail.sender([]) #=> []
- # mail.sender = "Mikel <mikel@me.org>"
- # mail.reply_to_addrs #=> [#<TMail::Address mikel@me.org>]
- def sender_addr( default = nil )
- f = @header['sender'] or return default
- f.addr or return default
- end
-
- # Destructively set the to value of the "Sender:" header to equal the passed in argument.
- #
- # TMail will parse your contents and turn each valid email address into a TMail::Address
- # object before assigning it to the mail message.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.sender_addrs = "Mikel <mikel@me.org>, another Mikel <mikel@you.org>"
- # mail.sender_addrs #=> [#<TMail::Address mikel@me.org>, #<TMail::Address mikel@you.org>]
- def sender_addr=( addr )
- if addr
- h = HeaderField.internal_new('sender', @config)
- h.addr = addr
- @header['sender'] = h
- else
- @header.delete 'sender'
- end
- addr
- end
-
- # Returns who the sender of this mail is as string instead to an Array of
- # TMail::Address objects which is what Mail#sender_addr returns
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.sender = "Mikel <mikel@me.org>"
- # mail.sender #=> "mikel@me.org"
- def sender( default = nil )
- f = @header['sender'] or return default
- a = f.addr or return default
- a.spec
- end
-
- # Destructively sets the "Sender:" field to the passed string (which should be a valid
- # email address)
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.sender = "mikel@abc.com"
- # mail.sender #=> "mikel@abc.org"
- # mail['sender'].to_s #=> "mikel@abc.com"
- def sender=( str )
- set_string_attr 'Sender', str
- end
-
- #== Subject methods
-
- # Returns the subject of the mail instance.
- #
- # If the subject field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.subject #=> nil
- # mail.subject("") #=> ""
- # mail.subject = "Hello"
- # mail.subject #=> "Hello"
- def subject( default = nil )
- if h = @header['subject']
- h.body
- else
- default
- end
- end
- alias quoted_subject subject
-
- # Destructively sets the passed string as the subject of the mail message.
- #
- # Example
- #
- # mail = TMail::Mail.new
- # mail.subject #=> "This subject"
- # mail.subject = "Another subject"
- # mail.subject #=> "Another subject"
- def subject=( str )
- set_string_attr 'Subject', str
- end
-
- #== Message Identity & Threading Methods
-
- # Returns the message ID for this mail object instance.
- #
- # If the message_id field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.message_id #=> nil
- # mail.message_id(TMail.new_message_id) #=> "<47404c5326d9c_2ad4fbb80161@baci.local.tmail>"
- # mail.message_id = TMail.new_message_id
- # mail.message_id #=> "<47404c5326d9c_2ad4fbb80161@baci.local.tmail>"
- def message_id( default = nil )
- if h = @header['message-id']
- h.id || default
- else
- default
- end
- end
-
- # Destructively sets the message ID of the mail object instance to the passed in string
- #
- # Invalid message IDs are ignored (silently, unless configured otherwise) and result in
- # a nil message ID. Left and right angle brackets are required.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.message_id = "<348F04F142D69C21-291E56D292BC@xxxx.net>"
- # mail.message_id #=> "<348F04F142D69C21-291E56D292BC@xxxx.net>"
- # mail.message_id = "this_is_my_badly_formatted_message_id"
- # mail.message_id #=> nil
- def message_id=( str )
- set_string_attr 'Message-Id', str
- end
-
- # Returns the "In-Reply-To:" field contents as an array of this mail instance if it exists
- #
- # If the in_reply_to field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.in_reply_to #=> nil
- # mail.in_reply_to([]) #=> []
- # TMail::Mail.load("../test/fixtures/raw_email_reply")
- # mail.in_reply_to #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
- def in_reply_to( default = nil )
- if h = @header['in-reply-to']
- h.ids
- else
- default
- end
- end
-
- # Destructively sets the value of the "In-Reply-To:" field of an email.
- #
- # Accepts an array of a single string of a message id
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.in_reply_to = ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
- # mail.in_reply_to #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
- def in_reply_to=( *idstrs )
- set_string_array_attr 'In-Reply-To', idstrs
- end
-
- # Returns the references of this email (prior messages relating to this message)
- # as an array of message ID strings. Useful when you are trying to thread an
- # email.
- #
- # If the references field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.references #=> nil
- # mail.references([]) #=> []
- # mail = TMail::Mail.load("../test/fixtures/raw_email_reply")
- # mail.references #=> ["<473FF3B8.9020707@xxx.org>", "<348F04F142D69C21-291E56D292BC@xxxx.net>"]
- def references( default = nil )
- if h = @header['references']
- h.refs
- else
- default
- end
- end
-
- # Destructively sets the value of the "References:" field of an email.
- #
- # Accepts an array of strings of message IDs
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.references = ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
- # mail.references #=> ["<348F04F142D69C21-291E56D292BC@xxxx.net>"]
- def references=( *strs )
- set_string_array_attr 'References', strs
- end
-
- #== MIME header methods
-
- # Returns the listed MIME version of this email from the "Mime-Version:" header field
- #
- # If the mime_version field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.mime_version #=> nil
- # mail.mime_version([]) #=> []
- # mail = TMail::Mail.load("../test/fixtures/raw_email")
- # mail.mime_version #=> "1.0"
- def mime_version( default = nil )
- if h = @header['mime-version']
- h.version || default
- else
- default
- end
- end
-
- def mime_version=( m, opt = nil )
- if opt
- if h = @header['mime-version']
- h.major = m
- h.minor = opt
- else
- store 'Mime-Version', "#{m}.#{opt}"
- end
- else
- store 'Mime-Version', m
- end
- m
- end
-
- # Returns the current "Content-Type" of the mail instance.
- #
- # If the content_type field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.content_type #=> nil
- # mail.content_type([]) #=> []
- # mail = TMail::Mail.load("../test/fixtures/raw_email")
- # mail.content_type #=> "text/plain"
- def content_type( default = nil )
- if h = @header['content-type']
- h.content_type || default
- else
- default
- end
- end
-
- # Returns the current main type of the "Content-Type" of the mail instance.
- #
- # If the content_type field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.main_type #=> nil
- # mail.main_type([]) #=> []
- # mail = TMail::Mail.load("../test/fixtures/raw_email")
- # mail.main_type #=> "text"
- def main_type( default = nil )
- if h = @header['content-type']
- h.main_type || default
- else
- default
- end
- end
-
- # Returns the current sub type of the "Content-Type" of the mail instance.
- #
- # If the content_type field does not exist, returns nil by default or you can pass in as
- # the parameter for what you want the default value to be.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.sub_type #=> nil
- # mail.sub_type([]) #=> []
- # mail = TMail::Mail.load("../test/fixtures/raw_email")
- # mail.sub_type #=> "plain"
- def sub_type( default = nil )
- if h = @header['content-type']
- h.sub_type || default
- else
- default
- end
- end
-
- # Destructively sets the "Content-Type:" header field of this mail object
- #
- # Allows you to set the main type, sub type as well as parameters to the field.
- # The main type and sub type need to be a string.
- #
- # The optional params hash can be passed with keys as symbols and values as a string,
- # or strings as keys and values.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.set_content_type("text", "plain")
- # mail.to_s #=> "Content-Type: text/plain\n\n"
- #
- # mail.set_content_type("text", "plain", {:charset => "EUC-KR", :format => "flowed"})
- # mail.to_s #=> "Content-Type: text/plain; charset=EUC-KR; format=flowed\n\n"
- #
- # mail.set_content_type("text", "plain", {"charset" => "EUC-KR", "format" => "flowed"})
- # mail.to_s #=> "Content-Type: text/plain; charset=EUC-KR; format=flowed\n\n"
- def set_content_type( str, sub = nil, param = nil )
- if sub
- main, sub = str, sub
- else
- main, sub = str.split(%r</>, 2)
- raise ArgumentError, "sub type missing: #{str.inspect}" unless sub
- end
- if h = @header['content-type']
- h.main_type = main
- h.sub_type = sub
- h.params.clear
- else
- store 'Content-Type', "#{main}/#{sub}"
- end
- @header['content-type'].params.replace param if param
- str
- end
-
- alias content_type= set_content_type
-
- # Returns the named type parameter as a string, from the "Content-Type:" header.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.type_param("charset") #=> nil
- # mail.type_param("charset", []) #=> []
- # mail.set_content_type("text", "plain", {:charset => "EUC-KR", :format => "flowed"})
- # mail.type_param("charset") #=> "EUC-KR"
- # mail.type_param("format") #=> "flowed"
- def type_param( name, default = nil )
- if h = @header['content-type']
- h[name] || default
- else
- default
- end
- end
-
- # Returns the character set of the email. Returns nil if no encoding set or returns
- # whatever default you pass as a parameter - note passing the parameter does NOT change
- # the mail object in any way.
- #
- # Example:
- #
- # mail = TMail::Mail.load("path_to/utf8_email")
- # mail.charset #=> "UTF-8"
- #
- # mail = TMail::Mail.new
- # mail.charset #=> nil
- # mail.charset("US-ASCII") #=> "US-ASCII"
- def charset( default = nil )
- if h = @header['content-type']
- h['charset'] or default
- else
- default
- end
- end
-
- # Destructively sets the character set used by this mail object to the passed string, you
- # should note though that this does nothing to the mail body, just changes the header
- # value, you will need to transliterate the body as well to match whatever you put
- # in this header value if you are changing character sets.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.charset #=> nil
- # mail.charset = "UTF-8"
- # mail.charset #=> "UTF-8"
- def charset=( str )
- if str
- if h = @header[ 'content-type' ]
- h['charset'] = str
- else
- store 'Content-Type', "text/plain; charset=#{str}"
- end
- end
- str
- end
-
- # Returns the transfer encoding of the email. Returns nil if no encoding set or returns
- # whatever default you pass as a parameter - note passing the parameter does NOT change
- # the mail object in any way.
- #
- # Example:
- #
- # mail = TMail::Mail.load("path_to/base64_encoded_email")
- # mail.transfer_encoding #=> "base64"
- #
- # mail = TMail::Mail.new
- # mail.transfer_encoding #=> nil
- # mail.transfer_encoding("base64") #=> "base64"
- def transfer_encoding( default = nil )
- if h = @header['content-transfer-encoding']
- h.encoding || default
- else
- default
- end
- end
-
- # Destructively sets the transfer encoding of the mail object to the passed string, you
- # should note though that this does nothing to the mail body, just changes the header
- # value, you will need to encode or decode the body as well to match whatever you put
- # in this header value.
- #
- # Example:
- #
- # mail = TMail::Mail.new
- # mail.transfer_encoding #=> nil
- # mail.transfer_encoding = "base64"
- # mail.transfer_encoding #=> "base64"
- def transfer_encoding=( str )
- set_string_attr 'Content-Transfer-Encoding', str
- end
-
- alias encoding transfer_encoding
- alias encoding= transfer_encoding=
- alias content_transfer_encoding transfer_encoding
- alias content_transfer_encoding= transfer_encoding=
-
- # Returns the content-disposition of the mail object, returns nil or the passed
- # default value if given
- #
- # Example:
- #
- # mail = TMail::Mail.load("path_to/raw_mail_with_attachment")
- # mail.disposition #=> "attachment"
- #
- # mail = TMail::Mail.load("path_to/plain_simple_email")
- # mail.disposition #=> nil
- # mail.disposition(false) #=> false
- def disposition( default = nil )
- if h = @header['content-disposition']
- h.disposition || default
- else
- default
- end
- end
-
- alias content_disposition disposition
-
- # Allows you to set the content-disposition of the mail object. Accepts a type
- # and a hash of parameters.
- #
- # Example:
- #
- # mail.set_disposition("attachment", {:filename => "test.rb"})
- # mail.disposition #=> "attachment"
- # mail['content-disposition'].to_s #=> "attachment; filename=test.rb"
- def set_disposition( str, params = nil )
- if h = @header['content-disposition']
- h.disposition = str
- h.params.clear
- else
- store('Content-Disposition', str)
- h = @header['content-disposition']
- end
- h.params.replace params if params
- end
-
- alias disposition= set_disposition
- alias set_content_disposition set_disposition
- alias content_disposition= set_disposition
-
- # Returns the value of a parameter in an existing content-disposition header
- #
- # Example:
- #
- # mail.set_disposition("attachment", {:filename => "test.rb"})
- # mail['content-disposition'].to_s #=> "attachment; filename=test.rb"
- # mail.disposition_param("filename") #=> "test.rb"
- # mail.disposition_param("missing_param_key") #=> nil
- # mail.disposition_param("missing_param_key", false) #=> false
- # mail.disposition_param("missing_param_key", "Nothing to see here") #=> "Nothing to see here"
- def disposition_param( name, default = nil )
- if h = @header['content-disposition']
- h[name] || default
- else
- default
- end
- end
-
- # Convert the Mail object's body into a Base64 encoded email
- # returning the modified Mail object
- def base64_encode!
- store 'Content-Transfer-Encoding', 'Base64'
- self.body = base64_encode
- end
-
- # Return the result of encoding the TMail::Mail object body
- # without altering the current body
- def base64_encode
- Base64.folding_encode(self.body)
- end
-
- # Convert the Mail object's body into a Base64 decoded email
- # returning the modified Mail object
- def base64_decode!
- if /base64/i === self.transfer_encoding('')
- store 'Content-Transfer-Encoding', '8bit'
- self.body = base64_decode
- end
- end
-
- # Returns the result of decoding the TMail::Mail object body
- # without altering the current body
- def base64_decode
- Base64.decode(self.body, @config.strict_base64decode?)
- end
-
- # Returns an array of each destination in the email message including to: cc: or bcc:
- #
- # Example:
- #
- # mail.to = "Mikel <mikel@lindsaar.net>"
- # mail.cc = "Trans <t@t.com>"
- # mail.bcc = "bob <bob@me.com>"
- # mail.destinations #=> ["mikel@lindsaar.net", "t@t.com", "bob@me.com"]
- def destinations( default = nil )
- ret = []
- %w( to cc bcc ).each do |nm|
- if h = @header[nm]
- h.addrs.each {|i| ret.push i.address }
- end
- end
- ret.empty? ? default : ret
- end
-
- # Yields a block of destination, yielding each as a string.
- # (from the destinations example)
- # mail.each_destination { |d| puts "#{d.class}: #{d}" }
- # String: mikel@lindsaar.net
- # String: t@t.com
- # String: bob@me.com
- def each_destination( &block )
- destinations([]).each do |i|
- if Address === i
- yield i
- else
- i.each(&block)
- end
- end
- end
-
- alias each_dest each_destination
-
- # Returns an array of reply to addresses that the Mail object has,
- # or if the Mail message has no reply-to, returns an array of the
- # Mail objects from addresses. Else returns the default which can
- # either be passed as a parameter or defaults to nil
- #
- # Example:
- # mail.from = "Mikel <mikel@lindsaar.net>"
- # mail.reply_to = nil
- # mail.reply_addresses #=> [""]
- #
- def reply_addresses( default = nil )
- reply_to_addrs(nil) or from_addrs(nil) or default
- end
-
- # Returns the "sender" field as an array -> useful to find out who to
- # send an error email to.
- def error_reply_addresses( default = nil )
- if s = sender(nil)
- [s]
- else
- from_addrs(default)
- end
- end
-
- # Returns true if the Mail object is a multipart message
- def multipart?
- main_type('').downcase == 'multipart'
- end
-
- # Creates a new email in reply to self. Sets the In-Reply-To and
- # References headers for you automagically.
- #
- # Example:
- # mail = TMail::Mail.load("my_email")
- # reply_email = mail.create_reply
- # reply_email.class #=> TMail::Mail
- # reply_email.references #=> ["<d3b8cf8e49f04480850c28713a1f473e@lindsaar.net>"]
- # reply_email.in_reply_to #=> ["<d3b8cf8e49f04480850c28713a1f473e@lindsaar.net>"]
- def create_reply
- setup_reply create_empty_mail()
- end
-
- # Creates a new email in reply to self. Sets the In-Reply-To and
- # References headers for you automagically.
- #
- # Example:
- # mail = TMail::Mail.load("my_email")
- # forward_email = mail.create_forward
- # forward_email.class #=> TMail::Mail
- # forward_email.content_type #=> "multipart/mixed"
- # forward_email.body #=> "Attachment: (unnamed)"
- # forward_email.encoded #=> Returns the original email as a MIME attachment
- def create_forward
- setup_forward create_empty_mail()
- end
-
- #:stopdoc:
- private
-
- def create_empty_mail
- self.class.new(StringPort.new(''), @config)
- end
-
- def setup_reply( mail )
- if tmp = reply_addresses(nil)
- mail.to_addrs = tmp
- end
-
- mid = message_id(nil)
- tmp = references(nil) || []
- tmp.push mid if mid
- mail.in_reply_to = [mid] if mid
- mail.references = tmp unless tmp.empty?
- mail.subject = 'Re: ' + subject('').sub(/\A(?:\[[^\]]+\])?(?:\s*Re:)*\s*/i, '')
- mail.mime_version = '1.0'
- mail
- end
-
- def setup_forward( mail )
- m = Mail.new(StringPort.new(''))
- m.body = decoded
- m.set_content_type 'message', 'rfc822'
- m.encoding = encoding('7bit')
- mail.parts.push m
- # call encoded to reparse the message
- mail.encoded
- mail
- end
-
- #:startdoc:
- end # class Mail
-
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb
deleted file mode 100644
index 6c0e251102..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-#:stopdoc:
-require 'tmail/mailbox'
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb
deleted file mode 100644
index 23a3f75de3..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb
+++ /dev/null
@@ -1,579 +0,0 @@
-=begin rdoc
-
-= Mail class
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-
-
-require 'tmail/interface'
-require 'tmail/encode'
-require 'tmail/header'
-require 'tmail/port'
-require 'tmail/config'
-require 'tmail/utils'
-require 'tmail/attachments'
-require 'tmail/quoting'
-require 'socket'
-
-module TMail
-
- # == Mail Class
- #
- # Accessing a TMail object done via the TMail::Mail class. As email can be fairly complex
- # creatures, you will find a large amount of accessor and setter methods in this class!
- #
- # Most of the below methods handle the header, in fact, what TMail does best is handle the
- # header of the email object. There are only a few methods that deal directly with the body
- # of the email, such as base64_encode and base64_decode.
- #
- # === Using TMail inside your code
- #
- # The usual way is to install the gem (see the {README}[link:/README] on how to do this) and
- # then put at the top of your class:
- #
- # require 'tmail'
- #
- # You can then create a new TMail object in your code with:
- #
- # @email = TMail::Mail.new
- #
- # Or if you have an email as a string, you can initialize a new TMail::Mail object and get it
- # to parse that string for you like so:
- #
- # @email = TMail::Mail.parse(email_text)
- #
- # You can also read a single email off the disk, for example:
- #
- # @email = TMail::Mail.load('filename.txt')
- #
- # Also, you can read a mailbox (usual unix mbox format) and end up with an array of TMail
- # objects by doing something like this:
- #
- # # Note, we pass true as the last variable to open the mailbox read only
- # mailbox = TMail::UNIXMbox.new("mailbox", nil, true)
- # @emails = []
- # mailbox.each_port { |m| @emails << TMail::Mail.new(m) }
- #
- class Mail
-
- class << self
-
- # Opens an email that has been saved out as a file by itself.
- #
- # This function will read a file non-destructively and then parse
- # the contents and return a TMail::Mail object.
- #
- # Does not handle multiple email mailboxes (like a unix mbox) for that
- # use the TMail::UNIXMbox class.
- #
- # Example:
- # mail = TMail::Mail.load('filename')
- #
- def load( fname )
- new(FilePort.new(fname))
- end
-
- alias load_from load
- alias loadfrom load
-
- # Parses an email from the supplied string and returns a TMail::Mail
- # object.
- #
- # Example:
- # require 'rubygems'; require 'tmail'
- # email_string =<<HEREDOC
- # To: mikel@lindsaar.net
- # From: mikel@me.com
- # Subject: This is a short Email
- #
- # Hello there Mikel!
- #
- # HEREDOC
- # mail = TMail::Mail.parse(email_string)
- # #=> #<TMail::Mail port=#<TMail::StringPort:id=0xa30ac0> bodyport=nil>
- # mail.body
- # #=> "Hello there Mikel!\n\n"
- def parse( str )
- new(StringPort.new(str))
- end
-
- end
-
- def initialize( port = nil, conf = DEFAULT_CONFIG ) #:nodoc:
- @port = port || StringPort.new
- @config = Config.to_config(conf)
-
- @header = {}
- @body_port = nil
- @body_parsed = false
- @epilogue = ''
- @parts = []
-
- @port.ropen {|f|
- parse_header f
- parse_body f unless @port.reproducible?
- }
- end
-
- # Provides access to the port this email is using to hold it's data
- #
- # Example:
- # mail = TMail::Mail.parse(email_string)
- # mail.port
- # #=> #<TMail::StringPort:id=0xa2c952>
- attr_reader :port
-
- def inspect
- "\#<#{self.class} port=#{@port.inspect} bodyport=#{@body_port.inspect}>"
- end
-
- #
- # to_s interfaces
- #
-
- public
-
- include StrategyInterface
-
- def write_back( eol = "\n", charset = 'e' )
- parse_body
- @port.wopen {|stream| encoded eol, charset, stream }
- end
-
- def accept( strategy )
- with_multipart_encoding(strategy) {
- ordered_each do |name, field|
- next if field.empty?
- strategy.header_name canonical(name)
- field.accept strategy
- strategy.puts
- end
- strategy.puts
- body_port().ropen {|r|
- strategy.write r.read
- }
- }
- end
-
- private
-
- def canonical( name )
- name.split(/-/).map {|s| s.capitalize }.join('-')
- end
-
- def with_multipart_encoding( strategy )
- if parts().empty? # DO NOT USE @parts
- yield
-
- else
- bound = ::TMail.new_boundary
- if @header.key? 'content-type'
- @header['content-type'].params['boundary'] = bound
- else
- store 'Content-Type', %<multipart/mixed; boundary="#{bound}">
- end
-
- yield
-
- parts().each do |tm|
- strategy.puts
- strategy.puts '--' + bound
- tm.accept strategy
- end
- strategy.puts
- strategy.puts '--' + bound + '--'
- strategy.write epilogue()
- end
- end
-
- ###
- ### header
- ###
-
- public
-
- ALLOW_MULTIPLE = {
- 'received' => true,
- 'resent-date' => true,
- 'resent-from' => true,
- 'resent-sender' => true,
- 'resent-to' => true,
- 'resent-cc' => true,
- 'resent-bcc' => true,
- 'resent-message-id' => true,
- 'comments' => true,
- 'keywords' => true
- }
- USE_ARRAY = ALLOW_MULTIPLE
-
- def header
- @header.dup
- end
-
- # Returns a TMail::AddressHeader object of the field you are querying.
- # Examples:
- # @mail['from'] #=> #<TMail::AddressHeader "mikel@test.com.au">
- # @mail['to'] #=> #<TMail::AddressHeader "mikel@test.com.au">
- #
- # You can get the string value of this by passing "to_s" to the query:
- # Example:
- # @mail['to'].to_s #=> "mikel@test.com.au"
- def []( key )
- @header[key.downcase]
- end
-
- def sub_header(key, param)
- (hdr = self[key]) ? hdr[param] : nil
- end
-
- alias fetch []
-
- # Allows you to set or delete TMail header objects at will.
- # Examples:
- # @mail = TMail::Mail.new
- # @mail['to'].to_s # => 'mikel@test.com.au'
- # @mail['to'] = 'mikel@elsewhere.org'
- # @mail['to'].to_s # => 'mikel@elsewhere.org'
- # @mail.encoded # => "To: mikel@elsewhere.org\r\n\r\n"
- # @mail['to'] = nil
- # @mail['to'].to_s # => nil
- # @mail.encoded # => "\r\n"
- #
- # Note: setting mail[] = nil actually deletes the header field in question from the object,
- # it does not just set the value of the hash to nil
- def []=( key, val )
- dkey = key.downcase
-
- if val.nil?
- @header.delete dkey
- return nil
- end
-
- case val
- when String
- header = new_hf(key, val)
- when HeaderField
- ;
- when Array
- ALLOW_MULTIPLE.include? dkey or
- raise ArgumentError, "#{key}: Header must not be multiple"
- @header[dkey] = val
- return val
- else
- header = new_hf(key, val.to_s)
- end
- if ALLOW_MULTIPLE.include? dkey
- (@header[dkey] ||= []).push header
- else
- @header[dkey] = header
- end
-
- val
- end
-
- alias store []=
-
- # Allows you to loop through each header in the TMail::Mail object in a block
- # Example:
- # @mail['to'] = 'mikel@elsewhere.org'
- # @mail['from'] = 'me@me.com'
- # @mail.each_header { |k,v| puts "#{k} = #{v}" }
- # # => from = me@me.com
- # # => to = mikel@elsewhere.org
- def each_header
- @header.each do |key, val|
- [val].flatten.each {|v| yield key, v }
- end
- end
-
- alias each_pair each_header
-
- def each_header_name( &block )
- @header.each_key(&block)
- end
-
- alias each_key each_header_name
-
- def each_field( &block )
- @header.values.flatten.each(&block)
- end
-
- alias each_value each_field
-
- FIELD_ORDER = %w(
- return-path received
- resent-date resent-from resent-sender resent-to
- resent-cc resent-bcc resent-message-id
- date from sender reply-to to cc bcc
- message-id in-reply-to references
- subject comments keywords
- mime-version content-type content-transfer-encoding
- content-disposition content-description
- )
-
- def ordered_each
- list = @header.keys
- FIELD_ORDER.each do |name|
- if list.delete(name)
- [@header[name]].flatten.each {|v| yield name, v }
- end
- end
- list.each do |name|
- [@header[name]].flatten.each {|v| yield name, v }
- end
- end
-
- def clear
- @header.clear
- end
-
- def delete( key )
- @header.delete key.downcase
- end
-
- def delete_if
- @header.delete_if do |key,val|
- if Array === val
- val.delete_if {|v| yield key, v }
- val.empty?
- else
- yield key, val
- end
- end
- end
-
- def keys
- @header.keys
- end
-
- def key?( key )
- @header.key? key.downcase
- end
-
- def values_at( *args )
- args.map {|k| @header[k.downcase] }.flatten
- end
-
- alias indexes values_at
- alias indices values_at
-
- private
-
- def parse_header( f )
- name = field = nil
- unixfrom = nil
-
- while line = f.gets
- case line
- when /\A[ \t]/ # continue from prev line
- raise SyntaxError, 'mail is began by space' unless field
- field << ' ' << line.strip
-
- when /\A([^\: \t]+):\s*/ # new header line
- add_hf name, field if field
- name = $1
- field = $' #.strip
-
- when /\A\-*\s*\z/ # end of header
- add_hf name, field if field
- name = field = nil
- break
-
- when /\AFrom (\S+)/
- unixfrom = $1
-
- when /^charset=.*/
-
- else
- raise SyntaxError, "wrong mail header: '#{line.inspect}'"
- end
- end
- add_hf name, field if name
-
- if unixfrom
- add_hf 'Return-Path', "<#{unixfrom}>" unless @header['return-path']
- end
- end
-
- def add_hf( name, field )
- key = name.downcase
- field = new_hf(name, field)
-
- if ALLOW_MULTIPLE.include? key
- (@header[key] ||= []).push field
- else
- @header[key] = field
- end
- end
-
- def new_hf( name, field )
- HeaderField.new(name, field, @config)
- end
-
- ###
- ### body
- ###
-
- public
-
- def body_port
- parse_body
- @body_port
- end
-
- def each( &block )
- body_port().ropen {|f| f.each(&block) }
- end
-
- def quoted_body
- body_port.ropen {|f| return f.read }
- end
-
- def quoted_body= str
- body_port.wopen { |f| f.write str }
- str
- end
-
- def body=( str )
- # Sets the body of the email to a new (encoded) string.
- #
- # We also reparses the email if the body is ever reassigned, this is a performance hit, however when
- # you assign the body, you usually want to be able to make sure that you can access the attachments etc.
- #
- # Usage:
- #
- # mail.body = "Hello, this is\nthe body text"
- # # => "Hello, this is\nthe body"
- # mail.body
- # # => "Hello, this is\nthe body"
- @body_parsed = false
- parse_body(StringInput.new(str))
- parse_body
- @body_port.wopen {|f| f.write str }
- str
- end
-
- alias preamble quoted_body
- alias preamble= quoted_body=
-
- def epilogue
- parse_body
- @epilogue.dup
- end
-
- def epilogue=( str )
- parse_body
- @epilogue = str
- str
- end
-
- def parts
- parse_body
- @parts
- end
-
- def each_part( &block )
- parts().each(&block)
- end
-
- # Returns true if the content type of this part of the email is
- # a disposition attachment
- def disposition_is_attachment?
- (self['content-disposition'] && self['content-disposition'].disposition == "attachment")
- end
-
- # Returns true if this part's content main type is text, else returns false.
- # By main type is meant "text/plain" is text. "text/html" is text
- def content_type_is_text?
- self.header['content-type'] && (self.header['content-type'].main_type != "text")
- end
-
- private
-
- def parse_body( f = nil )
- return if @body_parsed
-
- if f
- parse_body_0 f
- else
- @port.ropen {|f|
- skip_header f
- parse_body_0 f
- }
- end
- @body_parsed = true
- end
-
- def skip_header( f )
- while line = f.gets
- return if /\A[\r\n]*\z/ === line
- end
- end
-
- def parse_body_0( f )
- if multipart?
- read_multipart f
- else
- @body_port = @config.new_body_port(self)
- @body_port.wopen {|w|
- w.write f.read
- }
- end
- end
-
- def read_multipart( src )
- bound = @header['content-type'].params['boundary']
- is_sep = /\A--#{Regexp.quote bound}(?:--)?[ \t]*(?:\n|\r\n|\r)/
- lastbound = "--#{bound}--"
-
- ports = [ @config.new_preamble_port(self) ]
- begin
- f = ports.last.wopen
- while line = src.gets
- if is_sep === line
- f.close
- break if line.strip == lastbound
- ports.push @config.new_part_port(self)
- f = ports.last.wopen
- else
- f << line
- end
- end
- @epilogue = (src.read || '')
- ensure
- f.close if f and not f.closed?
- end
-
- @body_port = ports.shift
- @parts = ports.map {|p| self.class.new(p, @config) }
- end
-
- end # class Mail
-
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb
deleted file mode 100644
index b0bc6a7f74..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb
+++ /dev/null
@@ -1,495 +0,0 @@
-=begin rdoc
-
-= Mailbox and Mbox interaction class
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-require 'tmail/port'
-require 'socket'
-require 'mutex_m'
-
-
-unless [].respond_to?(:sort_by)
-module Enumerable#:nodoc:
- def sort_by
- map {|i| [yield(i), i] }.sort {|a,b| a.first <=> b.first }.map {|i| i[1] }
- end
-end
-end
-
-
-module TMail
-
- class MhMailbox
-
- PORT_CLASS = MhPort
-
- def initialize( dir )
- edir = File.expand_path(dir)
- raise ArgumentError, "not directory: #{dir}"\
- unless FileTest.directory? edir
- @dirname = edir
- @last_file = nil
- @last_atime = nil
- end
-
- def directory
- @dirname
- end
-
- alias dirname directory
-
- attr_accessor :last_atime
-
- def inspect
- "#<#{self.class} #{@dirname}>"
- end
-
- def close
- end
-
- def new_port
- PORT_CLASS.new(next_file_name())
- end
-
- def each_port
- mail_files().each do |path|
- yield PORT_CLASS.new(path)
- end
- @last_atime = Time.now
- end
-
- alias each each_port
-
- def reverse_each_port
- mail_files().reverse_each do |path|
- yield PORT_CLASS.new(path)
- end
- @last_atime = Time.now
- end
-
- alias reverse_each reverse_each_port
-
- # old #each_mail returns Port
- #def each_mail
- # each_port do |port|
- # yield Mail.new(port)
- # end
- #end
-
- def each_new_port( mtime = nil, &block )
- mtime ||= @last_atime
- return each_port(&block) unless mtime
- return unless File.mtime(@dirname) >= mtime
-
- mail_files().each do |path|
- yield PORT_CLASS.new(path) if File.mtime(path) > mtime
- end
- @last_atime = Time.now
- end
-
- private
-
- def mail_files
- Dir.entries(@dirname)\
- .select {|s| /\A\d+\z/ === s }\
- .map {|s| s.to_i }\
- .sort\
- .map {|i| "#{@dirname}/#{i}" }\
- .select {|path| FileTest.file? path }
- end
-
- def next_file_name
- unless n = @last_file
- n = 0
- Dir.entries(@dirname)\
- .select {|s| /\A\d+\z/ === s }\
- .map {|s| s.to_i }.sort\
- .each do |i|
- next unless FileTest.file? "#{@dirname}/#{i}"
- n = i
- end
- end
- begin
- n += 1
- end while FileTest.exist? "#{@dirname}/#{n}"
- @last_file = n
-
- "#{@dirname}/#{n}"
- end
-
- end # MhMailbox
-
- MhLoader = MhMailbox
-
-
- class UNIXMbox
-
- class << self
- alias newobj new
- end
-
- # Creates a new mailbox object that you can iterate through to collect the
- # emails from with "each_port".
- #
- # You need to pass it a filename of a unix mailbox format file, the format of this
- # file can be researched at this page at {wikipedia}[link:http://en.wikipedia.org/wiki/Mbox]
- #
- # ==== Parameters
- #
- # +filename+: The filename of the mailbox you want to open
- #
- # +tmpdir+: Can be set to override TMail using the system environment's temp dir. TMail will first
- # use the temp dir specified by you (if any) or then the temp dir specified in the Environment's TEMP
- # value then the value in the Environment's TMP value or failing all of the above, '/tmp'
- #
- # +readonly+: If set to false, each email you take from the mail box will be removed from the mailbox.
- # default is *false* - ie, it *WILL* truncate your mailbox file to ZERO once it has read the emails out.
- #
- # ==== Options:
- #
- # None
- #
- # ==== Examples:
- #
- # # First show using readonly true:
- #
- # require 'ftools'
- # File.size("../test/fixtures/mailbox")
- # #=> 20426
- #
- # mailbox = TMail::UNIXMbox.new("../test/fixtures/mailbox", nil, true)
- # #=> #<TMail::UNIXMbox:0x14a2aa8 @readonly=true.....>
- #
- # mailbox.each_port do |port|
- # mail = TMail::Mail.new(port)
- # puts mail.subject
- # end
- # #Testing mailbox 1
- # #Testing mailbox 2
- # #Testing mailbox 3
- # #Testing mailbox 4
- # require 'ftools'
- # File.size?("../test/fixtures/mailbox")
- # #=> 20426
- #
- # # Now show with readonly set to the default false
- #
- # mailbox = TMail::UNIXMbox.new("../test/fixtures/mailbox")
- # #=> #<TMail::UNIXMbox:0x14a2aa8 @readonly=false.....>
- #
- # mailbox.each_port do |port|
- # mail = TMail::Mail.new(port)
- # puts mail.subject
- # end
- # #Testing mailbox 1
- # #Testing mailbox 2
- # #Testing mailbox 3
- # #Testing mailbox 4
- #
- # File.size?("../test/fixtures/mailbox")
- # #=> nil
- def UNIXMbox.new( filename, tmpdir = nil, readonly = false )
- tmpdir = ENV['TEMP'] || ENV['TMP'] || '/tmp'
- newobj(filename, "#{tmpdir}/ruby_tmail_#{$$}_#{rand()}", readonly, false)
- end
-
- def UNIXMbox.lock( fname )
- begin
- f = File.open(fname, 'r+')
- f.flock File::LOCK_EX
- yield f
- ensure
- f.flock File::LOCK_UN
- f.close if f and not f.closed?
- end
- end
-
- def UNIXMbox.static_new( fname, dir, readonly = false )
- newobj(fname, dir, readonly, true)
- end
-
- def initialize( fname, mhdir, readonly, static )
- @filename = fname
- @readonly = readonly
- @closed = false
-
- Dir.mkdir mhdir
- @real = MhMailbox.new(mhdir)
- @finalizer = UNIXMbox.mkfinal(@real, @filename, !@readonly, !static)
- ObjectSpace.define_finalizer self, @finalizer
- end
-
- def UNIXMbox.mkfinal( mh, mboxfile, writeback_p, cleanup_p )
- lambda {
- if writeback_p
- lock(mboxfile) {|f|
- mh.each_port do |port|
- f.puts create_from_line(port)
- port.ropen {|r|
- f.puts r.read
- }
- end
- }
- end
- if cleanup_p
- Dir.foreach(mh.dirname) do |fname|
- next if /\A\.\.?\z/ === fname
- File.unlink "#{mh.dirname}/#{fname}"
- end
- Dir.rmdir mh.dirname
- end
- }
- end
-
- # make _From line
- def UNIXMbox.create_from_line( port )
- sprintf 'From %s %s',
- fromaddr(), TextUtils.time2str(File.mtime(port.filename))
- end
-
- def UNIXMbox.fromaddr(port)
- h = HeaderField.new_from_port(port, 'Return-Path') ||
- HeaderField.new_from_port(port, 'From') ||
- HeaderField.new_from_port(port, 'EnvelopeSender') or return 'nobody'
- a = h.addrs[0] or return 'nobody'
- a.spec
- end
-
- def close
- return if @closed
-
- ObjectSpace.undefine_finalizer self
- @finalizer.call
- @finalizer = nil
- @real = nil
- @closed = true
- @updated = nil
- end
-
- def each_port( &block )
- close_check
- update
- @real.each_port(&block)
- end
-
- alias each each_port
-
- def reverse_each_port( &block )
- close_check
- update
- @real.reverse_each_port(&block)
- end
-
- alias reverse_each reverse_each_port
-
- # old #each_mail returns Port
- #def each_mail( &block )
- # each_port do |port|
- # yield Mail.new(port)
- # end
- #end
-
- def each_new_port( mtime = nil )
- close_check
- update
- @real.each_new_port(mtime) {|p| yield p }
- end
-
- def new_port
- close_check
- @real.new_port
- end
-
- private
-
- def close_check
- @closed and raise ArgumentError, 'accessing already closed mbox'
- end
-
- def update
- return if FileTest.zero?(@filename)
- return if @updated and File.mtime(@filename) < @updated
- w = nil
- port = nil
- time = nil
- UNIXMbox.lock(@filename) {|f|
- begin
- f.each do |line|
- if /\AFrom / === line
- w.close if w
- File.utime time, time, port.filename if time
-
- port = @real.new_port
- w = port.wopen
- time = fromline2time(line)
- else
- w.print line if w
- end
- end
- ensure
- if w and not w.closed?
- w.close
- File.utime time, time, port.filename if time
- end
- end
- f.truncate(0) unless @readonly
- @updated = Time.now
- }
- end
-
- def fromline2time( line )
- m = /\AFrom \S+ \w+ (\w+) (\d+) (\d+):(\d+):(\d+) (\d+)/.match(line) \
- or return nil
- Time.local(m[6].to_i, m[1], m[2].to_i, m[3].to_i, m[4].to_i, m[5].to_i)
- end
-
- end # UNIXMbox
-
- MboxLoader = UNIXMbox
-
-
- class Maildir
-
- extend Mutex_m
-
- PORT_CLASS = MaildirPort
-
- @seq = 0
- def Maildir.unique_number
- synchronize {
- @seq += 1
- return @seq
- }
- end
-
- def initialize( dir = nil )
- @dirname = dir || ENV['MAILDIR']
- raise ArgumentError, "not directory: #{@dirname}"\
- unless FileTest.directory? @dirname
- @new = "#{@dirname}/new"
- @tmp = "#{@dirname}/tmp"
- @cur = "#{@dirname}/cur"
- end
-
- def directory
- @dirname
- end
-
- def inspect
- "#<#{self.class} #{@dirname}>"
- end
-
- def close
- end
-
- def each_port
- mail_files(@cur).each do |path|
- yield PORT_CLASS.new(path)
- end
- end
-
- alias each each_port
-
- def reverse_each_port
- mail_files(@cur).reverse_each do |path|
- yield PORT_CLASS.new(path)
- end
- end
-
- alias reverse_each reverse_each_port
-
- def new_port
- fname = nil
- tmpfname = nil
- newfname = nil
-
- begin
- fname = "#{Time.now.to_i}.#{$$}_#{Maildir.unique_number}.#{Socket.gethostname}"
-
- tmpfname = "#{@tmp}/#{fname}"
- newfname = "#{@new}/#{fname}"
- end while FileTest.exist? tmpfname
-
- if block_given?
- File.open(tmpfname, 'w') {|f| yield f }
- File.rename tmpfname, newfname
- PORT_CLASS.new(newfname)
- else
- File.open(tmpfname, 'w') {|f| f.write "\n\n" }
- PORT_CLASS.new(tmpfname)
- end
- end
-
- def each_new_port
- mail_files(@new).each do |path|
- dest = @cur + '/' + File.basename(path)
- File.rename path, dest
- yield PORT_CLASS.new(dest)
- end
-
- check_tmp
- end
-
- TOO_OLD = 60 * 60 * 36 # 36 hour
-
- def check_tmp
- old = Time.now.to_i - TOO_OLD
-
- each_filename(@tmp) do |full, fname|
- if FileTest.file? full and
- File.stat(full).mtime.to_i < old
- File.unlink full
- end
- end
- end
-
- private
-
- def mail_files( dir )
- Dir.entries(dir)\
- .select {|s| s[0] != ?. }\
- .sort_by {|s| s.slice(/\A\d+/).to_i }\
- .map {|s| "#{dir}/#{s}" }\
- .select {|path| FileTest.file? path }
- end
-
- def each_filename( dir )
- Dir.foreach(dir) do |fname|
- path = "#{dir}/#{fname}"
- if fname[0] != ?. and FileTest.file? path
- yield path, fname
- end
- end
- end
-
- end # Maildir
-
- MaildirLoader = Maildir
-
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb
deleted file mode 100644
index e52772793f..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-#:stopdoc:
-require 'tmail/version'
-require 'tmail/mail'
-require 'tmail/mailbox'
-require 'tmail/core_extensions'
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb
deleted file mode 100644
index 6c0e251102..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-#:stopdoc:
-require 'tmail/mailbox'
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb
deleted file mode 100644
index 65147228a1..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb
+++ /dev/null
@@ -1,248 +0,0 @@
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-#:stopdoc:
-require 'nkf'
-#:startdoc:
-
-module TMail
-
- class Mail
-
- def send_to( smtp )
- do_send_to(smtp) do
- ready_to_send
- end
- end
-
- def send_text_to( smtp )
- do_send_to(smtp) do
- ready_to_send
- mime_encode
- end
- end
-
- def do_send_to( smtp )
- from = from_address or raise ArgumentError, 'no from address'
- (dests = destinations).empty? and raise ArgumentError, 'no receipient'
- yield
- send_to_0 smtp, from, dests
- end
- private :do_send_to
-
- def send_to_0( smtp, from, to )
- smtp.ready(from, to) do |f|
- encoded "\r\n", 'j', f, ''
- end
- end
-
- def ready_to_send
- delete_no_send_fields
- add_message_id
- add_date
- end
-
- NOSEND_FIELDS = %w(
- received
- bcc
- )
-
- def delete_no_send_fields
- NOSEND_FIELDS.each do |nm|
- delete nm
- end
- delete_if {|n,v| v.empty? }
- end
-
- def add_message_id( fqdn = nil )
- self.message_id = ::TMail::new_message_id(fqdn)
- end
-
- def add_date
- self.date = Time.now
- end
-
- def mime_encode
- if parts.empty?
- mime_encode_singlepart
- else
- mime_encode_multipart true
- end
- end
-
- def mime_encode_singlepart
- self.mime_version = '1.0'
- b = body
- if NKF.guess(b) != NKF::BINARY
- mime_encode_text b
- else
- mime_encode_binary b
- end
- end
-
- def mime_encode_text( body )
- self.body = NKF.nkf('-j -m0', body)
- self.set_content_type 'text', 'plain', {'charset' => 'iso-2022-jp'}
- self.encoding = '7bit'
- end
-
- def mime_encode_binary( body )
- self.body = [body].pack('m')
- self.set_content_type 'application', 'octet-stream'
- self.encoding = 'Base64'
- end
-
- def mime_encode_multipart( top = true )
- self.mime_version = '1.0' if top
- self.set_content_type 'multipart', 'mixed'
- e = encoding(nil)
- if e and not /\A(?:7bit|8bit|binary)\z/i === e
- raise ArgumentError,
- 'using C.T.Encoding with multipart mail is not permitted'
- end
- end
-
- end
-
- #:stopdoc:
- class DeleteFields
-
- NOSEND_FIELDS = %w(
- received
- bcc
- )
-
- def initialize( nosend = nil, delempty = true )
- @no_send_fields = nosend || NOSEND_FIELDS.dup
- @delete_empty_fields = delempty
- end
-
- attr :no_send_fields
- attr :delete_empty_fields, true
-
- def exec( mail )
- @no_send_fields.each do |nm|
- delete nm
- end
- delete_if {|n,v| v.empty? } if @delete_empty_fields
- end
-
- end
- #:startdoc:
-
- #:stopdoc:
- class AddMessageId
-
- def initialize( fqdn = nil )
- @fqdn = fqdn
- end
-
- attr :fqdn, true
-
- def exec( mail )
- mail.message_id = ::TMail::new_msgid(@fqdn)
- end
-
- end
- #:startdoc:
-
- #:stopdoc:
- class AddDate
-
- def exec( mail )
- mail.date = Time.now
- end
-
- end
- #:startdoc:
-
- #:stopdoc:
- class MimeEncodeAuto
-
- def initialize( s = nil, m = nil )
- @singlepart_composer = s || MimeEncodeSingle.new
- @multipart_composer = m || MimeEncodeMulti.new
- end
-
- attr :singlepart_composer
- attr :multipart_composer
-
- def exec( mail )
- if mail._builtin_multipart?
- then @multipart_composer
- else @singlepart_composer end.exec mail
- end
-
- end
- #:startdoc:
-
- #:stopdoc:
- class MimeEncodeSingle
-
- def exec( mail )
- mail.mime_version = '1.0'
- b = mail.body
- if NKF.guess(b) != NKF::BINARY
- on_text b
- else
- on_binary b
- end
- end
-
- def on_text( body )
- mail.body = NKF.nkf('-j -m0', body)
- mail.set_content_type 'text', 'plain', {'charset' => 'iso-2022-jp'}
- mail.encoding = '7bit'
- end
-
- def on_binary( body )
- mail.body = [body].pack('m')
- mail.set_content_type 'application', 'octet-stream'
- mail.encoding = 'Base64'
- end
-
- end
- #:startdoc:
-
- #:stopdoc:
- class MimeEncodeMulti
-
- def exec( mail, top = true )
- mail.mime_version = '1.0' if top
- mail.set_content_type 'multipart', 'mixed'
- e = encoding(nil)
- if e and not /\A(?:7bit|8bit|binary)\z/i === e
- raise ArgumentError,
- 'using C.T.Encoding with multipart mail is not permitted'
- end
- mail.parts.each do |m|
- exec m, false if m._builtin_multipart?
- end
- end
-
- end
- #:startdoc:
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb
deleted file mode 100644
index def663b233..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb
+++ /dev/null
@@ -1,132 +0,0 @@
-=begin rdoc
-
-= Obsolete methods that are deprecated
-
-If you really want to see them, go to lib/tmail/obsolete.rb and view to your
-heart's content.
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-#:stopdoc:
-module TMail #:nodoc:
-
- class Mail
- alias include? key?
- alias has_key? key?
-
- def values
- ret = []
- each_field {|v| ret.push v }
- ret
- end
-
- def value?( val )
- HeaderField === val or return false
-
- [ @header[val.name.downcase] ].flatten.include? val
- end
-
- alias has_value? value?
- end
-
- class Mail
- def from_addr( default = nil )
- addr, = from_addrs(nil)
- addr || default
- end
-
- def from_address( default = nil )
- if a = from_addr(nil)
- a.spec
- else
- default
- end
- end
-
- alias from_address= from_addrs=
-
- def from_phrase( default = nil )
- if a = from_addr(nil)
- a.phrase
- else
- default
- end
- end
-
- alias msgid message_id
- alias msgid= message_id=
-
- alias each_dest each_destination
- end
-
- class Address
- alias route routes
- alias addr spec
-
- def spec=( str )
- @local, @domain = str.split(/@/,2).map {|s| s.split(/\./) }
- end
-
- alias addr= spec=
- alias address= spec=
- end
-
- class MhMailbox
- alias new_mail new_port
- alias each_mail each_port
- alias each_newmail each_new_port
- end
- class UNIXMbox
- alias new_mail new_port
- alias each_mail each_port
- alias each_newmail each_new_port
- end
- class Maildir
- alias new_mail new_port
- alias each_mail each_port
- alias each_newmail each_new_port
- end
-
- extend TextUtils
-
- class << self
- alias msgid? message_id?
- alias boundary new_boundary
- alias msgid new_message_id
- alias new_msgid new_message_id
- end
-
- def Mail.boundary
- ::TMail.new_boundary
- end
-
- def Mail.msgid
- ::TMail.new_message_id
- end
-
-end # module TMail
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb
deleted file mode 100644
index 0ddc525213..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb
+++ /dev/null
@@ -1,1478 +0,0 @@
-#:stopdoc:
-# DO NOT MODIFY!!!!
-# This file is automatically generated by racc 1.4.5
-# from racc grammer file "parser.y".
-#
-#
-# parser.rb: generated by racc (runtime embedded)
-#
-###### racc/parser.rb begin
-unless $".index 'racc/parser.rb'
-$".push 'racc/parser.rb'
-
-self.class.module_eval <<'..end racc/parser.rb modeval..id8076474214', 'racc/parser.rb', 1
-#
-# $Id: parser.rb,v 1.7 2005/11/20 17:31:32 aamine Exp $
-#
-# Copyright (c) 1999-2005 Minero Aoki
-#
-# This program is free software.
-# You can distribute/modify this program under the same terms of ruby.
-#
-# As a special exception, when this code is copied by Racc
-# into a Racc output file, you may use that output file
-# without restriction.
-#
-
-unless defined?(NotImplementedError)
- NotImplementedError = NotImplementError
-end
-
-module Racc
- class ParseError < StandardError; end
-end
-unless defined?(::ParseError)
- ParseError = Racc::ParseError
-end
-
-module Racc
-
- unless defined?(Racc_No_Extentions)
- Racc_No_Extentions = false
- end
-
- class Parser
-
- old_verbose, $VERBOSE = $VERBOSE, nil
- Racc_Runtime_Version = '1.4.5'
- Racc_Runtime_Revision = '$Revision: 1.7 $'.split[1]
-
- Racc_Runtime_Core_Version_R = '1.4.5'
- Racc_Runtime_Core_Revision_R = '$Revision: 1.7 $'.split[1]
- begin
- require 'racc/cparse'
- # Racc_Runtime_Core_Version_C = (defined in extention)
- Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
- unless new.respond_to?(:_racc_do_parse_c, true)
- raise LoadError, 'old cparse.so'
- end
- if Racc_No_Extentions
- raise LoadError, 'selecting ruby version of racc runtime core'
- end
-
- Racc_Main_Parsing_Routine = :_racc_do_parse_c
- Racc_YY_Parse_Method = :_racc_yyparse_c
- Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
- Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
- Racc_Runtime_Type = 'c'
- rescue LoadError
- Racc_Main_Parsing_Routine = :_racc_do_parse_rb
- Racc_YY_Parse_Method = :_racc_yyparse_rb
- Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
- Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
- Racc_Runtime_Type = 'ruby'
- end
- $VERBOSE = old_verbose
-
- def Parser.racc_runtime_type
- Racc_Runtime_Type
- end
-
- private
-
- def _racc_setup
- @yydebug = false unless self.class::Racc_debug_parser
- @yydebug = false unless defined?(@yydebug)
- if @yydebug
- @racc_debug_out = $stderr unless defined?(@racc_debug_out)
- @racc_debug_out ||= $stderr
- end
- arg = self.class::Racc_arg
- arg[13] = true if arg.size < 14
- arg
- end
-
- def _racc_init_sysvars
- @racc_state = [0]
- @racc_tstack = []
- @racc_vstack = []
-
- @racc_t = nil
- @racc_val = nil
-
- @racc_read_next = true
-
- @racc_user_yyerror = false
- @racc_error_status = 0
- end
-
- ###
- ### do_parse
- ###
-
- def do_parse
- __send__(Racc_Main_Parsing_Routine, _racc_setup(), false)
- end
-
- def next_token
- raise NotImplementedError, "#{self.class}\#next_token is not defined"
- end
-
- def _racc_do_parse_rb(arg, in_debug)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
-
- _racc_init_sysvars
- tok = act = i = nil
- nerr = 0
-
- catch(:racc_end_parse) {
- while true
- if i = action_pointer[@racc_state[-1]]
- if @racc_read_next
- if @racc_t != 0 # not EOF
- tok, @racc_val = next_token()
- unless tok # EOF
- @racc_t = 0
- else
- @racc_t = (token_table[tok] or 1) # error token
- end
- racc_read_token(@racc_t, tok, @racc_val) if @yydebug
- @racc_read_next = false
- end
- end
- i += @racc_t
- unless i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
- end
- else
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
- end
- }
- end
-
- ###
- ### yyparse
- ###
-
- def yyparse(recv, mid)
- __send__(Racc_YY_Parse_Method, recv, mid, _racc_setup(), true)
- end
-
- def _racc_yyparse_rb(recv, mid, arg, c_debug)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
-
- _racc_init_sysvars
- tok = nil
- act = nil
- i = nil
- nerr = 0
-
- catch(:racc_end_parse) {
- until i = action_pointer[@racc_state[-1]]
- while act = _racc_evalact(action_default[@racc_state[-1]], arg)
- ;
- end
- end
- recv.__send__(mid) do |tok, val|
- unless tok
- @racc_t = 0
- else
- @racc_t = (token_table[tok] or 1) # error token
- end
- @racc_val = val
- @racc_read_next = false
-
- i += @racc_t
- unless i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
-
- while not (i = action_pointer[@racc_state[-1]]) or
- not @racc_read_next or
- @racc_t == 0 # $
- unless i and i += @racc_t and
- i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
- end
- end
- }
- end
-
- ###
- ### common
- ###
-
- def _racc_evalact(act, arg)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
- nerr = 0 # tmp
-
- if act > 0 and act < shift_n
- #
- # shift
- #
- if @racc_error_status > 0
- @racc_error_status -= 1 unless @racc_t == 1 # error token
- end
- @racc_vstack.push @racc_val
- @racc_state.push act
- @racc_read_next = true
- if @yydebug
- @racc_tstack.push @racc_t
- racc_shift @racc_t, @racc_tstack, @racc_vstack
- end
-
- elsif act < 0 and act > -reduce_n
- #
- # reduce
- #
- code = catch(:racc_jump) {
- @racc_state.push _racc_do_reduce(arg, act)
- false
- }
- if code
- case code
- when 1 # yyerror
- @racc_user_yyerror = true # user_yyerror
- return -reduce_n
- when 2 # yyaccept
- return shift_n
- else
- raise '[Racc Bug] unknown jump code'
- end
- end
-
- elsif act == shift_n
- #
- # accept
- #
- racc_accept if @yydebug
- throw :racc_end_parse, @racc_vstack[0]
-
- elsif act == -reduce_n
- #
- # error
- #
- case @racc_error_status
- when 0
- unless arg[21] # user_yyerror
- nerr += 1
- on_error @racc_t, @racc_val, @racc_vstack
- end
- when 3
- if @racc_t == 0 # is $
- throw :racc_end_parse, nil
- end
- @racc_read_next = true
- end
- @racc_user_yyerror = false
- @racc_error_status = 3
- while true
- if i = action_pointer[@racc_state[-1]]
- i += 1 # error token
- if i >= 0 and
- (act = action_table[i]) and
- action_check[i] == @racc_state[-1]
- break
- end
- end
- throw :racc_end_parse, nil if @racc_state.size <= 1
- @racc_state.pop
- @racc_vstack.pop
- if @yydebug
- @racc_tstack.pop
- racc_e_pop @racc_state, @racc_tstack, @racc_vstack
- end
- end
- return act
-
- else
- raise "[Racc Bug] unknown action #{act.inspect}"
- end
-
- racc_next_state(@racc_state[-1], @racc_state) if @yydebug
-
- nil
- end
-
- def _racc_do_reduce(arg, act)
- action_table, action_check, action_default, action_pointer,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, token_table, shift_n,
- reduce_n, use_result, * = arg
- state = @racc_state
- vstack = @racc_vstack
- tstack = @racc_tstack
-
- i = act * -3
- len = reduce_table[i]
- reduce_to = reduce_table[i+1]
- method_id = reduce_table[i+2]
- void_array = []
-
- tmp_t = tstack[-len, len] if @yydebug
- tmp_v = vstack[-len, len]
- tstack[-len, len] = void_array if @yydebug
- vstack[-len, len] = void_array
- state[-len, len] = void_array
-
- # tstack must be updated AFTER method call
- if use_result
- vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
- else
- vstack.push __send__(method_id, tmp_v, vstack)
- end
- tstack.push reduce_to
-
- racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
-
- k1 = reduce_to - nt_base
- if i = goto_pointer[k1]
- i += state[-1]
- if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
- return curstate
- end
- end
- goto_default[k1]
- end
-
- def on_error(t, val, vstack)
- raise ParseError, sprintf("\nparse error on value %s (%s)",
- val.inspect, token_to_str(t) || '?')
- end
-
- def yyerror
- throw :racc_jump, 1
- end
-
- def yyaccept
- throw :racc_jump, 2
- end
-
- def yyerrok
- @racc_error_status = 0
- end
-
- #
- # for debugging output
- #
-
- def racc_read_token(t, tok, val)
- @racc_debug_out.print 'read '
- @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
- @racc_debug_out.puts val.inspect
- @racc_debug_out.puts
- end
-
- def racc_shift(tok, tstack, vstack)
- @racc_debug_out.puts "shift #{racc_token2str tok}"
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
-
- def racc_reduce(toks, sim, tstack, vstack)
- out = @racc_debug_out
- out.print 'reduce '
- if toks.empty?
- out.print ' <none>'
- else
- toks.each {|t| out.print ' ', racc_token2str(t) }
- end
- out.puts " --> #{racc_token2str(sim)}"
-
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
-
- def racc_accept
- @racc_debug_out.puts 'accept'
- @racc_debug_out.puts
- end
-
- def racc_e_pop(state, tstack, vstack)
- @racc_debug_out.puts 'error recovering mode: pop token'
- racc_print_states state
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
-
- def racc_next_state(curstate, state)
- @racc_debug_out.puts "goto #{curstate}"
- racc_print_states state
- @racc_debug_out.puts
- end
-
- def racc_print_stacks(t, v)
- out = @racc_debug_out
- out.print ' ['
- t.each_index do |i|
- out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
- end
- out.puts ' ]'
- end
-
- def racc_print_states(s)
- out = @racc_debug_out
- out.print ' ['
- s.each {|st| out.print ' ', st }
- out.puts ' ]'
- end
-
- def racc_token2str(tok)
- self.class::Racc_token_to_s_table[tok] or
- raise "[Racc Bug] can't convert token #{tok} to string"
- end
-
- def token_to_str(t)
- self.class::Racc_token_to_s_table[t]
- end
-
- end
-
-end
-..end racc/parser.rb modeval..id8076474214
-end
-###### racc/parser.rb end
-
-
-#
-# parser.rb
-#
-# Copyright (c) 1998-2007 Minero Aoki
-#
-# This program is free software.
-# You can distribute/modify this program under the terms of
-# the GNU Lesser General Public License version 2.1.
-#
-
-require 'tmail/scanner'
-require 'tmail/utils'
-
-
-module TMail
-
- class Parser < Racc::Parser
-
-module_eval <<'..end parser.y modeval..id7b0b3dccb7', 'parser.y', 340
-
- include TextUtils
-
- def self.parse( ident, str, cmt = nil )
- new.parse(ident, str, cmt)
- end
-
- MAILP_DEBUG = false
-
- def initialize
- self.debug = MAILP_DEBUG
- end
-
- def debug=( flag )
- @yydebug = flag && Racc_debug_parser
- @scanner_debug = flag
- end
-
- def debug
- @yydebug
- end
-
- def parse( ident, str, comments = nil )
- @scanner = Scanner.new(str, ident, comments)
- @scanner.debug = @scanner_debug
- @first = [ident, ident]
- result = yyparse(self, :parse_in)
- comments.map! {|c| to_kcode(c) } if comments
- result
- end
-
- private
-
- def parse_in( &block )
- yield @first
- @scanner.scan(&block)
- end
-
- def on_error( t, val, vstack )
- raise SyntaxError, "parse error on token #{racc_token2str t}"
- end
-
-..end parser.y modeval..id7b0b3dccb7
-
-##### racc 1.4.5 generates ###
-
-racc_reduce_table = [
- 0, 0, :racc_error,
- 2, 35, :_reduce_1,
- 2, 35, :_reduce_2,
- 2, 35, :_reduce_3,
- 2, 35, :_reduce_4,
- 2, 35, :_reduce_5,
- 2, 35, :_reduce_6,
- 2, 35, :_reduce_7,
- 2, 35, :_reduce_8,
- 2, 35, :_reduce_9,
- 2, 35, :_reduce_10,
- 2, 35, :_reduce_11,
- 2, 35, :_reduce_12,
- 6, 36, :_reduce_13,
- 0, 48, :_reduce_none,
- 2, 48, :_reduce_none,
- 3, 49, :_reduce_16,
- 5, 49, :_reduce_17,
- 1, 50, :_reduce_18,
- 7, 37, :_reduce_19,
- 0, 51, :_reduce_none,
- 2, 51, :_reduce_21,
- 0, 52, :_reduce_none,
- 2, 52, :_reduce_23,
- 1, 58, :_reduce_24,
- 3, 58, :_reduce_25,
- 2, 58, :_reduce_26,
- 0, 53, :_reduce_none,
- 2, 53, :_reduce_28,
- 0, 54, :_reduce_29,
- 3, 54, :_reduce_30,
- 0, 55, :_reduce_none,
- 2, 55, :_reduce_32,
- 2, 55, :_reduce_33,
- 0, 56, :_reduce_none,
- 2, 56, :_reduce_35,
- 1, 61, :_reduce_36,
- 1, 61, :_reduce_37,
- 0, 57, :_reduce_none,
- 2, 57, :_reduce_39,
- 1, 38, :_reduce_none,
- 1, 38, :_reduce_none,
- 3, 38, :_reduce_none,
- 1, 46, :_reduce_none,
- 1, 46, :_reduce_none,
- 1, 46, :_reduce_none,
- 1, 39, :_reduce_none,
- 2, 39, :_reduce_47,
- 1, 64, :_reduce_48,
- 3, 64, :_reduce_49,
- 1, 68, :_reduce_none,
- 1, 68, :_reduce_none,
- 1, 69, :_reduce_52,
- 3, 69, :_reduce_53,
- 1, 47, :_reduce_none,
- 1, 47, :_reduce_none,
- 2, 47, :_reduce_56,
- 2, 67, :_reduce_none,
- 3, 65, :_reduce_58,
- 2, 65, :_reduce_59,
- 1, 70, :_reduce_60,
- 2, 70, :_reduce_61,
- 4, 62, :_reduce_62,
- 3, 62, :_reduce_63,
- 2, 72, :_reduce_none,
- 2, 73, :_reduce_65,
- 4, 73, :_reduce_66,
- 3, 63, :_reduce_67,
- 1, 63, :_reduce_68,
- 1, 74, :_reduce_none,
- 2, 74, :_reduce_70,
- 1, 71, :_reduce_71,
- 3, 71, :_reduce_72,
- 1, 59, :_reduce_73,
- 3, 59, :_reduce_74,
- 1, 76, :_reduce_75,
- 2, 76, :_reduce_76,
- 1, 75, :_reduce_none,
- 1, 75, :_reduce_none,
- 1, 75, :_reduce_none,
- 1, 77, :_reduce_none,
- 1, 77, :_reduce_none,
- 1, 77, :_reduce_none,
- 1, 66, :_reduce_none,
- 2, 66, :_reduce_none,
- 3, 60, :_reduce_85,
- 1, 40, :_reduce_86,
- 3, 40, :_reduce_87,
- 1, 79, :_reduce_none,
- 2, 79, :_reduce_89,
- 1, 41, :_reduce_90,
- 2, 41, :_reduce_91,
- 3, 42, :_reduce_92,
- 5, 43, :_reduce_93,
- 3, 43, :_reduce_94,
- 0, 80, :_reduce_95,
- 5, 80, :_reduce_96,
- 5, 80, :_reduce_97,
- 1, 44, :_reduce_98,
- 3, 45, :_reduce_99,
- 0, 81, :_reduce_none,
- 1, 81, :_reduce_none,
- 1, 78, :_reduce_none,
- 1, 78, :_reduce_none,
- 1, 78, :_reduce_none,
- 1, 78, :_reduce_none,
- 1, 78, :_reduce_none,
- 1, 78, :_reduce_none,
- 1, 78, :_reduce_none ]
-
-racc_reduce_n = 109
-
-racc_shift_n = 167
-
-racc_action_table = [
- -70, -69, 23, 25, 145, 146, 29, 31, 105, 106,
- 16, 17, 20, 22, 136, 27, -70, -69, 32, 101,
- -70, -69, 153, 100, 113, 115, -70, -69, -70, 109,
- 75, 23, 25, 101, 154, 29, 31, 142, 143, 16,
- 17, 20, 22, 107, 27, 23, 25, 32, 98, 29,
- 31, 96, 94, 16, 17, 20, 22, 78, 27, 23,
- 25, 32, 112, 29, 31, 74, 91, 16, 17, 20,
- 22, 88, 117, 92, 81, 32, 23, 25, 80, 123,
- 29, 31, 100, 125, 16, 17, 20, 22, 126, 23,
- 25, 109, 32, 29, 31, 91, 128, 16, 17, 20,
- 22, 129, 27, 23, 25, 32, 101, 29, 31, 101,
- 130, 16, 17, 20, 22, 79, 52, 23, 25, 32,
- 78, 29, 31, 133, 78, 16, 17, 20, 22, 77,
- 23, 25, 75, 32, 29, 31, 65, 62, 16, 17,
- 20, 22, 139, 23, 25, 101, 32, 29, 31, 60,
- 100, 16, 17, 20, 22, 44, 27, 101, 147, 32,
- 23, 25, 120, 148, 29, 31, 151, 152, 16, 17,
- 20, 22, 42, 27, 156, 158, 32, 23, 25, 120,
- 40, 29, 31, 15, 163, 16, 17, 20, 22, 40,
- 27, 23, 25, 32, 68, 29, 31, 165, 166, 16,
- 17, 20, 22, nil, 27, 23, 25, 32, nil, 29,
- 31, 74, nil, 16, 17, 20, 22, nil, 23, 25,
- nil, 32, 29, 31, nil, nil, 16, 17, 20, 22,
- nil, 23, 25, nil, 32, 29, 31, nil, nil, 16,
- 17, 20, 22, nil, 23, 25, nil, 32, 29, 31,
- nil, nil, 16, 17, 20, 22, nil, 23, 25, nil,
- 32, 29, 31, nil, nil, 16, 17, 20, 22, nil,
- 27, 23, 25, 32, nil, 29, 31, nil, nil, 16,
- 17, 20, 22, nil, 23, 25, nil, 32, 29, 31,
- nil, nil, 16, 17, 20, 22, nil, 23, 25, nil,
- 32, 29, 31, nil, nil, 16, 17, 20, 22, nil,
- 84, 25, nil, 32, 29, 31, nil, 87, 16, 17,
- 20, 22, 4, 6, 7, 8, 9, 10, 11, 12,
- 13, 1, 2, 3, 84, 25, nil, nil, 29, 31,
- nil, 87, 16, 17, 20, 22, 84, 25, nil, nil,
- 29, 31, nil, 87, 16, 17, 20, 22, 84, 25,
- nil, nil, 29, 31, nil, 87, 16, 17, 20, 22,
- 84, 25, nil, nil, 29, 31, nil, 87, 16, 17,
- 20, 22, 84, 25, nil, nil, 29, 31, nil, 87,
- 16, 17, 20, 22, 84, 25, nil, nil, 29, 31,
- nil, 87, 16, 17, 20, 22 ]
-
-racc_action_check = [
- 75, 28, 68, 68, 136, 136, 68, 68, 72, 72,
- 68, 68, 68, 68, 126, 68, 75, 28, 68, 67,
- 75, 28, 143, 66, 86, 86, 75, 28, 75, 75,
- 28, 3, 3, 86, 143, 3, 3, 134, 134, 3,
- 3, 3, 3, 73, 3, 151, 151, 3, 62, 151,
- 151, 60, 56, 151, 151, 151, 151, 51, 151, 52,
- 52, 151, 80, 52, 52, 52, 50, 52, 52, 52,
- 52, 45, 89, 52, 42, 52, 71, 71, 41, 96,
- 71, 71, 97, 98, 71, 71, 71, 71, 100, 7,
- 7, 101, 71, 7, 7, 102, 104, 7, 7, 7,
- 7, 105, 7, 8, 8, 7, 108, 8, 8, 111,
- 112, 8, 8, 8, 8, 40, 8, 9, 9, 8,
- 36, 9, 9, 117, 121, 9, 9, 9, 9, 33,
- 10, 10, 70, 9, 10, 10, 13, 12, 10, 10,
- 10, 10, 130, 2, 2, 131, 10, 2, 2, 11,
- 135, 2, 2, 2, 2, 6, 2, 138, 139, 2,
- 90, 90, 90, 140, 90, 90, 141, 142, 90, 90,
- 90, 90, 5, 90, 147, 150, 90, 127, 127, 127,
- 4, 127, 127, 1, 156, 127, 127, 127, 127, 158,
- 127, 26, 26, 127, 26, 26, 26, 162, 163, 26,
- 26, 26, 26, nil, 26, 27, 27, 26, nil, 27,
- 27, 27, nil, 27, 27, 27, 27, nil, 154, 154,
- nil, 27, 154, 154, nil, nil, 154, 154, 154, 154,
- nil, 122, 122, nil, 154, 122, 122, nil, nil, 122,
- 122, 122, 122, nil, 76, 76, nil, 122, 76, 76,
- nil, nil, 76, 76, 76, 76, nil, 38, 38, nil,
- 76, 38, 38, nil, nil, 38, 38, 38, 38, nil,
- 38, 55, 55, 38, nil, 55, 55, nil, nil, 55,
- 55, 55, 55, nil, 94, 94, nil, 55, 94, 94,
- nil, nil, 94, 94, 94, 94, nil, 59, 59, nil,
- 94, 59, 59, nil, nil, 59, 59, 59, 59, nil,
- 114, 114, nil, 59, 114, 114, nil, 114, 114, 114,
- 114, 114, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 77, 77, nil, nil, 77, 77,
- nil, 77, 77, 77, 77, 77, 44, 44, nil, nil,
- 44, 44, nil, 44, 44, 44, 44, 44, 113, 113,
- nil, nil, 113, 113, nil, 113, 113, 113, 113, 113,
- 88, 88, nil, nil, 88, 88, nil, 88, 88, 88,
- 88, 88, 74, 74, nil, nil, 74, 74, nil, 74,
- 74, 74, 74, 74, 129, 129, nil, nil, 129, 129,
- nil, 129, 129, 129, 129, 129 ]
-
-racc_action_pointer = [
- 320, 152, 129, 17, 165, 172, 137, 75, 89, 103,
- 116, 135, 106, 105, nil, nil, nil, nil, nil, nil,
- nil, nil, nil, nil, nil, nil, 177, 191, 1, nil,
- nil, nil, nil, 109, nil, nil, 94, nil, 243, nil,
- 99, 64, 74, nil, 332, 52, nil, nil, nil, nil,
- 50, 31, 45, nil, nil, 257, 36, nil, nil, 283,
- 22, nil, 16, nil, nil, nil, -3, -10, -12, nil,
- 103, 62, -8, 15, 368, 0, 230, 320, nil, nil,
- 47, nil, nil, nil, nil, nil, 4, nil, 356, 50,
- 146, nil, nil, nil, 270, nil, 65, 56, 52, nil,
- 57, 62, 79, nil, 68, 81, nil, nil, 77, nil,
- nil, 80, 96, 344, 296, nil, nil, 108, nil, nil,
- nil, 98, 217, nil, nil, nil, -19, 163, nil, 380,
- 128, 116, nil, nil, 14, 124, -26, nil, 128, 141,
- 148, 141, 152, 7, nil, nil, nil, 160, nil, nil,
- 149, 31, nil, nil, 204, nil, 167, nil, 174, nil,
- nil, nil, 169, 184, nil, nil, nil ]
-
-racc_action_default = [
- -109, -109, -109, -109, -14, -109, -20, -109, -109, -109,
- -109, -109, -109, -109, -10, -95, -105, -106, -77, -44,
- -107, -11, -108, -79, -43, -102, -109, -109, -60, -103,
- -55, -104, -78, -68, -54, -71, -45, -12, -109, -1,
- -109, -109, -109, -2, -109, -22, -51, -48, -50, -3,
- -40, -41, -109, -46, -4, -86, -5, -88, -6, -90,
- -109, -7, -95, -8, -9, -98, -100, -61, -59, -56,
- -69, -109, -109, -109, -109, -75, -109, -109, -57, -15,
- -109, 167, -73, -80, -82, -21, -24, -81, -109, -27,
- -109, -83, -47, -89, -109, -91, -109, -100, -109, -99,
- -101, -75, -58, -52, -109, -109, -64, -63, -65, -76,
- -72, -67, -109, -109, -109, -26, -23, -109, -29, -49,
- -84, -42, -87, -92, -94, -95, -109, -109, -62, -109,
- -109, -25, -74, -28, -31, -100, -109, -53, -66, -109,
- -109, -34, -109, -109, -93, -96, -97, -109, -18, -13,
- -38, -109, -30, -33, -109, -32, -16, -19, -14, -35,
- -36, -37, -109, -109, -39, -85, -17 ]
-
-racc_goto_table = [
- 39, 67, 70, 73, 38, 66, 69, 24, 37, 57,
- 59, 36, 55, 67, 99, 90, 85, 157, 69, 108,
- 83, 134, 111, 76, 49, 53, 141, 70, 73, 150,
- 118, 89, 45, 155, 159, 149, 140, 21, 14, 19,
- 119, 102, 64, 63, 61, 124, 70, 104, 58, 132,
- 83, 56, 97, 83, 54, 93, 43, 5, 131, 95,
- 116, nil, 76, nil, 83, 76, nil, 127, nil, 38,
- nil, nil, nil, 103, 138, nil, 110, nil, nil, nil,
- nil, nil, nil, 144, nil, nil, nil, nil, nil, 83,
- 83, nil, nil, nil, 57, nil, nil, 122, nil, 121,
- nil, nil, nil, nil, nil, 83, nil, nil, nil, nil,
- nil, nil, nil, nil, nil, 135, nil, nil, nil, nil,
- nil, nil, 93, nil, nil, nil, 70, 161, 38, 70,
- 162, 160, 137, nil, nil, nil, nil, nil, nil, nil,
- nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
- nil, nil, nil, nil, 164 ]
-
-racc_goto_check = [
- 2, 37, 37, 29, 36, 46, 28, 13, 13, 41,
- 41, 31, 45, 37, 47, 32, 24, 23, 28, 25,
- 44, 20, 25, 42, 4, 4, 21, 37, 29, 22,
- 19, 18, 17, 26, 27, 16, 15, 12, 11, 33,
- 34, 35, 10, 9, 8, 47, 37, 29, 7, 43,
- 44, 6, 46, 44, 5, 41, 3, 1, 25, 41,
- 24, nil, 42, nil, 44, 42, nil, 32, nil, 36,
- nil, nil, nil, 13, 25, nil, 41, nil, nil, nil,
- nil, nil, nil, 47, nil, nil, nil, nil, nil, 44,
- 44, nil, nil, nil, 41, nil, nil, 45, nil, 31,
- nil, nil, nil, nil, nil, 44, nil, nil, nil, nil,
- nil, nil, nil, nil, nil, 46, nil, nil, nil, nil,
- nil, nil, 41, nil, nil, nil, 37, 29, 36, 37,
- 29, 28, 13, nil, nil, nil, nil, nil, nil, nil,
- nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
- nil, nil, nil, nil, 2 ]
-
-racc_goto_pointer = [
- nil, 57, -4, 50, 17, 46, 42, 38, 33, 31,
- 29, 37, 35, 5, nil, -94, -105, 26, -14, -59,
- -97, -108, -112, -133, -28, -55, -110, -117, -20, -24,
- nil, 9, -35, 37, -50, -27, 1, -25, nil, nil,
- nil, 0, -5, -65, -24, 3, -10, -52 ]
-
-racc_goto_default = [
- nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
- nil, nil, nil, 48, 41, nil, nil, nil, nil, nil,
- nil, nil, nil, nil, nil, 86, nil, nil, 30, 34,
- 50, 51, nil, 46, 47, nil, 26, 28, 71, 72,
- 33, 35, 114, 82, 18, nil, nil, nil ]
-
-racc_token_table = {
- false => 0,
- Object.new => 1,
- :DATETIME => 2,
- :RECEIVED => 3,
- :MADDRESS => 4,
- :RETPATH => 5,
- :KEYWORDS => 6,
- :ENCRYPTED => 7,
- :MIMEVERSION => 8,
- :CTYPE => 9,
- :CENCODING => 10,
- :CDISPOSITION => 11,
- :ADDRESS => 12,
- :MAILBOX => 13,
- :DIGIT => 14,
- :ATOM => 15,
- "," => 16,
- ":" => 17,
- :FROM => 18,
- :BY => 19,
- "@" => 20,
- :DOMLIT => 21,
- :VIA => 22,
- :WITH => 23,
- :ID => 24,
- :FOR => 25,
- ";" => 26,
- "<" => 27,
- ">" => 28,
- "." => 29,
- :QUOTED => 30,
- :TOKEN => 31,
- "/" => 32,
- "=" => 33 }
-
-racc_use_result_var = false
-
-racc_nt_base = 34
-
-Racc_arg = [
- racc_action_table,
- racc_action_check,
- racc_action_default,
- racc_action_pointer,
- racc_goto_table,
- racc_goto_check,
- racc_goto_default,
- racc_goto_pointer,
- racc_nt_base,
- racc_reduce_table,
- racc_token_table,
- racc_shift_n,
- racc_reduce_n,
- racc_use_result_var ]
-
-Racc_token_to_s_table = [
-'$end',
-'error',
-'DATETIME',
-'RECEIVED',
-'MADDRESS',
-'RETPATH',
-'KEYWORDS',
-'ENCRYPTED',
-'MIMEVERSION',
-'CTYPE',
-'CENCODING',
-'CDISPOSITION',
-'ADDRESS',
-'MAILBOX',
-'DIGIT',
-'ATOM',
-'","',
-'":"',
-'FROM',
-'BY',
-'"@"',
-'DOMLIT',
-'VIA',
-'WITH',
-'ID',
-'FOR',
-'";"',
-'"<"',
-'">"',
-'"."',
-'QUOTED',
-'TOKEN',
-'"/"',
-'"="',
-'$start',
-'content',
-'datetime',
-'received',
-'addrs_TOP',
-'retpath',
-'keys',
-'enc',
-'version',
-'ctype',
-'cencode',
-'cdisp',
-'addr_TOP',
-'mbox',
-'day',
-'hour',
-'zone',
-'from',
-'by',
-'via',
-'with',
-'id',
-'for',
-'received_datetime',
-'received_domain',
-'domain',
-'msgid',
-'received_addrspec',
-'routeaddr',
-'spec',
-'addrs',
-'group_bare',
-'commas',
-'group',
-'addr',
-'mboxes',
-'addr_phrase',
-'local_head',
-'routes',
-'at_domains',
-'local',
-'word',
-'dots',
-'domword',
-'atom',
-'phrase',
-'params',
-'opt_semicolon']
-
-Racc_debug_parser = false
-
-##### racc system variables end #####
-
- # reduce 0 omitted
-
-module_eval <<'.,.,', 'parser.y', 16
- def _reduce_1( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 17
- def _reduce_2( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 18
- def _reduce_3( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 19
- def _reduce_4( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 20
- def _reduce_5( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 21
- def _reduce_6( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 22
- def _reduce_7( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 23
- def _reduce_8( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 24
- def _reduce_9( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 25
- def _reduce_10( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 26
- def _reduce_11( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 27
- def _reduce_12( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 36
- def _reduce_13( val, _values)
- t = Time.gm(val[3].to_i, val[2], val[1].to_i, 0, 0, 0)
- (t + val[4] - val[5]).localtime
- end
-.,.,
-
- # reduce 14 omitted
-
- # reduce 15 omitted
-
-module_eval <<'.,.,', 'parser.y', 45
- def _reduce_16( val, _values)
- (val[0].to_i * 60 * 60) +
- (val[2].to_i * 60)
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 51
- def _reduce_17( val, _values)
- (val[0].to_i * 60 * 60) +
- (val[2].to_i * 60) +
- (val[4].to_i)
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 56
- def _reduce_18( val, _values)
- timezone_string_to_unixtime(val[0])
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 61
- def _reduce_19( val, _values)
- val
- end
-.,.,
-
- # reduce 20 omitted
-
-module_eval <<'.,.,', 'parser.y', 67
- def _reduce_21( val, _values)
- val[1]
- end
-.,.,
-
- # reduce 22 omitted
-
-module_eval <<'.,.,', 'parser.y', 73
- def _reduce_23( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 79
- def _reduce_24( val, _values)
- join_domain(val[0])
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 83
- def _reduce_25( val, _values)
- join_domain(val[2])
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 87
- def _reduce_26( val, _values)
- join_domain(val[0])
- end
-.,.,
-
- # reduce 27 omitted
-
-module_eval <<'.,.,', 'parser.y', 93
- def _reduce_28( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 98
- def _reduce_29( val, _values)
- []
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 103
- def _reduce_30( val, _values)
- val[0].push val[2]
- val[0]
- end
-.,.,
-
- # reduce 31 omitted
-
-module_eval <<'.,.,', 'parser.y', 109
- def _reduce_32( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 113
- def _reduce_33( val, _values)
- val[1]
- end
-.,.,
-
- # reduce 34 omitted
-
-module_eval <<'.,.,', 'parser.y', 119
- def _reduce_35( val, _values)
- val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 125
- def _reduce_36( val, _values)
- val[0].spec
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 129
- def _reduce_37( val, _values)
- val[0].spec
- end
-.,.,
-
- # reduce 38 omitted
-
-module_eval <<'.,.,', 'parser.y', 136
- def _reduce_39( val, _values)
- val[1]
- end
-.,.,
-
- # reduce 40 omitted
-
- # reduce 41 omitted
-
- # reduce 42 omitted
-
- # reduce 43 omitted
-
- # reduce 44 omitted
-
- # reduce 45 omitted
-
- # reduce 46 omitted
-
-module_eval <<'.,.,', 'parser.y', 146
- def _reduce_47( val, _values)
- [ Address.new(nil, nil) ]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 152
- def _reduce_48( val, _values)
- val
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 157
- def _reduce_49( val, _values)
- val[0].push val[2]
- val[0]
- end
-.,.,
-
- # reduce 50 omitted
-
- # reduce 51 omitted
-
-module_eval <<'.,.,', 'parser.y', 165
- def _reduce_52( val, _values)
- val
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 170
- def _reduce_53( val, _values)
- val[0].push val[2]
- val[0]
- end
-.,.,
-
- # reduce 54 omitted
-
- # reduce 55 omitted
-
-module_eval <<'.,.,', 'parser.y', 178
- def _reduce_56( val, _values)
- val[1].phrase = Decoder.decode(val[0])
- val[1]
- end
-.,.,
-
- # reduce 57 omitted
-
-module_eval <<'.,.,', 'parser.y', 185
- def _reduce_58( val, _values)
- AddressGroup.new(val[0], val[2])
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 185
- def _reduce_59( val, _values)
- AddressGroup.new(val[0], [])
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 188
- def _reduce_60( val, _values)
- val[0].join('.')
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 189
- def _reduce_61( val, _values)
- val[0] << ' ' << val[1].join('.')
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 196
- def _reduce_62( val, _values)
- val[2].routes.replace val[1]
- val[2]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 200
- def _reduce_63( val, _values)
- val[1]
- end
-.,.,
-
- # reduce 64 omitted
-
-module_eval <<'.,.,', 'parser.y', 203
- def _reduce_65( val, _values)
- [ val[1].join('.') ]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 204
- def _reduce_66( val, _values)
- val[0].push val[3].join('.'); val[0]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 206
- def _reduce_67( val, _values)
- Address.new( val[0], val[2] )
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 207
- def _reduce_68( val, _values)
- Address.new( val[0], nil )
- end
-.,.,
-
- # reduce 69 omitted
-
-module_eval <<'.,.,', 'parser.y', 210
- def _reduce_70( val, _values)
- val[0].push ''; val[0]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 213
- def _reduce_71( val, _values)
- val
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 222
- def _reduce_72( val, _values)
- val[1].times do
- val[0].push ''
- end
- val[0].push val[2]
- val[0]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 224
- def _reduce_73( val, _values)
- val
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 233
- def _reduce_74( val, _values)
- val[1].times do
- val[0].push ''
- end
- val[0].push val[2]
- val[0]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 234
- def _reduce_75( val, _values)
- 0
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 235
- def _reduce_76( val, _values)
- 1
- end
-.,.,
-
- # reduce 77 omitted
-
- # reduce 78 omitted
-
- # reduce 79 omitted
-
- # reduce 80 omitted
-
- # reduce 81 omitted
-
- # reduce 82 omitted
-
- # reduce 83 omitted
-
- # reduce 84 omitted
-
-module_eval <<'.,.,', 'parser.y', 253
- def _reduce_85( val, _values)
- val[1] = val[1].spec
- val.join('')
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 254
- def _reduce_86( val, _values)
- val
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 255
- def _reduce_87( val, _values)
- val[0].push val[2]; val[0]
- end
-.,.,
-
- # reduce 88 omitted
-
-module_eval <<'.,.,', 'parser.y', 258
- def _reduce_89( val, _values)
- val[0] << ' ' << val[1]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 265
- def _reduce_90( val, _values)
- val.push nil
- val
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 269
- def _reduce_91( val, _values)
- val
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 274
- def _reduce_92( val, _values)
- [ val[0].to_i, val[2].to_i ]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 279
- def _reduce_93( val, _values)
- [ val[0].downcase, val[2].downcase, decode_params(val[3]) ]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 283
- def _reduce_94( val, _values)
- [ val[0].downcase, nil, decode_params(val[1]) ]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 288
- def _reduce_95( val, _values)
- {}
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 293
- def _reduce_96( val, _values)
- val[0][ val[2].downcase ] = ('"' + val[4].to_s + '"')
- val[0]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 298
- def _reduce_97( val, _values)
- val[0][ val[2].downcase ] = val[4]
- val[0]
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 303
- def _reduce_98( val, _values)
- val[0].downcase
- end
-.,.,
-
-module_eval <<'.,.,', 'parser.y', 308
- def _reduce_99( val, _values)
- [ val[0].downcase, decode_params(val[1]) ]
- end
-.,.,
-
- # reduce 100 omitted
-
- # reduce 101 omitted
-
- # reduce 102 omitted
-
- # reduce 103 omitted
-
- # reduce 104 omitted
-
- # reduce 105 omitted
-
- # reduce 106 omitted
-
- # reduce 107 omitted
-
- # reduce 108 omitted
-
- def _reduce_none( val, _values)
- val[0]
- end
-
- end # class Parser
-
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb
deleted file mode 100644
index 445f0e632b..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb
+++ /dev/null
@@ -1,379 +0,0 @@
-=begin rdoc
-
-= Port class
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-require 'tmail/stringio'
-
-
-module TMail
-
- class Port
- def reproducible?
- false
- end
- end
-
-
- ###
- ### FilePort
- ###
-
- class FilePort < Port
-
- def initialize( fname )
- @filename = File.expand_path(fname)
- super()
- end
-
- attr_reader :filename
-
- alias ident filename
-
- def ==( other )
- other.respond_to?(:filename) and @filename == other.filename
- end
-
- alias eql? ==
-
- def hash
- @filename.hash
- end
-
- def inspect
- "#<#{self.class}:#{@filename}>"
- end
-
- def reproducible?
- true
- end
-
- def size
- File.size @filename
- end
-
-
- def ropen( &block )
- File.open(@filename, &block)
- end
-
- def wopen( &block )
- File.open(@filename, 'w', &block)
- end
-
- def aopen( &block )
- File.open(@filename, 'a', &block)
- end
-
-
- def read_all
- ropen {|f|
- return f.read
- }
- end
-
-
- def remove
- File.unlink @filename
- end
-
- def move_to( port )
- begin
- File.link @filename, port.filename
- rescue Errno::EXDEV
- copy_to port
- end
- File.unlink @filename
- end
-
- alias mv move_to
-
- def copy_to( port )
- if FilePort === port
- copy_file @filename, port.filename
- else
- File.open(@filename) {|r|
- port.wopen {|w|
- while s = r.sysread(4096)
- w.write << s
- end
- } }
- end
- end
-
- alias cp copy_to
-
- private
-
- # from fileutils.rb
- def copy_file( src, dest )
- st = r = w = nil
-
- File.open(src, 'rb') {|r|
- File.open(dest, 'wb') {|w|
- st = r.stat
- begin
- while true
- w.write r.sysread(st.blksize)
- end
- rescue EOFError
- end
- } }
- end
-
- end
-
-
- module MailFlags
-
- def seen=( b )
- set_status 'S', b
- end
-
- def seen?
- get_status 'S'
- end
-
- def replied=( b )
- set_status 'R', b
- end
-
- def replied?
- get_status 'R'
- end
-
- def flagged=( b )
- set_status 'F', b
- end
-
- def flagged?
- get_status 'F'
- end
-
- private
-
- def procinfostr( str, tag, true_p )
- a = str.upcase.split(//)
- a.push true_p ? tag : nil
- a.delete tag unless true_p
- a.compact.sort.join('').squeeze
- end
-
- end
-
-
- class MhPort < FilePort
-
- include MailFlags
-
- private
-
- def set_status( tag, flag )
- begin
- tmpfile = @filename + '.tmailtmp.' + $$.to_s
- File.open(tmpfile, 'w') {|f|
- write_status f, tag, flag
- }
- File.unlink @filename
- File.link tmpfile, @filename
- ensure
- File.unlink tmpfile
- end
- end
-
- def write_status( f, tag, flag )
- stat = ''
- File.open(@filename) {|r|
- while line = r.gets
- if line.strip.empty?
- break
- elsif m = /\AX-TMail-Status:/i.match(line)
- stat = m.post_match.strip
- else
- f.print line
- end
- end
-
- s = procinfostr(stat, tag, flag)
- f.puts 'X-TMail-Status: ' + s unless s.empty?
- f.puts
-
- while s = r.read(2048)
- f.write s
- end
- }
- end
-
- def get_status( tag )
- File.foreach(@filename) {|line|
- return false if line.strip.empty?
- if m = /\AX-TMail-Status:/i.match(line)
- return m.post_match.strip.include?(tag[0])
- end
- }
- false
- end
-
- end
-
-
- class MaildirPort < FilePort
-
- def move_to_new
- new = replace_dir(@filename, 'new')
- File.rename @filename, new
- @filename = new
- end
-
- def move_to_cur
- new = replace_dir(@filename, 'cur')
- File.rename @filename, new
- @filename = new
- end
-
- def replace_dir( path, dir )
- "#{File.dirname File.dirname(path)}/#{dir}/#{File.basename path}"
- end
- private :replace_dir
-
-
- include MailFlags
-
- private
-
- MAIL_FILE = /\A(\d+\.[\d_]+\.[^:]+)(?:\:(\d),(\w+)?)?\z/
-
- def set_status( tag, flag )
- if m = MAIL_FILE.match(File.basename(@filename))
- s, uniq, type, info, = m.to_a
- return if type and type != '2' # do not change anything
- newname = File.dirname(@filename) + '/' +
- uniq + ':2,' + procinfostr(info.to_s, tag, flag)
- else
- newname = @filename + ':2,' + tag
- end
-
- File.link @filename, newname
- File.unlink @filename
- @filename = newname
- end
-
- def get_status( tag )
- m = MAIL_FILE.match(File.basename(@filename)) or return false
- m[2] == '2' and m[3].to_s.include?(tag[0])
- end
-
- end
-
-
- ###
- ### StringPort
- ###
-
- class StringPort < Port
-
- def initialize( str = '' )
- @buffer = str
- super()
- end
-
- def string
- @buffer
- end
-
- def to_s
- @buffer.dup
- end
-
- alias read_all to_s
-
- def size
- @buffer.size
- end
-
- def ==( other )
- StringPort === other and @buffer.equal? other.string
- end
-
- alias eql? ==
-
- def hash
- @buffer.object_id.hash
- end
-
- def inspect
- "#<#{self.class}:id=#{sprintf '0x%x', @buffer.object_id}>"
- end
-
- def reproducible?
- true
- end
-
- def ropen( &block )
- @buffer or raise Errno::ENOENT, "#{inspect} is already removed"
- StringInput.open(@buffer, &block)
- end
-
- def wopen( &block )
- @buffer = ''
- StringOutput.new(@buffer, &block)
- end
-
- def aopen( &block )
- @buffer ||= ''
- StringOutput.new(@buffer, &block)
- end
-
- def remove
- @buffer = nil
- end
-
- alias rm remove
-
- def copy_to( port )
- port.wopen {|f|
- f.write @buffer
- }
- end
-
- alias cp copy_to
-
- def move_to( port )
- if StringPort === port
- str = @buffer
- port.instance_eval { @buffer = str }
- else
- copy_to port
- end
- remove
- end
-
- end
-
-end # module TMail
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb
deleted file mode 100644
index cb9f4288f1..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb
+++ /dev/null
@@ -1,118 +0,0 @@
-=begin rdoc
-
-= Quoting methods
-
-=end
-module TMail
- class Mail
- def subject(to_charset = 'utf-8')
- Unquoter.unquote_and_convert_to(quoted_subject, to_charset)
- end
-
- def unquoted_body(to_charset = 'utf-8')
- from_charset = sub_header("content-type", "charset")
- case (content_transfer_encoding || "7bit").downcase
- when "quoted-printable"
- # the default charset is set to iso-8859-1 instead of 'us-ascii'.
- # This is needed as many mailer do not set the charset but send in ISO. This is only used if no charset is set.
- if !from_charset.blank? && from_charset.downcase == 'us-ascii'
- from_charset = 'iso-8859-1'
- end
-
- Unquoter.unquote_quoted_printable_and_convert_to(quoted_body,
- to_charset, from_charset, true)
- when "base64"
- Unquoter.unquote_base64_and_convert_to(quoted_body, to_charset,
- from_charset)
- when "7bit", "8bit"
- Unquoter.convert_to(quoted_body, to_charset, from_charset)
- when "binary"
- quoted_body
- else
- quoted_body
- end
- end
-
- def body(to_charset = 'utf-8', &block)
- attachment_presenter = block || Proc.new { |file_name| "Attachment: #{file_name}\n" }
-
- if multipart?
- parts.collect { |part|
- header = part["content-type"]
-
- if part.multipart?
- part.body(to_charset, &attachment_presenter)
- elsif header.nil?
- ""
- elsif !attachment?(part)
- part.unquoted_body(to_charset)
- else
- attachment_presenter.call(header["name"] || "(unnamed)")
- end
- }.join
- else
- unquoted_body(to_charset)
- end
- end
- end
-
- class Unquoter
- class << self
- def unquote_and_convert_to(text, to_charset, from_charset = "iso-8859-1", preserve_underscores=false)
- return "" if text.nil?
- text.gsub(/(.*?)(?:(?:=\?(.*?)\?(.)\?(.*?)\?=)|$)/) do
- before = $1
- from_charset = $2
- quoting_method = $3
- text = $4
-
- before = convert_to(before, to_charset, from_charset) if before.length > 0
- before + case quoting_method
- when "q", "Q" then
- unquote_quoted_printable_and_convert_to(text, to_charset, from_charset, preserve_underscores)
- when "b", "B" then
- unquote_base64_and_convert_to(text, to_charset, from_charset)
- when nil then
- # will be nil at the end of the string, due to the nature of
- # the regex used.
- ""
- else
- raise "unknown quoting method #{quoting_method.inspect}"
- end
- end
- end
-
- def unquote_quoted_printable_and_convert_to(text, to, from, preserve_underscores=false)
- text = text.gsub(/_/, " ") unless preserve_underscores
- text = text.gsub(/\r\n|\r/, "\n") # normalize newlines
- convert_to(text.unpack("M*").first, to, from)
- end
-
- def unquote_base64_and_convert_to(text, to, from)
- convert_to(Base64.decode(text), to, from)
- end
-
- begin
- require 'iconv'
- def convert_to(text, to, from)
- return text unless to && from
- text ? Iconv.iconv(to, from, text).first : ""
- rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
- # the 'from' parameter specifies a charset other than what the text
- # actually is...not much we can do in this case but just return the
- # unconverted text.
- #
- # Ditto if either parameter represents an unknown charset, like
- # X-UNKNOWN.
- text
- end
- rescue LoadError
- # Not providing quoting support
- def convert_to(text, to, from)
- warn "Action Mailer: iconv not loaded; ignoring conversion from #{from} to #{to} (#{__FILE__}:#{__LINE__})"
- text
- end
- end
- end
- end
-end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb
deleted file mode 100644
index b4fffb8abb..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb
+++ /dev/null
@@ -1,58 +0,0 @@
-#:stopdoc:
-require 'rbconfig'
-
-# Attempts to require anative extension.
-# Falls back to pure-ruby version, if it fails.
-#
-# This uses Config::CONFIG['arch'] from rbconfig.
-
-def require_arch(fname)
- arch = Config::CONFIG['arch']
- begin
- path = File.join("tmail", arch, fname)
- require path
- rescue LoadError => e
- # try pre-built Windows binaries
- if arch =~ /mswin/
- require File.join("tmail", 'mswin32', fname)
- else
- raise e
- end
- end
-end
-
-
-# def require_arch(fname)
-# dext = Config::CONFIG['DLEXT']
-# begin
-# if File.extname(fname) == dext
-# path = fname
-# else
-# path = File.join("tmail","#{fname}.#{dext}")
-# end
-# require path
-# rescue LoadError => e
-# begin
-# arch = Config::CONFIG['arch']
-# path = File.join("tmail", arch, "#{fname}.#{dext}")
-# require path
-# rescue LoadError
-# case path
-# when /i686/
-# path.sub!('i686', 'i586')
-# when /i586/
-# path.sub!('i586', 'i486')
-# when /i486/
-# path.sub!('i486', 'i386')
-# else
-# begin
-# require fname + '.rb'
-# rescue LoadError
-# raise e
-# end
-# end
-# retry
-# end
-# end
-# end
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb
deleted file mode 100644
index a5d01396b8..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-=begin rdoc
-
-= Scanner for TMail
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-#:stopdoc:
-#require 'tmail/require_arch'
-require 'tmail/utils'
-require 'tmail/config'
-
-module TMail
- # NOTE: It woiuld be nice if these two libs could boith be called "tmailscanner", and
- # the native extension would have precedence. However RubyGems boffs that up b/c
- # it does not gaurantee load_path order.
- begin
- raise LoadError, 'Turned off native extentions by user choice' if ENV['NORUBYEXT']
- require('tmail/tmailscanner') # c extension
- Scanner = TMailScanner
- rescue LoadError
- require 'tmail/scanner_r'
- Scanner = TMailScanner
- end
-end
-#:stopdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb
deleted file mode 100644
index f2075502d8..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb
+++ /dev/null
@@ -1,261 +0,0 @@
-# scanner_r.rb
-#
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-#:stopdoc:
-require 'tmail/config'
-
-module TMail
-
- class TMailScanner
-
- Version = '1.2.3'
- Version.freeze
-
- MIME_HEADERS = {
- :CTYPE => true,
- :CENCODING => true,
- :CDISPOSITION => true
- }
-
- alnum = 'a-zA-Z0-9'
- atomsyms = %q[ _#!$%&`'*+-{|}~^/=? ].strip
- tokensyms = %q[ _#!$%&`'*+-{|}~^@. ].strip
- atomchars = alnum + Regexp.quote(atomsyms)
- tokenchars = alnum + Regexp.quote(tokensyms)
- iso2022str = '\e(?!\(B)..(?:[^\e]+|\e(?!\(B)..)*\e\(B'
-
- eucstr = "(?:[\xa1-\xfe][\xa1-\xfe])+"
- sjisstr = "(?:[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc])+"
- utf8str = "(?:[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf])+"
-
- quoted_with_iso2022 = /\A(?:[^\\\e"]+|#{iso2022str})+/n
- domlit_with_iso2022 = /\A(?:[^\\\e\]]+|#{iso2022str})+/n
- comment_with_iso2022 = /\A(?:[^\\\e()]+|#{iso2022str})+/n
-
- quoted_without_iso2022 = /\A[^\\"]+/n
- domlit_without_iso2022 = /\A[^\\\]]+/n
- comment_without_iso2022 = /\A[^\\()]+/n
-
- PATTERN_TABLE = {}
- PATTERN_TABLE['EUC'] =
- [
- /\A(?:[#{atomchars}]+|#{iso2022str}|#{eucstr})+/n,
- /\A(?:[#{tokenchars}]+|#{iso2022str}|#{eucstr})+/n,
- quoted_with_iso2022,
- domlit_with_iso2022,
- comment_with_iso2022
- ]
- PATTERN_TABLE['SJIS'] =
- [
- /\A(?:[#{atomchars}]+|#{iso2022str}|#{sjisstr})+/n,
- /\A(?:[#{tokenchars}]+|#{iso2022str}|#{sjisstr})+/n,
- quoted_with_iso2022,
- domlit_with_iso2022,
- comment_with_iso2022
- ]
- PATTERN_TABLE['UTF8'] =
- [
- /\A(?:[#{atomchars}]+|#{utf8str})+/n,
- /\A(?:[#{tokenchars}]+|#{utf8str})+/n,
- quoted_without_iso2022,
- domlit_without_iso2022,
- comment_without_iso2022
- ]
- PATTERN_TABLE['NONE'] =
- [
- /\A[#{atomchars}]+/n,
- /\A[#{tokenchars}]+/n,
- quoted_without_iso2022,
- domlit_without_iso2022,
- comment_without_iso2022
- ]
-
-
- def initialize( str, scantype, comments )
- init_scanner str
- @comments = comments || []
- @debug = false
-
- # fix scanner mode
- @received = (scantype == :RECEIVED)
- @is_mime_header = MIME_HEADERS[scantype]
-
- atom, token, @quoted_re, @domlit_re, @comment_re = PATTERN_TABLE[TMail.KCODE]
- @word_re = (MIME_HEADERS[scantype] ? token : atom)
- end
-
- attr_accessor :debug
-
- def scan( &block )
- if @debug
- scan_main do |arr|
- s, v = arr
- printf "%7d %-10s %s\n",
- rest_size(),
- s.respond_to?(:id2name) ? s.id2name : s.inspect,
- v.inspect
- yield arr
- end
- else
- scan_main(&block)
- end
- end
-
- private
-
- RECV_TOKEN = {
- 'from' => :FROM,
- 'by' => :BY,
- 'via' => :VIA,
- 'with' => :WITH,
- 'id' => :ID,
- 'for' => :FOR
- }
-
- def scan_main
- until eof?
- if skip(/\A[\n\r\t ]+/n) # LWSP
- break if eof?
- end
-
- if s = readstr(@word_re)
- if @is_mime_header
- yield [:TOKEN, s]
- else
- # atom
- if /\A\d+\z/ === s
- yield [:DIGIT, s]
- elsif @received
- yield [RECV_TOKEN[s.downcase] || :ATOM, s]
- else
- yield [:ATOM, s]
- end
- end
-
- elsif skip(/\A"/)
- yield [:QUOTED, scan_quoted_word()]
-
- elsif skip(/\A\[/)
- yield [:DOMLIT, scan_domain_literal()]
-
- elsif skip(/\A\(/)
- @comments.push scan_comment()
-
- else
- c = readchar()
- yield [c, c]
- end
- end
-
- yield [false, '$']
- end
-
- def scan_quoted_word
- scan_qstr(@quoted_re, /\A"/, 'quoted-word')
- end
-
- def scan_domain_literal
- '[' + scan_qstr(@domlit_re, /\A\]/, 'domain-literal') + ']'
- end
-
- def scan_qstr( pattern, terminal, type )
- result = ''
- until eof?
- if s = readstr(pattern) then result << s
- elsif skip(terminal) then return result
- elsif skip(/\A\\/) then result << readchar()
- else
- raise "TMail FATAL: not match in #{type}"
- end
- end
- scan_error! "found unterminated #{type}"
- end
-
- def scan_comment
- result = ''
- nest = 1
- content = @comment_re
-
- until eof?
- if s = readstr(content) then result << s
- elsif skip(/\A\)/) then nest -= 1
- return result if nest == 0
- result << ')'
- elsif skip(/\A\(/) then nest += 1
- result << '('
- elsif skip(/\A\\/) then result << readchar()
- else
- raise 'TMail FATAL: not match in comment'
- end
- end
- scan_error! 'found unterminated comment'
- end
-
- # string scanner
-
- def init_scanner( str )
- @src = str
- end
-
- def eof?
- @src.empty?
- end
-
- def rest_size
- @src.size
- end
-
- def readstr( re )
- if m = re.match(@src)
- @src = m.post_match
- m[0]
- else
- nil
- end
- end
-
- def readchar
- readstr(/\A./)
- end
-
- def skip( re )
- if m = re.match(@src)
- @src = m.post_match
- true
- else
- false
- end
- end
-
- def scan_error!( msg )
- raise SyntaxError, msg
- end
-
- end
-
-end # module TMail
-#:startdoc: \ No newline at end of file
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb
deleted file mode 100644
index 8357398788..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb
+++ /dev/null
@@ -1,280 +0,0 @@
-# encoding: utf-8
-=begin rdoc
-
-= String handling class
-
-=end
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-class StringInput#:nodoc:
-
- include Enumerable
-
- class << self
-
- def new( str )
- if block_given?
- begin
- f = super
- yield f
- ensure
- f.close if f
- end
- else
- super
- end
- end
-
- alias open new
-
- end
-
- def initialize( str )
- @src = str
- @pos = 0
- @closed = false
- @lineno = 0
- end
-
- attr_reader :lineno
-
- def string
- @src
- end
-
- def inspect
- "#<#{self.class}:#{@closed ? 'closed' : 'open'},src=#{@src[0,30].inspect}>"
- end
-
- def close
- stream_check!
- @pos = nil
- @closed = true
- end
-
- def closed?
- @closed
- end
-
- def pos
- stream_check!
- [@pos, @src.size].min
- end
-
- alias tell pos
-
- def seek( offset, whence = IO::SEEK_SET )
- stream_check!
- case whence
- when IO::SEEK_SET
- @pos = offset
- when IO::SEEK_CUR
- @pos += offset
- when IO::SEEK_END
- @pos = @src.size - offset
- else
- raise ArgumentError, "unknown seek flag: #{whence}"
- end
- @pos = 0 if @pos < 0
- @pos = [@pos, @src.size + 1].min
- offset
- end
-
- def rewind
- stream_check!
- @pos = 0
- end
-
- def eof?
- stream_check!
- @pos > @src.size
- end
-
- def each( &block )
- stream_check!
- begin
- @src.each(&block)
- ensure
- @pos = 0
- end
- end
-
- def gets
- stream_check!
- if idx = @src.index(?\n, @pos)
- idx += 1 # "\n".size
- line = @src[ @pos ... idx ]
- @pos = idx
- @pos += 1 if @pos == @src.size
- else
- line = @src[ @pos .. -1 ]
- @pos = @src.size + 1
- end
- @lineno += 1
-
- line
- end
-
- def getc
- stream_check!
- ch = @src[@pos]
- @pos += 1
- @pos += 1 if @pos == @src.size
- ch
- end
-
- def read( len = nil )
- stream_check!
- return read_all unless len
- str = @src[@pos, len]
- @pos += len
- @pos += 1 if @pos == @src.size
- str
- end
-
- alias sysread read
-
- def read_all
- stream_check!
- return nil if eof?
- rest = @src[@pos ... @src.size]
- @pos = @src.size + 1
- rest
- end
-
- def stream_check!
- @closed and raise IOError, 'closed stream'
- end
-
-end
-
-
-class StringOutput#:nodoc:
-
- class << self
-
- def new( str = '' )
- if block_given?
- begin
- f = super
- yield f
- ensure
- f.close if f
- end
- else
- super
- end
- end
-
- alias open new
-
- end
-
- def initialize( str = '' )
- @dest = str
- @closed = false
- end
-
- def close
- @closed = true
- end
-
- def closed?
- @closed
- end
-
- def string
- @dest
- end
-
- alias value string
- alias to_str string
-
- def size
- @dest.size
- end
-
- alias pos size
-
- def inspect
- "#<#{self.class}:#{@dest ? 'open' : 'closed'},#{object_id}>"
- end
-
- def print( *args )
- stream_check!
- raise ArgumentError, 'wrong # of argument (0 for >1)' if args.empty?
- args.each do |s|
- raise ArgumentError, 'nil not allowed' if s.nil?
- @dest << s.to_s
- end
- nil
- end
-
- def puts( *args )
- stream_check!
- args.each do |str|
- @dest << (s = str.to_s)
- @dest << "\n" unless s[-1] == ?\n
- end
- @dest << "\n" if args.empty?
- nil
- end
-
- def putc( ch )
- stream_check!
- @dest << ch.chr
- nil
- end
-
- def printf( *args )
- stream_check!
- @dest << sprintf(*args)
- nil
- end
-
- def write( str )
- stream_check!
- s = str.to_s
- @dest << s
- s.size
- end
-
- alias syswrite write
-
- def <<( str )
- stream_check!
- @dest << str.to_s
- self
- end
-
- private
-
- def stream_check!
- @closed and raise IOError, 'closed stream'
- end
-
-end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb
deleted file mode 100644
index dc594a4229..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb
+++ /dev/null
@@ -1,337 +0,0 @@
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-# = TMail - The EMail Swiss Army Knife for Ruby
-#
-# The TMail library provides you with a very complete way to handle and manipulate EMails
-# from within your Ruby programs.
-#
-# Used as the backbone for email handling by the Ruby on Rails and Nitro web frameworks as
-# well as a bunch of other Ruby apps including the Ruby-Talk mailing list to newsgroup email
-# gateway, it is a proven and reliable email handler that won't let you down.
-#
-# Originally created by Minero Aoki, TMail has been recently picked up by Mikel Lindsaar and
-# is being actively maintained. Numerous backlogged bug fixes have been applied as well as
-# Ruby 1.9 compatibility and a swath of documentation to boot.
-#
-# TMail allows you to treat an email totally as an object and allow you to get on with your
-# own programming without having to worry about crafting the perfect email address validation
-# parser, or assembling an email from all it's component parts.
-#
-# TMail handles the most complex part of the email - the header. It generates and parses
-# headers and provides you with instant access to their innards through simple and logically
-# named accessor and setter methods.
-#
-# TMail also provides a wrapper to Net/SMTP as well as Unix Mailbox handling methods to
-# directly read emails from your unix mailbox, parse them and use them.
-#
-# Following is the comprehensive list of methods to access TMail::Mail objects. You can also
-# check out TMail::Mail, TMail::Address and TMail::Headers for other lists.
-module TMail
-
- # Provides an exception to throw on errors in Syntax within TMail's parsers
- class SyntaxError < StandardError; end
-
- # Provides a new email boundary to separate parts of the email. This is a random
- # string based off the current time, so should be fairly unique.
- #
- # For Example:
- #
- # TMail.new_boundary
- # #=> "mimepart_47bf656968207_25a8fbb80114"
- # TMail.new_boundary
- # #=> "mimepart_47bf66051de4_25a8fbb80240"
- def TMail.new_boundary
- 'mimepart_' + random_tag
- end
-
- # Provides a new email message ID. You can use this to generate unique email message
- # id's for your email so you can track them.
- #
- # Optionally takes a fully qualified domain name (default to the current hostname
- # returned by Socket.gethostname) that will be appended to the message ID.
- #
- # For Example:
- #
- # email.message_id = TMail.new_message_id
- # #=> "<47bf66845380e_25a8fbb80332@baci.local.tmail>"
- # email.to_s
- # #=> "Message-Id: <47bf668b633f1_25a8fbb80475@baci.local.tmail>\n\n"
- # email.message_id = TMail.new_message_id("lindsaar.net")
- # #=> "<47bf668b633f1_25a8fbb80475@lindsaar.net.tmail>"
- # email.to_s
- # #=> "Message-Id: <47bf668b633f1_25a8fbb80475@lindsaar.net.tmail>\n\n"
- def TMail.new_message_id( fqdn = nil )
- fqdn ||= ::Socket.gethostname
- "<#{random_tag()}@#{fqdn}.tmail>"
- end
-
- #:stopdoc:
- def TMail.random_tag #:nodoc:
- @uniq += 1
- t = Time.now
- sprintf('%x%x_%x%x%d%x',
- t.to_i, t.tv_usec,
- $$, Thread.current.object_id, @uniq, rand(255))
- end
- private_class_method :random_tag
-
- @uniq = 0
-
- #:startdoc:
-
- # Text Utils provides a namespace to define TOKENs, ATOMs, PHRASEs and CONTROL characters that
- # are OK per RFC 2822.
- #
- # It also provides methods you can call to determine if a string is safe
- module TextUtils
-
- aspecial = %Q|()<>[]:;.\\,"|
- tspecial = %Q|()<>[];:\\,"/?=|
- lwsp = %Q| \t\r\n|
- control = %Q|\x00-\x1f\x7f-\xff|
-
- CONTROL_CHAR = /[#{control}]/n
- ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{lwsp}]/n
- PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n
- TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{lwsp}]/n
-
- # Returns true if the string supplied is free from characters not allowed as an ATOM
- def atom_safe?( str )
- not ATOM_UNSAFE === str
- end
-
- # If the string supplied has ATOM unsafe characters in it, will return the string quoted
- # in double quotes, otherwise returns the string unmodified
- def quote_atom( str )
- (ATOM_UNSAFE === str) ? dquote(str) : str
- end
-
- # If the string supplied has PHRASE unsafe characters in it, will return the string quoted
- # in double quotes, otherwise returns the string unmodified
- def quote_phrase( str )
- (PHRASE_UNSAFE === str) ? dquote(str) : str
- end
-
- # Returns true if the string supplied is free from characters not allowed as a TOKEN
- def token_safe?( str )
- not TOKEN_UNSAFE === str
- end
-
- # If the string supplied has TOKEN unsafe characters in it, will return the string quoted
- # in double quotes, otherwise returns the string unmodified
- def quote_token( str )
- (TOKEN_UNSAFE === str) ? dquote(str) : str
- end
-
- # Wraps supplied string in double quotes unless it is already wrapped
- # Returns double quoted string
- def dquote( str ) #:nodoc:
- unless str =~ /^".*?"$/
- '"' + str.gsub(/["\\]/n) {|s| '\\' + s } + '"'
- else
- str
- end
- end
- private :dquote
-
- # Unwraps supplied string from inside double quotes
- # Returns unquoted string
- def unquote( str )
- str =~ /^"(.*?)"$/ ? $1 : str
- end
-
- # Provides a method to join a domain name by it's parts and also makes it
- # ATOM safe by quoting it as needed
- def join_domain( arr )
- arr.map {|i|
- if /\A\[.*\]\z/ === i
- i
- else
- quote_atom(i)
- end
- }.join('.')
- end
-
- #:stopdoc:
- ZONESTR_TABLE = {
- 'jst' => 9 * 60,
- 'eet' => 2 * 60,
- 'bst' => 1 * 60,
- 'met' => 1 * 60,
- 'gmt' => 0,
- 'utc' => 0,
- 'ut' => 0,
- 'nst' => -(3 * 60 + 30),
- 'ast' => -4 * 60,
- 'edt' => -4 * 60,
- 'est' => -5 * 60,
- 'cdt' => -5 * 60,
- 'cst' => -6 * 60,
- 'mdt' => -6 * 60,
- 'mst' => -7 * 60,
- 'pdt' => -7 * 60,
- 'pst' => -8 * 60,
- 'a' => -1 * 60,
- 'b' => -2 * 60,
- 'c' => -3 * 60,
- 'd' => -4 * 60,
- 'e' => -5 * 60,
- 'f' => -6 * 60,
- 'g' => -7 * 60,
- 'h' => -8 * 60,
- 'i' => -9 * 60,
- # j not use
- 'k' => -10 * 60,
- 'l' => -11 * 60,
- 'm' => -12 * 60,
- 'n' => 1 * 60,
- 'o' => 2 * 60,
- 'p' => 3 * 60,
- 'q' => 4 * 60,
- 'r' => 5 * 60,
- 's' => 6 * 60,
- 't' => 7 * 60,
- 'u' => 8 * 60,
- 'v' => 9 * 60,
- 'w' => 10 * 60,
- 'x' => 11 * 60,
- 'y' => 12 * 60,
- 'z' => 0 * 60
- }
- #:startdoc:
-
- # Takes a time zone string from an EMail and converts it to Unix Time (seconds)
- def timezone_string_to_unixtime( str )
- if m = /([\+\-])(\d\d?)(\d\d)/.match(str)
- sec = (m[2].to_i * 60 + m[3].to_i) * 60
- m[1] == '-' ? -sec : sec
- else
- min = ZONESTR_TABLE[str.downcase] or
- raise SyntaxError, "wrong timezone format '#{str}'"
- min * 60
- end
- end
-
- #:stopdoc:
- WDAY = %w( Sun Mon Tue Wed Thu Fri Sat TMailBUG )
- MONTH = %w( TMailBUG Jan Feb Mar Apr May Jun
- Jul Aug Sep Oct Nov Dec TMailBUG )
-
- def time2str( tm )
- # [ruby-list:7928]
- gmt = Time.at(tm.to_i)
- gmt.gmtime
- offset = tm.to_i - Time.local(*gmt.to_a[0,6].reverse).to_i
-
- # DO NOT USE strftime: setlocale() breaks it
- sprintf '%s, %s %s %d %02d:%02d:%02d %+.2d%.2d',
- WDAY[tm.wday], tm.mday, MONTH[tm.month],
- tm.year, tm.hour, tm.min, tm.sec,
- *(offset / 60).divmod(60)
- end
-
-
- MESSAGE_ID = /<[^\@>]+\@[^>\@]+>/
-
- def message_id?( str )
- MESSAGE_ID === str
- end
-
-
- MIME_ENCODED = /=\?[^\s?=]+\?[QB]\?[^\s?=]+\?=/i
-
- def mime_encoded?( str )
- MIME_ENCODED === str
- end
-
-
- def decode_params( hash )
- new = Hash.new
- encoded = nil
- hash.each do |key, value|
- if m = /\*(?:(\d+)\*)?\z/.match(key)
- ((encoded ||= {})[m.pre_match] ||= [])[(m[1] || 0).to_i] = value
- else
- new[key] = to_kcode(value)
- end
- end
- if encoded
- encoded.each do |key, strings|
- new[key] = decode_RFC2231(strings.join(''))
- end
- end
-
- new
- end
-
- NKF_FLAGS = {
- 'EUC' => '-e -m',
- 'SJIS' => '-s -m'
- }
-
- def to_kcode( str )
- flag = NKF_FLAGS[TMail.KCODE] or return str
- NKF.nkf(flag, str)
- end
-
- RFC2231_ENCODED = /\A(?:iso-2022-jp|euc-jp|shift_jis|us-ascii)?'[a-z]*'/in
-
- def decode_RFC2231( str )
- m = RFC2231_ENCODED.match(str) or return str
- begin
- to_kcode(m.post_match.gsub(/%[\da-f]{2}/in) {|s| s[1,2].hex.chr })
- rescue
- m.post_match.gsub(/%[\da-f]{2}/in, "")
- end
- end
-
- def quote_boundary
- # Make sure the Content-Type boundary= parameter is quoted if it contains illegal characters
- # (to ensure any special characters in the boundary text are escaped from the parser
- # (such as = in MS Outlook's boundary text))
- if @body =~ /^(.*)boundary=(.*)$/m
- preamble = $1
- remainder = $2
- if remainder =~ /;/
- remainder =~ /^(.*?)(;.*)$/m
- boundary_text = $1
- post = $2.chomp
- else
- boundary_text = remainder.chomp
- end
- if boundary_text =~ /[\/\?\=]/
- boundary_text = "\"#{boundary_text}\"" unless boundary_text =~ /^".*?"$/
- @body = "#{preamble}boundary=#{boundary_text}#{post}"
- end
- end
- end
- #:startdoc:
-
-
- end
-
-end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb
deleted file mode 100644
index 95228497c0..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# version.rb
-#
-#--
-# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
-#
-# 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.
-#
-# Note: Originally licensed under LGPL v2+. Using MIT license for Rails
-# with permission of Minero Aoki.
-#++
-
-#:stopdoc:
-module TMail
- module VERSION
- MAJOR = 1
- MINOR = 2
- TINY = 3
-
- STRING = [MAJOR, MINOR, TINY].join('.')
- end
-end
diff --git a/actionmailer/lib/action_mailer/vendor/tmail.rb b/actionmailer/lib/action_mailer/vendor/tmail.rb
deleted file mode 100644
index 60555605f6..0000000000
--- a/actionmailer/lib/action_mailer/vendor/tmail.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-# Prefer gems to the bundled libs.
-require 'rubygems'
-
-begin
- gem 'tmail', '~> 1.2.3'
-rescue Gem::LoadError
- $:.unshift "#{File.dirname(__FILE__)}/tmail-1.2.3"
-end
-
-module TMail
-end
-
-require 'tmail'
-
-require 'active_support/core_ext/kernel/reporting'
-silence_warnings do
- TMail::Encoder.const_set("MAX_LINE_LEN", 200)
-end
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
index e84b3b0d23..af6f1bc92e 100644
--- a/actionmailer/test/abstract_unit.rb
+++ b/actionmailer/test/abstract_unit.rb
@@ -1,12 +1,9 @@
-root = File.expand_path('../../..', __FILE__)
begin
- require "#{root}/vendor/gems/environment"
+ require File.expand_path('../../../vendor/gems/environment', __FILE__)
rescue LoadError
- $:.unshift("#{root}/activesupport/lib")
- $:.unshift("#{root}/actionpack/lib")
end
-lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
+lib = File.expand_path('../../lib', __FILE__)
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'rubygems'
diff --git a/actionmailer/test/adv_attr_test.rb b/actionmailer/test/adv_attr_test.rb
index fd909a5627..f22d733bc5 100644
--- a/actionmailer/test/adv_attr_test.rb
+++ b/actionmailer/test/adv_attr_test.rb
@@ -1,18 +1,36 @@
require 'abstract_unit'
require 'action_mailer/adv_attr_accessor'
-class AdvAttrTest < Test::Unit::TestCase
+class AdvAttrTest < ActiveSupport::TestCase
class Person
- include ActionMailer::AdvAttrAccessor
+ cattr_reader :protected_instance_variables
+ @@protected_instance_variables = []
+
+ extend ActionMailer::AdvAttrAccessor
adv_attr_accessor :name
end
+ def setup
+ @person = Person.new
+ end
+
def test_adv_attr
- bob = Person.new
- assert_nil bob.name
- bob.name 'Bob'
- assert_equal 'Bob', bob.name
+ assert_nil @person.name
+ @person.name 'Bob'
+ assert_equal 'Bob', @person.name
+ end
+
+ def test_adv_attr_writer
+ assert_nil @person.name
+ @person.name = 'Bob'
+ assert_equal 'Bob', @person.name
+ end
+
+ def test_raise_an_error_with_multiple_args
+ assert_raise(ArgumentError) { @person.name('x', 'y') }
+ end
- assert_raise(ArgumentError) {bob.name 'x', 'y'}
+ def test_ivar_is_added_to_protected_instnace_variables
+ assert Person.protected_instance_variables.include?('@name')
end
end
diff --git a/actionmailer/test/asset_host_test.rb b/actionmailer/test/asset_host_test.rb
index 1c92dd266d..f3383e5608 100644
--- a/actionmailer/test/asset_host_test.rb
+++ b/actionmailer/test/asset_host_test.rb
@@ -24,7 +24,7 @@ class AssetHostTest < Test::Unit::TestCase
def test_asset_host_as_string
ActionController::Base.asset_host = "http://www.example.com"
mail = AssetHostMailer.deliver_email_with_asset(@recipient)
- assert_equal "<img alt=\"Somelogo\" src=\"http://www.example.com/images/somelogo.png\" />", mail.body.strip
+ assert_equal "<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
@@ -36,7 +36,7 @@ class AssetHostTest < Test::Unit::TestCase
end
}
mail = AssetHostMailer.deliver_email_with_asset(@recipient)
- assert_equal "<img alt=\"Somelogo\" src=\"http://images.example.com/images/somelogo.png\" />", mail.body.strip
+ assert_equal "<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
@@ -49,6 +49,6 @@ class AssetHostTest < Test::Unit::TestCase
}
mail = nil
assert_nothing_raised { mail = AssetHostMailer.deliver_email_with_asset(@recipient) }
- assert_equal "<img alt=\"Somelogo\" src=\"http://www.example.com/images/somelogo.png\" />", mail.body.strip
+ assert_equal "<img alt=\"Somelogo\" src=\"http://www.example.com/images/somelogo.png\" />", mail.body.to_s.strip
end
end \ No newline at end of file
diff --git a/actionmailer/test/fixtures/attachments/foo.jpg b/actionmailer/test/fixtures/attachments/foo.jpg
new file mode 100644
index 0000000000..b976fe5e00
--- /dev/null
+++ b/actionmailer/test/fixtures/attachments/foo.jpg
Binary files differ
diff --git a/actionmailer/test/fixtures/attachments/test.jpg b/actionmailer/test/fixtures/attachments/test.jpg
new file mode 100644
index 0000000000..b976fe5e00
--- /dev/null
+++ b/actionmailer/test/fixtures/attachments/test.jpg
Binary files differ
diff --git a/actionmailer/test/mail_helper_test.rb b/actionmailer/test/mail_helper_test.rb
index f8b002e0a7..2d3565d159 100644
--- a/actionmailer/test/mail_helper_test.rb
+++ b/actionmailer/test/mail_helper_test.rb
@@ -55,7 +55,7 @@ end
class MailerHelperTest < Test::Unit::TestCase
def new_mail( charset="utf-8" )
- mail = TMail::Mail.new
+ mail = Mail.new
mail.set_content_type "text", "plain", { "charset" => charset } if charset
mail
end
@@ -90,7 +90,7 @@ class MailerHelperTest < Test::Unit::TestCase
def test_use_mail_helper
mail = HelperMailer.create_use_mail_helper(@recipient)
assert_match %r{ But soft!}, mail.encoded
- assert_match %r{east, and\n Juliet}, mail.encoded
+ assert_match %r{east, and\r\n Juliet}, mail.encoded
end
end
diff --git a/actionmailer/test/mail_layout_test.rb b/actionmailer/test/mail_layout_test.rb
index f37c26ff69..0877e7b2cb 100644
--- a/actionmailer/test/mail_layout_test.rb
+++ b/actionmailer/test/mail_layout_test.rb
@@ -65,63 +65,85 @@ class LayoutMailerTest < Test::Unit::TestCase
def test_should_pickup_default_layout
mail = AutoLayoutMailer.create_hello(@recipient)
- assert_equal "Hello from layout Inside", mail.body.strip
+ assert_equal "Hello from layout Inside", mail.body.to_s.strip
end
def test_should_pickup_multipart_layout
mail = AutoLayoutMailer.create_multipart(@recipient)
- assert_equal "multipart/alternative", mail.content_type
+ # CHANGED: content_type returns an object
+ # assert_equal "multipart/alternative", mail.content_type
+ assert_equal "multipart/alternative", mail.mime_type
assert_equal 2, mail.parts.size
- assert_equal 'text/plain', mail.parts.first.content_type
- assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
+ # CHANGED: content_type returns an object
+ # assert_equal 'text/plain', mail.parts.first.content_type
+ assert_equal 'text/plain', mail.parts.first.mime_type
+
+ # CHANGED: body returns an object
+ # assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
+ assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s
- assert_equal 'text/html', mail.parts.last.content_type
- assert_equal "Hello from layout text/html multipart", mail.parts.last.body
+ # CHANGED: content_type returns an object
+ # assert_equal 'text/html', mail.parts.last.content_type
+ assert_equal 'text/html', mail.parts.last.mime_type
+
+ # CHANGED: body returns an object
+ # assert_equal "Hello from layout text/html multipart", mail.parts.last.body
+ assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s
end
def test_should_pickup_multipartmixed_layout
mail = AutoLayoutMailer.create_multipart(@recipient, "multipart/mixed")
- assert_equal "multipart/mixed", mail.content_type
+ # CHANGED: content_type returns an object
+ # assert_equal "multipart/mixed", mail.content_type
+ assert_equal "multipart/mixed", mail.mime_type
assert_equal 2, mail.parts.size
- assert_equal 'text/plain', mail.parts.first.content_type
- assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
+ # CHANGED: content_type returns an object
+ # assert_equal 'text/plain', mail.parts.first.content_type
+ assert_equal 'text/plain', mail.parts.first.mime_type
+ # CHANGED: body returns an object
+ # assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
+ assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s
- assert_equal 'text/html', mail.parts.last.content_type
- assert_equal "Hello from layout text/html multipart", mail.parts.last.body
+ # CHANGED: content_type returns an object
+ # assert_equal 'text/html', mail.parts.last.content_type
+ assert_equal 'text/html', mail.parts.last.mime_type
+ # CHANGED: body returns an object
+ # assert_equal "Hello from layout text/html multipart", mail.parts.last.body
+ assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s
end
def test_should_fix_multipart_layout
mail = AutoLayoutMailer.create_multipart(@recipient, "text/plain")
- assert_equal "multipart/alternative", mail.content_type
+ assert_equal "multipart/alternative", mail.mime_type
assert_equal 2, mail.parts.size
- assert_equal 'text/plain', mail.parts.first.content_type
- assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
+ 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.content_type
- assert_equal "Hello from layout text/html multipart", mail.parts.last.body
+ 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.create_spam(@recipient)
- assert_equal "Spammer layout Hello, Earth", mail.body.strip
+ assert_equal "Spammer layout Hello, Earth", mail.body.to_s.strip
end
def test_should_respect_layout_false
mail = AutoLayoutMailer.create_nolayout(@recipient)
- assert_equal "Hello, Earth", mail.body.strip
+ assert_equal "Hello, Earth", mail.body.to_s.strip
end
def test_explicit_class_layout
mail = ExplicitLayoutMailer.create_signup(@recipient)
- assert_equal "Spammer layout We do not spam", mail.body.strip
+ assert_equal "Spammer layout We do not spam", mail.body.to_s.strip
end
def test_explicit_layout_exceptions
mail = ExplicitLayoutMailer.create_logout(@recipient)
- assert_equal "You logged out", mail.body.strip
+ assert_equal "You logged out", mail.body.to_s.strip
end
end
diff --git a/actionmailer/test/mail_render_test.rb b/actionmailer/test/mail_render_test.rb
index 514f7ed798..09ce5e4854 100644
--- a/actionmailer/test/mail_render_test.rb
+++ b/actionmailer/test/mail_render_test.rb
@@ -40,13 +40,22 @@ class RenderMailer < ActionMailer::Base
from "tester@example.com"
end
- def included_old_subtemplate(recipient)
+ def mailer_accessor(recipient)
recipients recipient
- subject "Including another template in the one being rendered"
+ subject "Mailer Accessor"
from "tester@example.com"
- @world = "Earth"
- render :inline => "Hello, <%= render \"subtemplate\" %>"
+ render :inline => "Look, <%= mailer.subject %>!"
+ end
+
+ def no_instance_variable(recipient)
+ recipients recipient
+ subject "No Instance Variable"
+ from "tester@example.com"
+
+ silence_warnings do
+ render :inline => "Look, subject.nil? is <%= @subject.nil? %>!"
+ end
end
def initialize_defaults(method_name)
@@ -71,6 +80,8 @@ class SecondMailer < ActionMailer::Base
end
end
+# CHANGED: Those tests were changed because body returns an object now
+# Instead of mail.body.strip, we should mail.body.to_s.strip
class RenderHelperTest < Test::Unit::TestCase
def setup
set_delivery_method :test
@@ -86,27 +97,37 @@ class RenderHelperTest < Test::Unit::TestCase
def test_implicit_body
mail = RenderMailer.create_implicit_body(@recipient)
- assert_equal "Hello there, \n\nMr. test@localhost", mail.body.strip
+ assert_equal "Hello there, \n\nMr. test@localhost", mail.body.to_s.strip
end
def test_inline_template
mail = RenderMailer.create_inline_template(@recipient)
- assert_equal "Hello, Earth", mail.body.strip
+ assert_equal "Hello, Earth", mail.body.to_s.strip
end
def test_file_template
mail = RenderMailer.create_file_template(@recipient)
- assert_equal "Hello there, \n\nMr. test@localhost", mail.body.strip
+ assert_equal "Hello there, \n\nMr. test@localhost", mail.body.to_s.strip
end
def test_rxml_template
mail = RenderMailer.deliver_rxml_template(@recipient)
- assert_equal "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<test/>", mail.body.strip
+ assert_equal "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<test/>", mail.body.to_s.strip
end
def test_included_subtemplate
mail = RenderMailer.deliver_included_subtemplate(@recipient)
- assert_equal "Hey Ho, let's go!", mail.body.strip
+ assert_equal "Hey Ho, let's go!", mail.body.to_s.strip
+ end
+
+ def test_mailer_accessor
+ mail = RenderMailer.deliver_mailer_accessor(@recipient)
+ assert_equal "Look, Mailer Accessor!", mail.body.to_s.strip
+ end
+
+ def test_no_instance_variable
+ mail = RenderMailer.deliver_no_instance_variable(@recipient)
+ assert_equal "Look, subject.nil? is true!", mail.body.to_s.strip
end
end
@@ -125,12 +146,12 @@ class FirstSecondHelperTest < Test::Unit::TestCase
def test_ordering
mail = FirstMailer.create_share(@recipient)
- assert_equal "first mail", mail.body.strip
+ assert_equal "first mail", mail.body.to_s.strip
mail = SecondMailer.create_share(@recipient)
- assert_equal "second mail", mail.body.strip
+ assert_equal "second mail", mail.body.to_s.strip
mail = FirstMailer.create_share(@recipient)
- assert_equal "first mail", mail.body.strip
+ assert_equal "first mail", mail.body.to_s.strip
mail = SecondMailer.create_share(@recipient)
- assert_equal "second mail", mail.body.strip
+ assert_equal "second mail", mail.body.to_s.strip
end
end
diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb
index c98f0a7601..f66b4a174b 100644
--- a/actionmailer/test/mail_service_test.rb
+++ b/actionmailer/test/mail_service_test.rb
@@ -9,7 +9,7 @@ class FunkyPathMailer < ActionMailer::Base
subject "This path has dots"
from "Chad Fowler <chad@chadfowler.com>"
attachment :content_type => "text/plain",
- :body => "dots dots dots..."
+ :data => "dots dots dots..."
end
end
@@ -31,6 +31,18 @@ class TestMailer < ActionMailer::Base
render :text => "Goodbye, Mr. #{recipient}"
end
+ def from_with_name
+ from "System <system@loudthinking.com>"
+ recipients "root@loudthinking.com"
+ render :text => "Nothing to see here."
+ end
+
+ def from_without_name
+ from "system@loudthinking.com"
+ recipients "root@loudthinking.com"
+ render :text => "Nothing to see here."
+ end
+
def cc_bcc(recipient)
recipients recipient
subject "testing bcc/cc"
@@ -95,7 +107,7 @@ class TestMailer < ActionMailer::Base
cc "Foo áëô îü <extended@example.net>"
bcc "Foo áëô îü <extended@example.net>"
charset "utf-8"
-
+
render :text => "åœö blah"
end
@@ -143,8 +155,8 @@ class TestMailer < ActionMailer::Base
p.body = "blah"
end
- attachment :content_type => "image/jpeg", :filename => "foo.jpg",
- :body => "123456789"
+ attachment :content_type => "image/jpeg", :filename => File.join(File.dirname(__FILE__), "fixtures", "attachments", "foo.jpg"),
+ :data => "123456789"
render :text => "plain text default"
end
@@ -227,12 +239,12 @@ class TestMailer < ActionMailer::Base
from "test@example.com"
content_type "multipart/mixed"
- part :content_type => "multipart/alternative", :content_disposition => "inline", :headers => { "foo" => "bar" } do |p|
+ part :content_type => "multipart/alternative", :content_disposition => "inline", "foo" => "bar" do |p|
p.part :content_type => "text/plain", :body => "test text\nline #2"
p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
end
- attachment :content_type => "application/octet-stream",:filename => "test.txt", :body => "test abcdefghijklmnopqstuvwxyz"
+ attachment :content_type => "application/octet-stream", :filename => "test.txt", :data => "test abcdefghijklmnopqstuvwxyz"
end
def nested_multipart_with_body(recipient)
@@ -251,8 +263,8 @@ class TestMailer < ActionMailer::Base
subject "custom header in attachment"
from "test@example.com"
content_type "multipart/related"
- part :content_type => "text/html", :body => 'yo'
- attachment :content_type => "image/jpeg",:filename => "test.jpeg", :body => "i am not a real picture", :headers => { 'Content-ID' => '<test@test.com>' }
+ part :content_type => "text/html", :body => 'yo'
+ attachment :content_type => "image/jpeg", :filename => File.join(File.dirname(__FILE__), "fixtures", "attachments", "test.jpg"), :data => "i am not a real picture", 'Content-ID' => '<test@test.com>'
end
def unnamed_attachment(recipient)
@@ -261,7 +273,7 @@ class TestMailer < ActionMailer::Base
from "test@example.com"
content_type "multipart/mixed"
part :content_type => "text/plain", :body => "hullo"
- attachment :content_type => "application/octet-stream", :body => "test abcdefghijklmnopqstuvwxyz"
+ attachment :content_type => "application/octet-stream", :data => "test abcdefghijklmnopqstuvwxyz"
end
def headers_with_nonalpha_chars(recipient)
@@ -289,6 +301,7 @@ class TestMailer < ActionMailer::Base
render :text => "testing"
end
+ # This tests body calls accepeting a hash, which is deprecated.
def body_ivar(recipient)
recipients recipient
subject "Body as a local variable"
@@ -319,10 +332,10 @@ class ActionMailerTest < Test::Unit::TestCase
end
def new_mail( charset="utf-8" )
- mail = TMail::Mail.new
+ mail = Mail.new
mail.mime_version = "1.0"
if charset
- mail.set_content_type "text", "plain", { "charset" => charset }
+ mail.content_type ["text", "plain", { "charset" => charset }]
end
mail
end
@@ -346,30 +359,33 @@ class ActionMailerTest < Test::Unit::TestCase
def test_nested_parts
created = nil
assert_nothing_raised { created = TestMailer.create_nested_multipart(@recipient)}
- assert_equal 2,created.parts.size
- assert_equal 2,created.parts.first.parts.size
-
- assert_equal "multipart/mixed", created.content_type
- assert_equal "multipart/alternative", created.parts.first.content_type
- assert_equal "bar", created.parts.first.header['foo'].to_s
- assert_nil created.parts.first.charset
- assert_equal "text/plain", created.parts.first.parts.first.content_type
- assert_equal "text/html", created.parts.first.parts[1].content_type
- assert_equal "application/octet-stream", created.parts[1].content_type
+ assert_equal 2, created.parts.size
+ assert_equal 2, created.parts.first.parts.size
+
+ assert_equal "multipart/mixed", created.mime_type
+ assert_equal "multipart/alternative", created.parts[0].mime_type
+ assert_equal "bar", created.parts[0].header['foo'].to_s
+ assert_nil created.parts[0].charset
+ 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
created = nil
TestMailer.create_nested_multipart_with_body(@recipient)
assert_nothing_raised { created = TestMailer.create_nested_multipart_with_body(@recipient)}
+
assert_equal 1,created.parts.size
assert_equal 2,created.parts.first.parts.size
- assert_equal "multipart/mixed", created.content_type
- assert_equal "multipart/alternative", created.parts.first.content_type
- assert_equal "Nothing to see here.", created.parts.first.parts.first.body
- assert_equal "text/plain", created.parts.first.parts.first.content_type
- assert_equal "text/html", created.parts.first.parts[1].content_type
+ assert_equal "multipart/mixed", created.mime_type
+ assert_equal "multipart/alternative", created.parts.first.mime_type
+ assert_equal "text/plain", created.parts.first.parts.first.mime_type
+ assert_equal "Nothing to see here.", created.parts.first.parts.first.body.to_s
+ assert_equal "text/html", created.parts.first.parts.second.mime_type
+ assert_equal "<b>test</b> HTML<br/>", created.parts.first.parts.second.body.to_s
end
def test_attachment_with_custom_header
@@ -391,20 +407,30 @@ class ActionMailerTest < Test::Unit::TestCase
created = nil
assert_nothing_raised { created = TestMailer.create_signed_up(@recipient) }
assert_not_nil created
+
+ expected.message_id = '<123@456>'
+ created.message_id = '<123@456>'
+
assert_equal expected.encoded, created.encoded
assert_nothing_raised { TestMailer.deliver_signed_up(@recipient) }
- assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+
+ 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
def test_subject_with_i18n
assert_nothing_raised { TestMailer.deliver_subject_with_i18n(@recipient) }
- assert_equal "Subject with i18n", ActionMailer::Base.deliveries.first.subject
+ assert_equal "Subject with i18n", ActionMailer::Base.deliveries.first.subject.to_s
I18n.backend.store_translations('en', :actionmailer => {:test_mailer => {:subject_with_i18n => {:subject => "New Subject!"}}})
assert_nothing_raised { TestMailer.deliver_subject_with_i18n(@recipient) }
- assert_equal "New Subject!", ActionMailer::Base.deliveries.last.subject
+ assert_equal "New Subject!", ActionMailer::Base.deliveries.last.subject.to_s
end
def test_custom_template
@@ -418,6 +444,8 @@ class ActionMailerTest < Test::Unit::TestCase
created = nil
assert_nothing_raised { created = TestMailer.create_custom_template(@recipient) }
assert_not_nil created
+ expected.message_id = '<123@456>'
+ created.message_id = '<123@456>'
assert_equal expected.encoded, created.encoded
end
@@ -440,8 +468,8 @@ class ActionMailerTest < Test::Unit::TestCase
assert_nothing_raised { created = TestMailer.create_custom_templating_extension(@recipient) }
assert_not_nil created
assert_equal 2, created.parts.length
- assert_equal 'text/plain', created.parts[0].content_type
- assert_equal 'text/html', created.parts[1].content_type
+ assert_equal 'text/plain', created.parts[0].mime_type
+ assert_equal 'text/html', created.parts[1].mime_type
end
def test_cancelled_account
@@ -455,11 +483,17 @@ class ActionMailerTest < Test::Unit::TestCase
created = nil
assert_nothing_raised { created = TestMailer.create_cancelled_account(@recipient) }
assert_not_nil created
+ expected.message_id = '<123@456>'
+ created.message_id = '<123@456>'
assert_equal expected.encoded, created.encoded
assert_nothing_raised { TestMailer.deliver_cancelled_account(@recipient) }
assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ delivered = ActionMailer::Base.deliveries.first
+ expected.message_id = '<123@456>'
+ delivered.message_id = '<123@456>'
+
+ assert_equal expected.encoded, delivered.encoded
end
def test_cc_bcc
@@ -477,6 +511,8 @@ class ActionMailerTest < Test::Unit::TestCase
created = TestMailer.create_cc_bcc @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
@@ -484,7 +520,33 @@ class ActionMailerTest < Test::Unit::TestCase
end
assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ delivered = ActionMailer::Base.deliveries.first
+ expected.message_id = '<123@456>'
+ delivered.message_id = '<123@456>'
+
+ assert_equal expected.encoded, delivered.encoded
+ end
+
+ def test_from_without_name_for_smtp
+ ActionMailer::Base.delivery_method = :smtp
+ TestMailer.deliver_from_without_name
+
+ mail = MockSMTP.deliveries.first
+ assert_not_nil mail
+ mail, from, to = mail
+
+ assert_equal 'system@loudthinking.com', from.to_s
+ end
+
+ def test_from_with_name_for_smtp
+ ActionMailer::Base.delivery_method = :smtp
+ TestMailer.deliver_from_with_name
+
+ mail = MockSMTP.deliveries.first
+ assert_not_nil mail
+ mail, from, to = mail
+
+ assert_equal 'system@loudthinking.com', from.addresses.first
end
def test_reply_to
@@ -502,14 +564,23 @@ class ActionMailerTest < Test::Unit::TestCase
created = TestMailer.create_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
TestMailer.deliver_different_reply_to @recipient
end
- assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ 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
def test_iso_charset
@@ -527,14 +598,23 @@ class ActionMailerTest < Test::Unit::TestCase
created = TestMailer.create_iso_charset @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
TestMailer.deliver_iso_charset @recipient
end
- assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ 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
def test_unencoded_subject
@@ -552,14 +632,23 @@ class ActionMailerTest < Test::Unit::TestCase
created = TestMailer.create_unencoded_subject @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
TestMailer.deliver_unencoded_subject @recipient
end
- assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ 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
def test_instances_are_nil
@@ -625,7 +714,12 @@ class ActionMailerTest < Test::Unit::TestCase
TestMailer.logger = FakeLogger.new
TestMailer.deliver_signed_up(@recipient)
assert(TestMailer.logger.info_contents =~ /Sent mail to #{@recipient}/)
- assert_equal(TestMailer.logger.debug_contents, "\n#{mail.encoded}")
+ expected = TestMailer.logger.debug_contents
+ actual = "\n#{mail.encoded}"
+ expected.gsub!(/Message-ID:.*\r\n/, "Message-ID: <123@456>\r\n")
+ actual.gsub!(/Message-ID:.*\r\n/, "Message-ID: <123@456>\r\n")
+
+ assert_equal(expected, actual)
end
def test_unquote_quoted_printable_subject
@@ -636,9 +730,9 @@ Content-Type: text/plain; charset=iso-8859-1
The body
EOF
- mail = TMail::Mail.parse(msg)
+ mail = Mail.new(msg)
assert_equal "testing testing \326\244", mail.subject
- assert_equal "=?utf-8?Q?testing_testing_=D6=A4?=", mail.quoted_subject
+ assert_equal "Subject: =?utf-8?Q?testing_testing_=D6=A4?=\r\n", mail[:subject].encoded
end
def test_unquote_7bit_subject
@@ -649,9 +743,9 @@ Content-Type: text/plain; charset=iso-8859-1
The body
EOF
- mail = TMail::Mail.parse(msg)
+ mail = Mail.new(msg)
assert_equal "this == working?", mail.subject
- assert_equal "this == working?", mail.quoted_subject
+ assert_equal "Subject: this == working?\r\n", mail[:subject].encoded
end
def test_unquote_7bit_body
@@ -663,9 +757,9 @@ Content-Transfer-Encoding: 7bit
The=3Dbody
EOF
- mail = TMail::Mail.parse(msg)
- assert_equal "The=3Dbody", mail.body.strip
- assert_equal "The=3Dbody", mail.quoted_body.strip
+ mail = Mail.new(msg)
+ assert_equal "The=3Dbody", mail.body.to_s.strip
+ assert_equal "The=3Dbody", mail.body.encoded.strip
end
def test_unquote_quoted_printable_body
@@ -677,9 +771,9 @@ Content-Transfer-Encoding: quoted-printable
The=3Dbody
EOF
- mail = TMail::Mail.parse(msg)
- assert_equal "The=body", mail.body.strip
- assert_equal "The=3Dbody", mail.quoted_body.strip
+ mail = Mail.new(msg)
+ assert_equal "The=body", mail.body.to_s.strip
+ assert_equal "The=3Dbody", mail.body.encoded.strip
end
def test_unquote_base64_body
@@ -691,9 +785,9 @@ Content-Transfer-Encoding: base64
VGhlIGJvZHk=
EOF
- mail = TMail::Mail.parse(msg)
- assert_equal "The body", mail.body.strip
- assert_equal "VGhlIGJvZHk=", mail.quoted_body.strip
+ mail = Mail.new(msg)
+ assert_equal "The body", mail.body.to_s.strip
+ assert_equal "VGhlIGJvZHk=", mail.body.encoded.strip
end
def test_extended_headers
@@ -714,14 +808,22 @@ EOF
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
TestMailer.deliver_extended_headers @recipient
end
- assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ 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
def test_utf8_body_is_not_quoted
@@ -752,40 +854,40 @@ EOF
created = TestMailer.create_utf8_body @recipient
assert_match(/\nFrom: =\?utf-8\?Q\?Foo_.*?\?= <extended@example.net>\r/, created.encoded)
- assert_match(/\nTo: =\?utf-8\?Q\?Foo_.*?\?= <extended@example.net>, Example Recipient <me/, created.encoded)
+ assert_match(/\nTo: =\?utf-8\?Q\?Foo_.*?\?= <extended@example.net>, \r\n\tExample Recipient <me/, created.encoded)
end
def test_receive_decodes_base64_encoded_mail
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email")
TestMailer.receive(fixture)
- assert_match(/Jamis/, TestMailer.received_body)
+ assert_match(/Jamis/, TestMailer.received_body.to_s)
end
def test_receive_attachments
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email2")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
attachment = mail.attachments.last
assert_equal "smime.p7s", attachment.original_filename
- assert_equal "application/pkcs7-signature", attachment.content_type
+ assert_equal "application/pkcs7-signature", mail.parts.last.mime_type
end
def test_decode_attachment_without_charset
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email3")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
attachment = mail.attachments.last
assert_equal 1026, attachment.read.length
end
def test_attachment_using_content_location
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email12")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
assert_equal 1, mail.attachments.length
assert_equal "Photo25.jpg", mail.attachments.first.original_filename
end
def test_attachment_with_text_type
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email13")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
assert mail.has_attachments?
assert_equal 1, mail.attachments.length
assert_equal "hello.rb", mail.attachments.first.original_filename
@@ -793,19 +895,19 @@ EOF
def test_decode_part_without_content_type
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email4")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
assert_nothing_raised { mail.body }
end
def test_decode_message_without_content_type
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email5")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
assert_nothing_raised { mail.body }
end
def test_decode_message_with_incorrect_charset
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email6")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
assert_nothing_raised { mail.body }
end
@@ -827,30 +929,29 @@ EOF
def test_explicitly_multipart_messages
mail = TestMailer.create_explicitly_multipart_example(@recipient)
assert_equal 3, mail.parts.length
- assert_nil mail.content_type
- assert_equal "text/plain", mail.parts[0].content_type
+ assert_equal 'multipart/mixed', mail.mime_type
+ assert_equal "text/plain", mail.parts[0].mime_type
- assert_equal "text/html", mail.parts[1].content_type
- assert_equal "iso-8859-1", mail.parts[1].sub_header("content-type", "charset")
- assert_equal "inline", mail.parts[1].content_disposition
+ assert_equal "text/html", mail.parts[1].mime_type
+ assert_equal "iso-8859-1", mail.parts[1].charset
- assert_equal "image/jpeg", mail.parts[2].content_type
- assert_equal "attachment", mail.parts[2].content_disposition
- assert_equal "foo.jpg", mail.parts[2].sub_header("content-disposition", "filename")
- assert_equal "foo.jpg", mail.parts[2].sub_header("content-type", "name")
- assert_nil mail.parts[2].sub_header("content-type", "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
+ assert_nil mail.parts[2].charset
end
def test_explicitly_multipart_with_content_type
mail = TestMailer.create_explicitly_multipart_example(@recipient, "multipart/alternative")
assert_equal 3, mail.parts.length
- assert_equal "multipart/alternative", mail.content_type
+ assert_equal "multipart/alternative", mail.mime_type
end
def test_explicitly_multipart_with_invalid_content_type
mail = TestMailer.create_explicitly_multipart_example(@recipient, "text/xml")
assert_equal 3, mail.parts.length
- assert_nil mail.content_type
+ assert_equal 'multipart/mixed', mail.mime_type
end
def test_implicitly_multipart_messages
@@ -858,14 +959,14 @@ EOF
mail = TestMailer.create_implicitly_multipart_example(@recipient)
assert_equal 3, mail.parts.length
- assert_equal "1.0", mail.mime_version
- assert_equal "multipart/alternative", mail.content_type
- assert_equal "application/x-yaml", mail.parts[0].content_type
- assert_equal "utf-8", mail.parts[0].sub_header("content-type", "charset")
- assert_equal "text/plain", mail.parts[1].content_type
- assert_equal "utf-8", mail.parts[1].sub_header("content-type", "charset")
- assert_equal "text/html", mail.parts[2].content_type
- assert_equal "utf-8", mail.parts[2].sub_header("content-type", "charset")
+ assert_equal "1.0", mail.mime_version.to_s
+ assert_equal "multipart/alternative", mail.mime_type
+ assert_equal "text/plain", mail.parts[0].mime_type
+ assert_equal "utf-8", mail.parts[0].charset
+ assert_equal "text/html", mail.parts[1].mime_type
+ assert_equal "utf-8", mail.parts[1].charset
+ assert_equal "application/x-yaml", mail.parts[2].mime_type
+ assert_equal "utf-8", mail.parts[2].charset
end
def test_implicitly_multipart_messages_with_custom_order
@@ -873,41 +974,43 @@ EOF
mail = TestMailer.create_implicitly_multipart_example(@recipient, nil, ["application/x-yaml", "text/plain"])
assert_equal 3, mail.parts.length
- assert_equal "text/html", mail.parts[0].content_type
- assert_equal "text/plain", mail.parts[1].content_type
- assert_equal "application/x-yaml", mail.parts[2].content_type
+ assert_equal "application/x-yaml", mail.parts[0].mime_type
+ assert_equal "text/plain", mail.parts[1].mime_type
+ assert_equal "text/html", mail.parts[2].mime_type
end
def test_implicitly_multipart_messages_with_charset
mail = TestMailer.create_implicitly_multipart_example(@recipient, 'iso-8859-1')
- assert_equal "multipart/alternative", mail.header['content-type'].body
+ assert_equal "multipart/alternative", mail.header['content-type'].content_type
- assert_equal 'iso-8859-1', mail.parts[0].sub_header("content-type", "charset")
- assert_equal 'iso-8859-1', mail.parts[1].sub_header("content-type", "charset")
- assert_equal 'iso-8859-1', mail.parts[2].sub_header("content-type", "charset")
+ assert_equal 'iso-8859-1', mail.parts[0].content_type_parameters[:charset]
+ assert_equal 'iso-8859-1', mail.parts[1].content_type_parameters[:charset]
+ assert_equal 'iso-8859-1', mail.parts[2].content_type_parameters[:charset]
end
def test_html_mail
mail = TestMailer.create_html_mail(@recipient)
- assert_equal "text/html", mail.content_type
+ assert_equal "text/html", mail.mime_type
end
def test_html_mail_with_underscores
mail = TestMailer.create_html_mail_with_underscores(@recipient)
- assert_equal %{<a href="http://google.com" target="_blank">_Google</a>}, mail.body
+ assert_equal %{<a href="http://google.com" target="_blank">_Google</a>}, mail.body.to_s
end
def test_various_newlines
mail = TestMailer.create_various_newlines(@recipient)
assert_equal("line #1\nline #2\nline #3\nline #4\n\n" +
- "line #5\n\nline#6\n\nline #7", mail.body)
+ "line #5\n\nline#6\n\nline #7", mail.body.to_s)
end
def test_various_newlines_multipart
mail = TestMailer.create_various_newlines_multipart(@recipient)
- assert_equal "line #1\nline #2\nline #3\nline #4\n\n", mail.parts[0].body
- assert_equal "<p>line #1</p>\n<p>line #2</p>\n<p>line #3</p>\n<p>line #4</p>\n\n", mail.parts[1].body
+ assert_equal "line #1\nline #2\nline #3\nline #4\n\n", mail.parts[0].body.to_s
+ assert_equal "<p>line #1</p>\n<p>line #2</p>\n<p>line #3</p>\n<p>line #4</p>\n\n", mail.parts[1].body.to_s
+ assert_equal "line #1\r\nline #2\r\nline #3\r\nline #4\r\n\r\n", mail.parts[0].body.encoded
+ assert_equal "<p>line #1</p>\r\n<p>line #2</p>\r\n<p>line #3</p>\r\n<p>line #4</p>\r\n\r\n", mail.parts[1].body.encoded
end
def test_headers_removed_on_smtp_delivery
@@ -935,35 +1038,41 @@ EOF
def test_recursive_multipart_processing
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email7")
- mail = TMail::Mail.parse(fixture)
- assert_equal "This is the first part.\n\nAttachment: test.rb\nAttachment: test.pdf\n\n\nAttachment: smime.p7s\n", mail.body
+ mail = Mail.new(fixture)
+ assert_equal(2, mail.parts.length)
+ assert_equal(4, mail.parts.first.parts.length)
+ assert_equal("This is the first part.", mail.parts.first.parts.first.body.to_s)
+ assert_equal("test.rb", mail.parts.first.parts.second.filename)
+ assert_equal("flowed", mail.parts.first.parts.fourth.content_type_parameters[:format])
+ assert_equal('smime.p7s', mail.parts.second.filename)
end
def test_decode_encoded_attachment_filename
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email8")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
attachment = mail.attachments.last
expected = "01 Quien Te Dij\212at. Pitbull.mp3"
- expected.force_encoding(Encoding::ASCII_8BIT) if expected.respond_to?(:force_encoding)
-
- assert_equal expected, attachment.original_filename
- end
-
- def test_wrong_mail_header
- fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email9")
- assert_raise(TMail::SyntaxError) { TMail::Mail.parse(fixture) }
+
+ if expected.respond_to?(:force_encoding)
+ result = attachment.original_filename.dup
+ expected.force_encoding(Encoding::ASCII_8BIT)
+ result.force_encoding(Encoding::ASCII_8BIT)
+ assert_equal expected, result
+ else
+ assert_equal expected, attachment.original_filename
+ end
end
def test_decode_message_with_unknown_charset
fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email10")
- mail = TMail::Mail.parse(fixture)
+ mail = Mail.new(fixture)
assert_nothing_raised { mail.body }
end
def test_empty_header_values_omitted
result = TestMailer.create_unnamed_attachment(@recipient).encoded
- assert_match %r{Content-Type: application/octet-stream[^;]}, result
+ assert_match %r{Content-Type: application/octet-stream;}, result
assert_match %r{Content-Disposition: attachment[^;]}, result
end
@@ -972,9 +1081,9 @@ EOF
assert !mail.from_addrs.empty?
assert !mail.cc_addrs.empty?
assert !mail.bcc_addrs.empty?
- assert_match(/:/, mail.from_addrs.to_s)
- assert_match(/:/, mail.cc_addrs.to_s)
- assert_match(/:/, mail.bcc_addrs.to_s)
+ assert_match(/:/, mail[:from].decoded)
+ assert_match(/:/, mail[:cc].decoded)
+ assert_match(/:/, mail[:bcc].decoded)
end
def test_deliver_with_mail_object
@@ -986,31 +1095,32 @@ EOF
def test_multipart_with_template_path_with_dots
mail = FunkyPathMailer.create_multipart_with_template_path_with_dots(@recipient)
assert_equal 2, mail.parts.length
- assert "text/plain", mail.parts[1].content_type
+ assert "text/plain", mail.parts[1].mime_type
assert "utf-8", mail.parts[1].charset
end
def test_custom_content_type_attributes
mail = TestMailer.create_custom_content_type_attributes
- assert_match %r{format=flowed}, mail['content-type'].to_s
- assert_match %r{charset=utf-8}, mail['content-type'].to_s
+ assert_match %r{format=flowed}, mail.content_type
+ assert_match %r{charset=utf-8}, mail.content_type
end
def test_return_path_with_create
mail = TestMailer.create_return_path
- assert_equal "<another@somewhere.test>", mail['return-path'].to_s
+ assert_equal "another@somewhere.test", mail['return-path'].to_s
end
def test_return_path_with_deliver
ActionMailer::Base.delivery_method = :smtp
TestMailer.deliver_return_path
- assert_match %r{^Return-Path: <another@somewhere.test>}, MockSMTP.deliveries[0][0]
+ assert_match %r{^Return-Path: another@somewhere.test}, MockSMTP.deliveries[0][0]
assert_equal "another@somewhere.test", MockSMTP.deliveries[0][1].to_s
end
def test_body_is_stored_as_an_ivar
- mail = TestMailer.create_body_ivar(@recipient)
- assert_equal "body: foo\nbar: baz", mail.body
+ mail = nil
+ ActiveSupport::Deprecation.silence { mail = TestMailer.create_body_ivar(@recipient) }
+ assert_equal "body: foo\nbar: baz", mail.body.to_s
end
def test_starttls_is_enabled_if_supported
@@ -1139,6 +1249,6 @@ class RespondToTest < Test::Unit::TestCase
RespondToMailer.not_a_method
end
- assert_match /undefined method.*not_a_method/, error.message
+ assert_match(/undefined method.*not_a_method/, error.message)
end
end
diff --git a/actionmailer/test/mail_test.rb b/actionmailer/test/mail_test.rb
new file mode 100644
index 0000000000..ea6f25d157
--- /dev/null
+++ b/actionmailer/test/mail_test.rb
@@ -0,0 +1,24 @@
+require 'abstract_unit'
+
+class MailTest < Test::Unit::TestCase
+ def test_body
+ m = Mail.new
+ expected = 'something_with_underscores'
+ m.content_transfer_encoding = 'quoted-printable'
+ quoted_body = [expected].pack('*M')
+ m.body = quoted_body
+ assert_equal "something_with_underscores=\r\n", m.body.encoded
+ # CHANGED: body returns object, not string, Changed m.body to m.body.to_s
+ assert_equal expected, m.body.to_s
+ end
+
+ def test_nested_attachments_are_recognized_correctly
+ fixture = File.read("#{File.dirname(__FILE__)}/fixtures/raw_email_with_nested_attachment")
+ mail = Mail.new(fixture)
+ assert_equal 2, mail.attachments.length
+ assert_equal "image/png", mail.attachments.first.mime_type
+ assert_equal 1902, mail.attachments.first.decoded.length
+ assert_equal "application/pkcs7-signature", mail.attachments.last.mime_type
+ end
+
+end
diff --git a/actionmailer/test/quoting_test.rb b/actionmailer/test/quoting_test.rb
index 2fee1379db..7640f4b086 100644
--- a/actionmailer/test/quoting_test.rb
+++ b/actionmailer/test/quoting_test.rb
@@ -6,37 +6,37 @@ class QuotingTest < Test::Unit::TestCase
# Move some tests from TMAIL here
def test_unquote_quoted_printable
a ="=?ISO-8859-1?Q?[166417]_Bekr=E6ftelse_fra_Rejsefeber?="
- b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
+ b = Mail::Encodings.unquote_and_convert_to(a, 'utf-8')
assert_equal "[166417] Bekr\303\246ftelse fra Rejsefeber", b
end
def test_unquote_base64
a ="=?ISO-8859-1?B?WzE2NjQxN10gQmVrcuZmdGVsc2UgZnJhIFJlanNlZmViZXI=?="
- b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
+ b = Mail::Encodings.unquote_and_convert_to(a, 'utf-8')
assert_equal "[166417] Bekr\303\246ftelse fra Rejsefeber", b
end
def test_unquote_without_charset
a ="[166417]_Bekr=E6ftelse_fra_Rejsefeber"
- b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
+ b = Mail::Encodings.unquote_and_convert_to(a, 'utf-8')
assert_equal "[166417]_Bekr=E6ftelse_fra_Rejsefeber", b
end
def test_unqoute_multiple
a ="=?utf-8?q?Re=3A_=5B12=5D_=23137=3A_Inkonsistente_verwendung_von_=22Hin?==?utf-8?b?enVmw7xnZW4i?="
- b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
+ b = Mail::Encodings.unquote_and_convert_to(a, 'utf-8')
assert_equal "Re: [12] #137: Inkonsistente verwendung von \"Hinzuf\303\274gen\"", b
end
def test_unqoute_in_the_middle
a ="Re: Photos =?ISO-8859-1?Q?Brosch=FCre_Rand?="
- b = TMail::Unquoter.unquote_and_convert_to(a, 'utf-8')
+ b = Mail::Encodings.unquote_and_convert_to(a, 'utf-8')
assert_equal "Re: Photos Brosch\303\274re Rand", b
end
def test_unqoute_iso
a ="=?ISO-8859-1?Q?Brosch=FCre_Rand?="
- b = TMail::Unquoter.unquote_and_convert_to(a, 'iso-8859-1')
+ b = Mail::Encodings.unquote_and_convert_to(a, 'iso-8859-1')
expected = "Brosch\374re Rand"
expected.force_encoding 'iso-8859-1' if expected.respond_to?(:force_encoding)
assert_equal expected, b
@@ -50,14 +50,17 @@ class QuotingTest < Test::Unit::TestCase
$:.unshift(File.dirname(__FILE__) + "/../lib/")
if RUBY_VERSION < '1.9'
$KCODE = 'u'
- require 'jcode'
end
require 'action_mailer/quoting'
include ActionMailer::Quoting
quoted_printable(#{original.inspect}, "UTF-8")
CODE
- unquoted = TMail::Unquoter.unquote_and_convert_to(result, nil)
+ unquoted = Mail::Encodings.unquote_and_convert_to(result, nil)
+
+ unquoted.force_encoding(Encoding::ASCII_8BIT) if unquoted.respond_to?(:force_encoding)
+ original.force_encoding(Encoding::ASCII_8BIT) if original.respond_to?(:force_encoding)
+
assert_equal unquoted, original
end
@@ -65,12 +68,16 @@ class QuotingTest < Test::Unit::TestCase
# test an email that has been created using \r\n newlines, instead of
# \n newlines.
def test_email_quoted_with_0d0a
- mail = TMail::Mail.parse(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_quoted_with_0d0a"))
- assert_match %r{Elapsed time}, mail.body
+ mail = Mail.new(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_quoted_with_0d0a"))
+ # CHANGED: subject returns an object now
+ # assert_match %r{Elapsed time}, mail.body
+ assert_match %r{Elapsed time}, mail.body.to_s
end
def test_email_with_partially_quoted_subject
- mail = TMail::Mail.parse(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_with_partially_quoted_subject"))
+ mail = Mail.new(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_with_partially_quoted_subject"))
+ # CHANGED: subject returns an object now
+ # assert_equal "Re: Test: \"\346\274\242\345\255\227\" mid \"\346\274\242\345\255\227\" tail", mail.subject
assert_equal "Re: Test: \"\346\274\242\345\255\227\" mid \"\346\274\242\345\255\227\" tail", mail.subject
end
diff --git a/actionmailer/test/test_helper_test.rb b/actionmailer/test/test_helper_test.rb
index 34c5243936..1fed26f78f 100644
--- a/actionmailer/test/test_helper_test.rb
+++ b/actionmailer/test/test_helper_test.rb
@@ -18,9 +18,9 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
def test_setup_creates_the_expected_mailer
- assert @expected.is_a?(TMail::Mail)
+ assert @expected.is_a?(Mail::Message)
assert_equal "1.0", @expected.mime_version
- assert_equal "text/plain", @expected.content_type
+ assert_equal "text/plain", @expected.mime_type
end
def test_mailer_class_is_correctly_inferred
@@ -92,7 +92,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
end
- assert_match /2 .* but 1/, error.message
+ assert_match(/2 .* but 1/, error.message)
end
def test_assert_emails_too_many_sent
@@ -103,7 +103,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
end
- assert_match /1 .* but 2/, error.message
+ assert_match(/1 .* but 2/, error.message)
end
def test_assert_no_emails_failure
@@ -113,7 +113,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
end
- assert_match /0 .* but 1/, error.message
+ assert_match(/0 .* but 1/, error.message)
end
end
@@ -125,7 +125,7 @@ class AnotherTestHelperMailerTest < ActionMailer::TestCase
end
def test_setup_shouldnt_conflict_with_mailer_setup
- assert @expected.is_a?(TMail::Mail)
+ assert @expected.is_a?(Mail::Message)
assert_equal 'a value', @test_var
end
end
diff --git a/actionmailer/test/tmail_compat_test.rb b/actionmailer/test/tmail_compat_test.rb
new file mode 100644
index 0000000000..a1ca6a7243
--- /dev/null
+++ b/actionmailer/test/tmail_compat_test.rb
@@ -0,0 +1,23 @@
+require 'abstract_unit'
+
+class TmailCompatTest < Test::Unit::TestCase
+
+ def test_set_content_type_raises_deprecation_warning
+ mail = Mail.new
+ STDERR.expects(:puts) # Deprecation warning
+ assert_nothing_raised do
+ mail.set_content_type "text/plain"
+ end
+ assert_equal mail.mime_type, "text/plain"
+ end
+
+ def test_transfer_encoding_raises_deprecation_warning
+ mail = Mail.new
+ STDERR.expects(:puts) # Deprecation warning
+ assert_nothing_raised do
+ mail.transfer_encoding "base64"
+ end
+ assert_equal mail.content_transfer_encoding, "base64"
+ end
+
+end
diff --git a/actionmailer/test/tmail_test.rb b/actionmailer/test/tmail_test.rb
deleted file mode 100644
index 718990e79e..0000000000
--- a/actionmailer/test/tmail_test.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'abstract_unit'
-
-class TMailMailTest < Test::Unit::TestCase
- def test_body
- m = TMail::Mail.new
- expected = 'something_with_underscores'
- m.encoding = 'quoted-printable'
- quoted_body = [expected].pack('*M')
- m.body = quoted_body
- assert_equal "something_with_underscores=\n", m.quoted_body
- assert_equal expected, m.body
- end
-
- def test_nested_attachments_are_recognized_correctly
- fixture = File.read("#{File.dirname(__FILE__)}/fixtures/raw_email_with_nested_attachment")
- mail = TMail::Mail.parse(fixture)
- assert_equal 2, mail.attachments.length
- assert_equal "image/png", mail.attachments.first.content_type
- assert_equal 1902, mail.attachments.first.length
- assert_equal "application/pkcs7-signature", mail.attachments.last.content_type
- end
-end
diff --git a/actionmailer/test/url_test.rb b/actionmailer/test/url_test.rb
index 2224f6321c..12bf609dce 100644
--- a/actionmailer/test/url_test.rb
+++ b/actionmailer/test/url_test.rb
@@ -1,7 +1,9 @@
require 'abstract_unit'
-class TestMailer < ActionMailer::Base
+class WelcomeController < ActionController::Base
+end
+class TestMailer < ActionMailer::Base
default_url_options[:host] = 'www.basecamphq.com'
def signed_up_with_url(recipient)
@@ -10,8 +12,8 @@ class TestMailer < ActionMailer::Base
@from = "system@loudthinking.com"
@sent_on = Time.local(2004, 12, 12)
- @body["recipient"] = recipient
- @body["welcome_url"] = url_for :host => "example.com", :controller => "welcome", :action => "greeting"
+ @recipient = recipient
+ @welcome_url = url_for :host => "example.com", :controller => "welcome", :action => "greeting"
end
class <<self
@@ -31,10 +33,10 @@ class ActionMailerUrlTest < Test::Unit::TestCase
end
def new_mail( charset="utf-8" )
- mail = TMail::Mail.new
+ mail = Mail.new
mail.mime_version = "1.0"
if charset
- mail.set_content_type "text", "plain", { "charset" => charset }
+ mail.content_type ["text", "plain", { "charset" => charset }]
end
mail
end
@@ -52,27 +54,31 @@ class ActionMailerUrlTest < Test::Unit::TestCase
end
def test_signed_up_with_url
- ActionController::Routing.use_controllers! ['welcome'] do
- ActionController::Routing::Routes.draw do |map|
- map.connect ':controller/:action/:id'
- map.welcome 'welcome', :controller=>"foo", :action=>"bar"
- end
-
- expected = new_mail
- expected.to = @recipient
- expected.subject = "[Signed up] Welcome #{@recipient}"
- expected.body = "Hello there, \n\nMr. #{@recipient}. Please see our greeting at http://example.com/welcome/greeting http://www.basecamphq.com/welcome\n\n<img alt=\"Somelogo\" src=\"/images/somelogo.png\" />"
- expected.from = "system@loudthinking.com"
- expected.date = Time.local(2004, 12, 12)
-
- created = nil
- assert_nothing_raised { created = TestMailer.create_signed_up_with_url(@recipient) }
- assert_not_nil created
- assert_equal expected.encoded, created.encoded
-
- assert_nothing_raised { TestMailer.deliver_signed_up_with_url(@recipient) }
- assert_not_nil ActionMailer::Base.deliveries.first
- assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded
+ ActionController::Routing::Routes.draw do |map|
+ map.connect ':controller/:action/:id'
+ map.welcome 'welcome', :controller=>"foo", :action=>"bar"
end
+
+ expected = new_mail
+ expected.to = @recipient
+ expected.subject = "[Signed up] Welcome #{@recipient}"
+ expected.body = "Hello there, \n\nMr. #{@recipient}. Please see our greeting at http://example.com/welcome/greeting http://www.basecamphq.com/welcome\n\n<img alt=\"Somelogo\" src=\"/images/somelogo.png\" />"
+ expected.from = "system@loudthinking.com"
+ expected.date = Time.local(2004, 12, 12)
+
+ created = nil
+ assert_nothing_raised { created = TestMailer.create_signed_up_with_url(@recipient) }
+ assert_not_nil created
+
+ expected.message_id = '<123@456>'
+ created.message_id = '<123@456>'
+ assert_equal expected.encoded, created.encoded
+
+ assert_nothing_raised { TestMailer.deliver_signed_up_with_url(@recipient) }
+ assert_not_nil ActionMailer::Base.deliveries.first
+ delivered = ActionMailer::Base.deliveries.first
+
+ delivered.message_id = '<123@456>'
+ assert_equal expected.encoded, delivered.encoded
end
end
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 30f3f31563..782b4229fb 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,5 +1,19 @@
*Edge*
+* Added ActionDispatch::Request#authorization to access the http authentication header regardless of its proxy hiding [DHH]
+
+* Added :alert, :notice, and :flash as options to ActionController::Base#redirect_to that'll automatically set the proper flash before the redirection [DHH]. Examples:
+
+ flash[:notice] = 'Post was created'
+ redirect_to(@post)
+
+ ...becomes:
+
+ redirect_to(@post, :notice => 'Post was created')
+
+* Added ActionController::Base#notice/= and ActionController::Base#alert/= as a convenience accessors in both the controller and the view for flash[:notice]/= and flash[:alert]/= [DHH]
+
+
* Introduce grouped_collection_select helper. #1249 [Dan Codeape, Erik Ostrom]
* Make sure javascript_include_tag/stylesheet_link_tag does not append ".js" or ".css" onto external urls. #1664 [Matthew Rudy Jacobs]
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 99bdcc95fa..863daa4b44 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -31,7 +31,6 @@ 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.verbose = true
# t.warning = true
end
@@ -45,7 +44,6 @@ desc 'ActiveRecord Integration Tests'
Rake::TestTask.new(:test_active_record_integration) do |t|
t.libs << 'test'
t.test_files = Dir.glob("test/activerecord/*_test.rb")
- t.verbose = true
end
# Genereate the RDoc documentation
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index 2c534642ab..dc91fba64d 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -16,9 +16,9 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', '= 3.0.pre')
s.add_dependency('activemodel', '= 3.0.pre')
- s.add_dependency('rack', '~> 1.0.1')
+ s.add_dependency('rack', '~> 1.1.0')
s.add_dependency('rack-test', '~> 0.5.0')
- s.add_dependency('rack-mount', '~> 0.0.1')
+ s.add_dependency('rack-mount', '~> 0.4.0')
s.add_dependency('erubis', '~> 2.6.5')
s.require_path = 'lib'
diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb
index 1a6c4278c9..237ab577ba 100644
--- a/actionpack/lib/abstract_controller.rb
+++ b/actionpack/lib/abstract_controller.rb
@@ -1,16 +1,18 @@
-require "active_support/core_ext/module/attr_internal"
-require "active_support/core_ext/module/delegation"
+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/module/attr_internal'
+require 'active_support/core_ext/module/delegation'
module AbstractController
- autoload :Base, "abstract_controller/base"
- autoload :Callbacks, "abstract_controller/callbacks"
- autoload :Helpers, "abstract_controller/helpers"
- autoload :Layouts, "abstract_controller/layouts"
- autoload :LocalizedCache, "abstract_controller/localized_cache"
- autoload :Logger, "abstract_controller/logger"
- autoload :RenderingController, "abstract_controller/rendering_controller"
- # === Exceptions
- autoload :ActionNotFound, "abstract_controller/exceptions"
- autoload :DoubleRenderError, "abstract_controller/exceptions"
- autoload :Error, "abstract_controller/exceptions"
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Callbacks
+ autoload :Helpers
+ autoload :Layouts
+ autoload :LocalizedCache
+ autoload :Logger
+ autoload :Rendering
end
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index f5b1c9e4d1..a6889d5d01 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -1,8 +1,11 @@
module AbstractController
+ class Error < StandardError; end
+ class ActionNotFound < StandardError; end
class Base
attr_internal :response_body
attr_internal :action_name
+ attr_internal :formats
class << self
attr_reader :abstract
@@ -69,26 +72,43 @@ module AbstractController
# And always exclude explicitly hidden actions
hidden_actions
end
+
+ # Returns the full controller name, underscored, without the ending Controller.
+ # For instance, MyApp::MyPostsController would return "my_app/my_posts" for
+ # controller_name.
+ #
+ # ==== Returns
+ # String
+ def controller_path
+ @controller_path ||= name && name.sub(/Controller$/, '').underscore
+ end
end
abstract!
# Calls the action going through the entire action dispatch stack.
- #
+ #
# The actual method that is called is determined by calling
# #method_for_action. If no method can handle the action, then an
# ActionNotFound error is raised.
#
# ==== Returns
# self
- def process(action)
+ 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"
end
- process_action(action_name)
+ @_response_body = nil
+
+ process_action(action_name, *args)
+ end
+
+ # Delegates to the class' #controller_path
+ def controller_path
+ self.class.controller_path
end
private
@@ -108,8 +128,8 @@ module AbstractController
# Call the action. Override this in a subclass to modify the
# behavior around processing an action. This, and not #process,
# is the intended way to override action dispatching.
- def process_action(method_name)
- send_action(method_name)
+ def process_action(method_name, *args)
+ send_action(method_name, *args)
end
# Actually call the method associated with the action. Override
diff --git a/actionpack/lib/abstract_controller/exceptions.rb b/actionpack/lib/abstract_controller/exceptions.rb
deleted file mode 100644
index b671516de1..0000000000
--- a/actionpack/lib/abstract_controller/exceptions.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-module AbstractController
- class Error < StandardError; end
- class ActionNotFound < StandardError; end
-
- class DoubleRenderError < Error
- DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"."
-
- def initialize(message = nil)
- super(message || DEFAULT_MESSAGE)
- end
- end
-end
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index d3b492ad09..1d898d1a4c 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -4,7 +4,7 @@ module AbstractController
module Helpers
extend ActiveSupport::Concern
- include RenderingController
+ include Rendering
def self.next_serial
@helper_serial ||= 0
diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb
index c71cef42b2..6fbf6bc392 100644
--- a/actionpack/lib/abstract_controller/layouts.rb
+++ b/actionpack/lib/abstract_controller/layouts.rb
@@ -1,8 +1,164 @@
module AbstractController
+ # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
+ # repeated setups. The inclusion pattern has pages that look like this:
+ #
+ # <%= render "shared/header" %>
+ # Hello World
+ # <%= render "shared/footer" %>
+ #
+ # This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
+ # and if you ever want to change the structure of these two includes, you'll have to change all the templates.
+ #
+ # With layouts, you can flip it around and have the common structure know where to insert changing content. This means
+ # that the header and footer are only mentioned in one place, like this:
+ #
+ # // The header part of this layout
+ # <%= yield %>
+ # // The footer part of this layout
+ #
+ # And then you have content pages that look like this:
+ #
+ # hello world
+ #
+ # At rendering time, the content page is computed and then inserted in the layout, like this:
+ #
+ # // The header part of this layout
+ # hello world
+ # // The footer part of this layout
+ #
+ # == Accessing shared variables
+ #
+ # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
+ # references that won't materialize before rendering time:
+ #
+ # <h1><%= @page_title %></h1>
+ # <%= yield %>
+ #
+ # ...and content pages that fulfill these references _at_ rendering time:
+ #
+ # <% @page_title = "Welcome" %>
+ # Off-world colonies offers you a chance to start a new life
+ #
+ # The result after rendering is:
+ #
+ # <h1>Welcome</h1>
+ # Off-world colonies offers you a chance to start a new life
+ #
+ # == Layout assignment
+ #
+ # You can either specify a layout declaratively (using the #layout class method) or give
+ # it the same name as your controller, and place it in <tt>app/views/layouts</tt>.
+ # If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance.
+ #
+ # For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>,
+ # that template will be used for all actions in PostsController and controllers inheriting
+ # from PostsController.
+ #
+ # If you use a module, for instance Weblog::PostsController, you will need a template named
+ # <tt>app/views/layouts/weblog/posts.html.erb</tt>.
+ #
+ # Since all your controllers inherit from ApplicationController, they will use
+ # <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified
+ # or provided.
+ #
+ # == Inheritance Examples
+ #
+ # class BankController < ActionController::Base
+ # layout "bank_standard"
+ #
+ # class InformationController < BankController
+ #
+ # class TellerController < BankController
+ # # teller.html.erb exists
+ #
+ # class TillController < TellerController
+ #
+ # class VaultController < BankController
+ # layout :access_level_layout
+ #
+ # class EmployeeController < BankController
+ # layout nil
+ #
+ # The InformationController uses "bank_standard" inherited from the BankController, the VaultController overwrites
+ # and picks the layout dynamically, and the EmployeeController doesn't want to use a layout at all.
+ #
+ # The TellerController uses +teller.html.erb+, and TillController inherits that layout and
+ # uses it as well.
+ #
+ # == Types of layouts
+ #
+ # Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
+ # you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
+ # be done either by specifying a method reference as a symbol or using an inline method (as a proc).
+ #
+ # The method reference is the preferred approach to variable layouts and is used like this:
+ #
+ # class WeblogController < ActionController::Base
+ # layout :writers_and_readers
+ #
+ # def index
+ # # fetching posts
+ # end
+ #
+ # private
+ # def writers_and_readers
+ # logged_in? ? "writer_layout" : "reader_layout"
+ # end
+ #
+ # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
+ # is logged in or not.
+ #
+ # If you want to use an inline method, such as a proc, do something like this:
+ #
+ # class WeblogController < ActionController::Base
+ # layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
+ #
+ # 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"
+ #
+ # 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.
+ #
+ # == Conditional layouts
+ #
+ # If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
+ # a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
+ # <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
+ #
+ # class WeblogController < ActionController::Base
+ # layout "weblog_standard", :except => :rss
+ #
+ # # ...
+ #
+ # end
+ #
+ # This will assign "weblog_standard" as the WeblogController's layout except for the +rss+ action, which will not wrap a layout
+ # around the rendered view.
+ #
+ # Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
+ # #<tt>:except => [ :rss, :text_only ]</tt> is valid, as is <tt>:except => :rss</tt>.
+ #
+ # == Using a different layout in the action render call
+ #
+ # If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
+ # Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
+ # You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
+ #
+ # class WeblogController < ActionController::Base
+ # layout "weblog_standard"
+ #
+ # def help
+ # render :action => "help", :layout => "help"
+ # end
+ # end
+ #
+ # This will render the help action with the "help" layout instead of the controller-wide "weblog_standard" layout.
module Layouts
extend ActiveSupport::Concern
- include RenderingController
+ include Rendering
included do
extlib_inheritable_accessor(:_layout_conditions) { Hash.new }
@@ -20,7 +176,7 @@ module AbstractController
end
def clear_template_caches!
- @found_layouts.clear if @found_layouts
+ @found_layouts.clear if defined? @found_layouts
super
end
@@ -89,7 +245,7 @@ module AbstractController
# ==== Returns
# String:: A template name
def _implied_layout_name
- name && name.underscore
+ controller_path
end
# Takes the specified layout and creates a _layout method to be called
diff --git a/actionpack/lib/abstract_controller/localized_cache.rb b/actionpack/lib/abstract_controller/localized_cache.rb
index ee7b43cb9f..bf648af60a 100644
--- a/actionpack/lib/abstract_controller/localized_cache.rb
+++ b/actionpack/lib/abstract_controller/localized_cache.rb
@@ -1,6 +1,6 @@
module AbstractController
class HashKey
- @hash_keys = Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] = {} } }
+ @hash_keys = Hash.new {|h,k| h[k] = Hash.new {|sh,sk| sh[sk] = {} } }
def self.get(klass, formats, locale)
@hash_keys[klass][formats][locale] ||= new(klass, formats, locale)
diff --git a/actionpack/lib/abstract_controller/logger.rb b/actionpack/lib/abstract_controller/logger.rb
index 27ba5be45f..a23a13e1d6 100644
--- a/actionpack/lib/abstract_controller/logger.rb
+++ b/actionpack/lib/abstract_controller/logger.rb
@@ -9,53 +9,5 @@ module AbstractController
cattr_accessor :logger
extend ActiveSupport::Benchmarkable
end
-
- # A class that allows you to defer expensive processing
- # until the logger actually tries to log. Otherwise, you are
- # forced to do the processing in advance, and send the
- # entire processed String to the logger, which might
- # just discard the String if the log level is too low.
- #
- # TODO: Require that Rails loggers accept a block.
- class DelayedLog < ActiveSupport::BasicObject
- def initialize(&block)
- @str, @block = nil, block
- end
-
- def method_missing(*args, &block)
- unless @str
- @str, @block = @block.call, nil
- end
- @str.send(*args, &block)
- end
- end
-
- # Override process_action in the AbstractController::Base
- # to log details about the method.
- def process_action(action)
- result = ActiveSupport::Notifications.instrument(:process_action,
- :controller => self, :action => action) do
- super
- end
-
- if logger
- log = DelayedLog.new do
- "\n\nProcessing #{self.class.name}\##{action_name} " \
- "to #{request.formats} (for #{request_origin}) " \
- "[#{request.method.to_s.upcase}]"
- end
-
- logger.info(log)
- end
-
- result
- end
-
- private
- # Returns the request origin with the IP and time. This needs to be cached,
- # otherwise we would get different results for each time it calls.
- def request_origin
- @request_origin ||= "#{request.remote_ip} at #{Time.now.to_s(:db)}"
- end
end
end
diff --git a/actionpack/lib/abstract_controller/rendering_controller.rb b/actionpack/lib/abstract_controller/rendering.rb
index 7054b9cf26..332d86b089 100644
--- a/actionpack/lib/abstract_controller/rendering_controller.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -1,13 +1,18 @@
-require "abstract_controller/logger"
+require "abstract_controller/base"
module AbstractController
- module RenderingController
- extend ActiveSupport::Concern
+ class DoubleRenderError < Error
+ DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"."
- include AbstractController::Logger
+ def initialize(message = nil)
+ super(message || DEFAULT_MESSAGE)
+ end
+ end
+
+ module Rendering
+ extend ActiveSupport::Concern
included do
- attr_internal :formats
extlib_inheritable_accessor :_view_paths
self._view_paths ||= ActionView::PathSet.new
end
@@ -21,7 +26,7 @@ module AbstractController
# An instance of a view class. The default view class is ActionView::Base
#
# The view class must have the following methods:
- # View.for_controller[controller] Create a new ActionView instance for a
+ # View.for_controller[controller] Create a new ActionView instance for a
# controller
# View#render_partial[options]
# - responsible for setting options[:_template]
@@ -59,7 +64,7 @@ module AbstractController
def render_to_body(options = {})
# TODO: Refactor so we can just use the normal template logic for this
if options.key?(:partial)
- view_context.render_partial(options)
+ _render_partial(options)
else
_determine_template(options)
_render_template(options)
@@ -71,7 +76,7 @@ module AbstractController
#
# :api: plugin
def render_to_string(options = {})
- AbstractController::RenderingController.body_to_s(render_to_body(options))
+ AbstractController::Rendering.body_to_s(render_to_body(options))
end
# Renders the template from an object.
@@ -79,11 +84,18 @@ module AbstractController
# ==== Options
# _template<ActionView::Template>:: The template to render
# _layout<ActionView::Template>:: The layout to wrap the template in (optional)
- # _partial<TrueClass, FalseClass>:: Whether or not the template to be rendered is a partial
def _render_template(options)
view_context.render_template(options)
end
+ # Renders the given partial.
+ #
+ # ==== Options
+ # partial<String|Object>:: The partial name or the object to be rendered
+ def _render_partial(options)
+ view_context.render_partial(options)
+ end
+
# The list of view paths for this controller. See ActionView::ViewPathSet for
# more details about writing custom view paths.
def view_paths
@@ -115,10 +127,10 @@ module AbstractController
# _partial<TrueClass, FalseClass>:: Whether or not the file to look up is a partial
def _determine_template(options)
if options.key?(:text)
- options[:_template] = ActionView::TextTemplate.new(options[:text], format_for_text)
+ options[:_template] = ActionView::Template::Text.new(options[:text], format_for_text)
elsif options.key?(:inline)
- handler = ActionView::Template.handler_class_for_extension(options[:type] || "erb")
- template = ActionView::Template.new(options[:inline], "inline #{options[:inline].inspect}", handler, {})
+ handler = ActionView::Template.handler_class_for_extension(options[:type] || "erb")
+ template = ActionView::Template.new(options[:inline], "inline template", handler, {})
options[:_template] = template
elsif options.key?(:template)
options[:_template_name] = options[:template]
@@ -152,12 +164,12 @@ module AbstractController
module ClassMethods
def clear_template_caches!
end
-
+
# 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
+ # 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)
def append_view_path(path)
self.view_paths << path
@@ -166,8 +178,8 @@ 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
+ # 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)
def prepend_view_path(path)
clear_template_caches!
@@ -186,9 +198,8 @@ module AbstractController
# otherwise, process the parameter into a ViewPathSet.
def view_paths=(paths)
clear_template_caches!
- self._view_paths = paths.is_a?(ActionView::PathSet) ?
- paths : ActionView::Base.process_view_paths(paths)
+ self._view_paths = paths.is_a?(ActionView::PathSet) ? paths : ActionView::Base.process_view_paths(paths)
end
end
end
-end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 03a40e4fce..d66fc3fcc9 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -1,66 +1,76 @@
+activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
+$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
+require 'active_support/ruby/shim'
+
module ActionController
- autoload :Base, "action_controller/base"
- autoload :Benchmarking, "action_controller/metal/benchmarking"
- autoload :ConditionalGet, "action_controller/metal/conditional_get"
- autoload :Configuration, "action_controller/metal/configuration"
- autoload :Head, "action_controller/metal/head"
- autoload :Helpers, "action_controller/metal/helpers"
- autoload :HideActions, "action_controller/metal/hide_actions"
- autoload :Layouts, "action_controller/metal/layouts"
- autoload :Metal, "action_controller/metal"
- autoload :Middleware, "action_controller/middleware"
- autoload :RackConvenience, "action_controller/metal/rack_convenience"
- autoload :Rails2Compatibility, "action_controller/metal/compatibility"
- autoload :Redirector, "action_controller/metal/redirector"
- autoload :RenderingController, "action_controller/metal/rendering_controller"
- autoload :RenderOptions, "action_controller/metal/render_options"
- autoload :Rescue, "action_controller/metal/rescuable"
- autoload :Responder, "action_controller/metal/responder"
- autoload :Session, "action_controller/metal/session"
- autoload :Testing, "action_controller/metal/testing"
- autoload :UrlFor, "action_controller/metal/url_for"
+ extend ActiveSupport::Autoload
- autoload :Caching, 'action_controller/caching'
- autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
- autoload :Integration, 'action_controller/deprecated/integration_test'
- autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
- autoload :MimeResponds, 'action_controller/metal/mime_responds'
- autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
- autoload :PolymorphicRoutes, 'action_controller/polymorphic_routes'
- autoload :RecordIdentifier, 'action_controller/record_identifier'
- autoload :Routing, 'action_controller/deprecated'
- autoload :SessionManagement, 'action_controller/metal/session_management'
- autoload :TestCase, 'action_controller/testing/test_case'
- autoload :TestProcess, 'action_controller/testing/process'
- autoload :UrlRewriter, 'action_controller/url_rewriter'
- autoload :UrlWriter, 'action_controller/url_rewriter'
+ autoload :Base
+ autoload :Caching
+ autoload :PolymorphicRoutes
+ autoload :Translation
+ autoload :Metal
+ autoload :Middleware
- autoload :Verification, 'action_controller/metal/verification'
- autoload :Flash, 'action_controller/metal/flash'
- autoload :RequestForgeryProtection, 'action_controller/metal/request_forgery_protection'
- autoload :Streaming, 'action_controller/metal/streaming'
- autoload :HttpAuthentication, 'action_controller/metal/http_authentication'
- autoload :FilterParameterLogging, 'action_controller/metal/filter_parameter_logging'
- autoload :Translation, 'action_controller/translation'
- autoload :Cookies, 'action_controller/metal/cookies'
+ autoload_under "metal" do
+ autoload :Compatibility
+ autoload :ConditionalGet
+ autoload :Configuration
+ autoload :Cookies
+ autoload :FilterParameterLogging
+ autoload :Flash
+ autoload :Head
+ autoload :Helpers
+ autoload :HideActions
+ autoload :HttpAuthentication
+ autoload :Logger
+ autoload :MimeResponds
+ autoload :RackDelegation
+ autoload :Redirecting
+ autoload :Rendering
+ autoload :Renderers
+ autoload :RequestForgeryProtection
+ autoload :Rescue
+ autoload :Responder
+ autoload :SessionManagement
+ autoload :Streaming
+ autoload :UrlFor
+ autoload :Verification
+ end
- autoload :ActionControllerError, 'action_controller/metal/exceptions'
- autoload :RenderError, 'action_controller/metal/exceptions'
- autoload :RoutingError, 'action_controller/metal/exceptions'
- autoload :MethodNotAllowed, 'action_controller/metal/exceptions'
- autoload :NotImplemented, 'action_controller/metal/exceptions'
- autoload :UnknownController, 'action_controller/metal/exceptions'
- autoload :MissingFile, 'action_controller/metal/exceptions'
- autoload :RenderError, 'action_controller/metal/exceptions'
- autoload :SessionOverflowError, 'action_controller/metal/exceptions'
- autoload :UnknownHttpMethod, 'action_controller/metal/exceptions'
-end
+ autoload :Dispatcher, 'action_controller/dispatch/dispatcher'
+ autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
+ autoload :Routing, 'action_controller/deprecated'
+ autoload :Integration, 'action_controller/deprecated/integration_test'
+ autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
-autoload :HTML, 'action_controller/vendor/html-scanner'
-autoload :AbstractController, 'abstract_controller'
+ eager_autoload do
+ autoload :RecordIdentifier
+ autoload :UrlRewriter
+ autoload :UrlWriter, 'action_controller/url_rewriter'
+
+ # TODO: Don't autoload exceptions, setup explicit
+ # requires for files that need them
+ 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
+ end
+end
+# All of these simply register additional autoloads
+require 'abstract_controller'
require 'action_dispatch'
require 'action_view'
+require 'action_controller/vendor/html-scanner'
# Common ActiveSupport usage in ActionController
require "active_support/concern"
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 4c026fe5f7..b23be66910 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -3,31 +3,28 @@ module ActionController
abstract!
include AbstractController::Callbacks
- include AbstractController::Logger
+ include AbstractController::Layouts
include ActionController::Helpers
include ActionController::HideActions
include ActionController::UrlFor
- include ActionController::Redirector
- include ActionController::RenderingController
- include ActionController::RenderOptions::All
- include ActionController::Layouts
+ include ActionController::Redirecting
+ include ActionController::Rendering
+ include ActionController::Renderers::All
include ActionController::ConditionalGet
- include ActionController::RackConvenience
- include ActionController::Benchmarking
+ include ActionController::RackDelegation
+ include ActionController::Logger
include ActionController::Configuration
# Legacy modules
include SessionManagement
- include ActionDispatch::StatusCodes
include ActionController::Caching
include ActionController::MimeResponds
# Rails 2.x compatibility
- include ActionController::Rails2Compatibility
+ include ActionController::Compatibility
include ActionController::Cookies
- include ActionController::Session
include ActionController::Flash
include ActionController::Verification
include ActionController::RequestForgeryProtection
@@ -91,7 +88,7 @@ module ActionController
end
if options[:status]
- options[:status] = interpret_status(options[:status]).to_i
+ options[:status] = Rack::Utils.status_code(options[:status])
end
options[:update] = blk if block_given?
@@ -107,62 +104,5 @@ module ActionController
options = _normalize_options(action, options, &blk)
super(options)
end
-
- # Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
- #
- # * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
- # * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
- # * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) - 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>: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>
- #
- # Examples:
- # redirect_to :action => "show", :id => 5
- # redirect_to post
- # redirect_to "http://www.rubyonrails.org"
- # redirect_to "/images/screenshot.jpg"
- # redirect_to articles_url
- # redirect_to :back
- #
- # The redirection happens as a "302 Moved" header unless otherwise specified.
- #
- # Examples:
- # redirect_to post_url(@post), :status=>:found
- # redirect_to :action=>'atom', :status=>:moved_permanently
- # redirect_to post_url(@post), :status=>301
- # redirect_to :action=>'atom', :status=>302
- #
- # 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?
-
- status = if options.is_a?(Hash) && options.key?(:status)
- interpret_status(options.delete(:status))
- elsif response_status.key?(:status)
- interpret_status(response_status[:status])
- else
- 302
- end
-
- url = case options
- # The scheme name consist of a letter followed by any combination of
- # letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
- # characters; and is terminated by a colon (":").
- when %r{^\w[\w\d+.-]*:.*}
- options
- when String
- request.protocol + request.host_with_port + options
- when :back
- raise RedirectBackError unless refer = request.headers["Referer"]
- refer
- else
- url_for(options)
- end
-
- super(url, status)
- end
end
end
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index 3caf759032..69ed84da95 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -30,12 +30,15 @@ module ActionController #:nodoc:
# config.action_controller.cache_store = MyOwnStore.new("parameter")
module Caching
extend ActiveSupport::Concern
+ extend ActiveSupport::Autoload
- autoload :Actions, 'action_controller/caching/actions'
- autoload :Fragments, 'action_controller/caching/fragments'
- autoload :Pages, 'action_controller/caching/pages'
- autoload :Sweeper, 'action_controller/caching/sweeping'
- autoload :Sweeping, 'action_controller/caching/sweeping'
+ eager_autoload do
+ autoload :Actions
+ autoload :Fragments
+ autoload :Pages
+ autoload :Sweeper, 'action_controller/caching/sweeping'
+ autoload :Sweeping, 'action_controller/caching/sweeping'
+ end
included do
@@cache_store = nil
@@ -57,6 +60,17 @@ module ActionController #:nodoc:
def cache_configured?
perform_caching && cache_store
end
+
+ def log_event(name, before, after, instrumenter_id, payload)
+ if name.to_s =~ /(read|write|cache|expire|exist)_(fragment|page)\??/
+ key_or_path = payload[:key] || payload[:path]
+ human_name = name.to_s.humanize
+ duration = (after - before) * 1000
+ logger.info("#{human_name} #{key_or_path.inspect} (%.1fms)" % duration)
+ else
+ super
+ end
+ end
end
def caching_allowed?
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
index 8c1167d526..f569d0dd8b 100644
--- a/actionpack/lib/action_controller/caching/fragments.rb
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -74,7 +74,7 @@ module ActionController #:nodoc:
return unless cache_configured?
key = fragment_cache_key(key)
- ActiveSupport::Notifications.instrument(:fragment_exist?, :key => key) do
+ ActiveSupport::Notifications.instrument(:exist_fragment?, :key => key) do
cache_store.exist?(key, options)
end
end
diff --git a/actionpack/lib/action_controller/dispatch/dispatcher.rb b/actionpack/lib/action_controller/dispatch/dispatcher.rb
index e04da42637..cf02757cf6 100644
--- a/actionpack/lib/action_controller/dispatch/dispatcher.rb
+++ b/actionpack/lib/action_controller/dispatch/dispatcher.rb
@@ -13,11 +13,6 @@ module ActionController
# Run prepare callbacks before every request in development mode
self.prepare_each_request = true
- # Development mode callbacks
- ActionDispatch::Callbacks.before_dispatch do |app|
- ActionController::Routing::Routes.reload
- end
-
ActionDispatch::Callbacks.after_dispatch do
# Cleanup the application before processing the current request.
ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord)
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 60b3f9a89b..1819c0f886 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -28,24 +28,9 @@ module ActionController
self.class.controller_name
end
- # Returns the full controller name, underscored, without the ending Controller.
- # For instance, MyApp::MyPostsController would return "my_app/my_posts" for
- # controller_name.
- #
- # ==== Returns
- # String
- def self.controller_path
- @controller_path ||= name && name.sub(/Controller$/, '').underscore
- end
-
- # Delegates to the class' #controller_path
- def controller_path
- self.class.controller_path
- end
-
# The details below can be overridden to support a specific
# Request and Response object. The default ActionController::Base
- # implementation includes RackConvenience, which makes a request
+ # implementation includes RackDelegation, which makes a request
# and response object available. You might wish to control the
# environment and response manually for performance reasons.
@@ -57,7 +42,7 @@ module ActionController
end
# Basic implementations for content_type=, location=, and headers are
- # provided to reduce the dependency on the RackConvenience module
+ # provided to reduce the dependency on the RackDelegation module
# in Renderer and Redirector.
def content_type=(type)
@@ -68,6 +53,10 @@ module ActionController
headers["Location"] = url
end
+ def status=(status)
+ @_status = Rack::Utils.status_code(status)
+ end
+
# :api: private
def dispatch(name, env)
@_env = env
@@ -81,7 +70,7 @@ module ActionController
end
class ActionEndpoint
- @@endpoints = Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] = {} } }
+ @@endpoints = Hash.new {|h,k| h[k] = Hash.new {|sh,sk| sh[sk] = {} } }
def self.for(controller, action, stack)
@@endpoints[controller][action][stack] ||= begin
@@ -92,6 +81,7 @@ module ActionController
def initialize(controller, action)
@controller, @action = controller, action
+ @_formats = [Mime::HTML]
end
def call(env)
diff --git a/actionpack/lib/action_controller/metal/benchmarking.rb b/actionpack/lib/action_controller/metal/benchmarking.rb
deleted file mode 100644
index e58df69172..0000000000
--- a/actionpack/lib/action_controller/metal/benchmarking.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-require 'active_support/core_ext/benchmark'
-
-module ActionController #:nodoc:
- # The benchmarking module times the performance of actions and reports to the logger. If the Active Record
- # package has been included, a separate timing section for database calls will be added as well.
- module Benchmarking #:nodoc:
- extend ActiveSupport::Concern
-
- protected
- def render(*args, &block)
- if logger
- if Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
- db_runtime = ActiveRecord::Base.connection.reset_runtime
- end
-
- render_output = nil
- @view_runtime = Benchmark.ms { render_output = super }
-
- if Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
- @db_rt_before_render = db_runtime
- @db_rt_after_render = ActiveRecord::Base.connection.reset_runtime
- @view_runtime -= @db_rt_after_render
- end
-
- render_output
- else
- super
- end
- end
-
- private
- def process_action(*args)
- if logger
- ms = [Benchmark.ms { super }, 0.01].max
- logging_view = defined?(@view_runtime)
- logging_active_record = Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
-
- log_message = 'Completed in %.0fms' % ms
-
- if logging_view || logging_active_record
- log_message << " ("
- log_message << view_runtime if logging_view
-
- if logging_active_record
- log_message << ", " if logging_view
- log_message << active_record_runtime + ")"
- else
- ")"
- end
- end
-
- log_message << " | #{response.status}"
- log_message << " [#{complete_request_uri rescue "unknown"}]"
-
- logger.info(log_message)
- response.headers["X-Runtime"] = "%.0f" % ms
- else
- super
- end
- end
-
- def view_runtime
- "View: %.0f" % @view_runtime
- end
-
- def active_record_runtime
- db_runtime = ActiveRecord::Base.connection.reset_runtime
- db_runtime += @db_rt_before_render if @db_rt_before_render
- db_runtime += @db_rt_after_render if @db_rt_after_render
- "DB: %.0f" % db_runtime
- end
- end
-end
diff --git a/actionpack/lib/action_controller/metal/compatibility.rb b/actionpack/lib/action_controller/metal/compatibility.rb
index c251d79f4e..a90f798cd5 100644
--- a/actionpack/lib/action_controller/metal/compatibility.rb
+++ b/actionpack/lib/action_controller/metal/compatibility.rb
@@ -1,5 +1,5 @@
module ActionController
- module Rails2Compatibility
+ module Compatibility
extend ActiveSupport::Concern
class ::ActionController::ActionControllerError < StandardError #:nodoc:
@@ -46,11 +46,8 @@ module ActionController
cattr_accessor :use_accept_header
self.use_accept_header = true
- cattr_accessor :page_cache_directory
self.page_cache_directory = defined?(Rails.public_path) ? Rails.public_path : ""
- cattr_reader :cache_store
-
cattr_accessor :consider_all_requests_local
self.consider_all_requests_local = true
@@ -116,7 +113,7 @@ module ActionController
details[:prefix] = nil if name =~ /\blayouts/
super
end
-
+
# Move this into a "don't run in production" module
def _default_layout(details, require_layout = false)
super
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index 5156fbc1d5..61e7ece90d 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -2,7 +2,7 @@ module ActionController
module ConditionalGet
extend ActiveSupport::Concern
- include RackConvenience
+ include RackDelegation
include Head
# Sets the etag, last_modified, or both on the response and renders a
diff --git a/actionpack/lib/action_controller/metal/cookies.rb b/actionpack/lib/action_controller/metal/cookies.rb
index 6855ca1478..5b51bd21d0 100644
--- a/actionpack/lib/action_controller/metal/cookies.rb
+++ b/actionpack/lib/action_controller/metal/cookies.rb
@@ -46,17 +46,18 @@ module ActionController #:nodoc:
module Cookies
extend ActiveSupport::Concern
- include RackConvenience
+ include RackDelegation
included do
helper_method :cookies
+ cattr_accessor :cookie_verifier_secret
end
- protected
- # Returns the cookie container, which operates as described above.
- def cookies
- @cookies ||= CookieJar.build(request, response)
- end
+ protected
+ # Returns the cookie container, which operates as described above.
+ def cookies
+ @cookies ||= CookieJar.build(request, response)
+ end
end
class CookieJar < Hash #:nodoc:
@@ -86,7 +87,7 @@ module ActionController #:nodoc:
end
super(key.to_s, value)
-
+
options[:path] ||= "/"
response.set_cookie(key, options)
end
@@ -101,5 +102,96 @@ module ActionController #:nodoc:
response.delete_cookie(key, options)
value
end
+
+ # Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example:
+ #
+ # cookies.permanent[:prefers_open_id] = true
+ # # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+ #
+ # This jar is only meant for writing. You'll read permanent cookies through the regular accessor.
+ #
+ # This jar allows chaining with the signed jar as well, so you can set permanent, signed cookies. Examples:
+ #
+ # cookies.permanent.signed[:remember_me] = current_user.id
+ # # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+ def permanent
+ @permanent ||= PermanentCookieJar.new(self)
+ end
+
+ # Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from
+ # the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
+ # cookie was tampered with by the user (or a 3rd party), an ActiveSupport::MessageVerifier::InvalidSignature exception will
+ # be raised.
+ #
+ # This jar requires that you set a suitable secret for the verification on ActionController::Base.cookie_verifier_secret.
+ #
+ # Example:
+ #
+ # cookies.signed[:discount] = 45
+ # # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
+ #
+ # cookies.signed[:discount] # => 45
+ def signed
+ @signed ||= SignedCookieJar.new(self)
+ end
+ end
+
+ class PermanentCookieJar < CookieJar #:nodoc:
+ def initialize(parent_jar)
+ @parent_jar = parent_jar
+ end
+
+ def []=(key, options)
+ if options.is_a?(Hash)
+ options.symbolize_keys!
+ else
+ options = { :value => options }
+ end
+
+ options[:expires] = 20.years.from_now
+ @parent_jar[key] = options
+ end
+
+ def signed
+ @signed ||= SignedCookieJar.new(self)
+ end
+
+ def controller
+ @parent_jar.controller
+ end
+
+ def method_missing(method, *arguments, &block)
+ @parent_jar.send(method, *arguments, &block)
+ end
+ end
+
+ class SignedCookieJar < CookieJar #:nodoc:
+ def initialize(parent_jar)
+ unless ActionController::Base.cookie_verifier_secret
+ raise "You must set ActionController::Base.cookie_verifier_secret to use signed cookies"
+ end
+
+ @parent_jar = parent_jar
+ @verifier = ActiveSupport::MessageVerifier.new(ActionController::Base.cookie_verifier_secret)
+ end
+
+ def [](name)
+ @verifier.verify(@parent_jar[name])
+ end
+
+ def []=(key, options)
+ if options.is_a?(Hash)
+ options.symbolize_keys!
+ options[:value] = @verifier.generate(options[:value])
+ else
+ options = { :value => @verifier.generate(options) }
+ end
+
+ @parent_jar[key] = options
+ end
+
+ def method_missing(method, *arguments, &block)
+ @parent_jar.send(method, *arguments, &block)
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb
index b9d23da3e0..07024d0a9a 100644
--- a/actionpack/lib/action_controller/metal/exceptions.rb
+++ b/actionpack/lib/action_controller/metal/exceptions.rb
@@ -18,18 +18,9 @@ module ActionController
def initialize(*allowed_methods)
super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
- @allowed_methods = allowed_methods
- end
-
- def allowed_methods_header
- allowed_methods.map { |method_symbol| method_symbol.to_s.upcase } * ', '
- end
-
- def handle_response!(response)
- response.headers['Allow'] ||= allowed_methods_header
end
end
-
+
class NotImplemented < MethodNotAllowed #:nodoc:
end
diff --git a/actionpack/lib/action_controller/metal/filter_parameter_logging.rb b/actionpack/lib/action_controller/metal/filter_parameter_logging.rb
index a53c052075..59e200396a 100644
--- a/actionpack/lib/action_controller/metal/filter_parameter_logging.rb
+++ b/actionpack/lib/action_controller/metal/filter_parameter_logging.rb
@@ -2,8 +2,6 @@ module ActionController
module FilterParameterLogging
extend ActiveSupport::Concern
- include AbstractController::Logger
-
module ClassMethods
# Replace sensitive parameter data from the request log.
# Filters parameters that have any of the arguments as a substring.
@@ -54,23 +52,25 @@ module ActionController
end
protected :filter_parameters
end
- end
- INTERNAL_PARAMS = [:controller, :action, :format, :_method, :only_path]
+ protected
- def process(*)
- response = super
- if logger
- parameters = filter_parameters(params).except!(*INTERNAL_PARAMS)
- logger.info { " Parameters: #{parameters.inspect}" } unless parameters.empty?
+ # Overwrite log_process_action to include parameters information.
+ # If this method is invoked, it means logger is defined, so don't
+ # worry with such scenario here.
+ def log_process_action(controller) #:nodoc:
+ params = controller.send(:filter_parameters, controller.request.params)
+ logger.info " Parameters: #{params.inspect}" unless params.empty?
+ super
end
- response
end
+ INTERNAL_PARAMS = [:controller, :action, :format, :_method, :only_path]
+
protected
def filter_parameters(params)
- params.dup
+ params.dup.except!(*INTERNAL_PARAMS)
end
end
diff --git a/actionpack/lib/action_controller/metal/flash.rb b/actionpack/lib/action_controller/metal/flash.rb
index feb066a6f6..25e25940a7 100644
--- a/actionpack/lib/action_controller/metal/flash.rb
+++ b/actionpack/lib/action_controller/metal/flash.rb
@@ -28,7 +28,9 @@ module ActionController #:nodoc:
module Flash
extend ActiveSupport::Concern
- include Session
+ included do
+ helper_method :alert, :notice
+ end
class FlashNow #:nodoc:
def initialize(flash)
@@ -121,30 +123,18 @@ module ActionController #:nodoc:
session["flash"] = self
end
- private
- # Used internally by the <tt>keep</tt> and <tt>discard</tt> methods
- # use() # marks the entire flash as used
- # use('msg') # marks the "msg" entry as used
- # use(nil, false) # marks the entire flash as unused (keeps it around for one more action)
- # use('msg', false) # marks the "msg" entry as unused (keeps it around for one more action)
- # Returns the single value for the key you asked to be marked (un)used or the FlashHash itself
- # if no key is passed.
- def use(key = nil, used = true)
- Array(key || keys).each { |k| used ? @used << k : @used.delete(k) }
- return key ? self[key] : self
- end
- end
-
- protected
- def process_action(method_name)
- super
- @_flash.store(session) if @_flash
- @_flash = nil
- end
-
- def reset_session
- super
- @_flash = nil
+ private
+ # Used internally by the <tt>keep</tt> and <tt>discard</tt> methods
+ # use() # marks the entire flash as used
+ # use('msg') # marks the "msg" entry as used
+ # use(nil, false) # marks the entire flash as unused (keeps it around for one more action)
+ # use('msg', false) # marks the "msg" entry as unused (keeps it around for one more action)
+ # Returns the single value for the key you asked to be marked (un)used or the FlashHash itself
+ # if no key is passed.
+ def use(key = nil, used = true)
+ Array(key || keys).each { |k| used ? @used << k : @used.delete(k) }
+ return key ? self[key] : self
+ end
end
# Access the contents of the flash. Use <tt>flash["notice"]</tt> to
@@ -158,5 +148,54 @@ module ActionController #:nodoc:
@_flash
end
+
+ # Convenience accessor for flash[:alert]
+ def alert
+ flash[:alert]
+ end
+
+ # Convenience accessor for flash[:alert]=
+ def alert=(message)
+ flash[:alert] = message
+ end
+
+ # Convenience accessor for flash[:notice]
+ def notice
+ flash[:notice]
+ end
+
+ # Convenience accessor for flash[:notice]=
+ def notice=(message)
+ flash[:notice] = message
+ end
+
+ protected
+ def process_action(method_name)
+ @_flash = nil
+ super
+ @_flash.store(session) if @_flash
+ @_flash = nil
+ end
+
+ def reset_session
+ super
+ @_flash = nil
+ end
+
+ def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
+ if alert = response_status_and_flash.delete(:alert)
+ flash[:alert] = alert
+ end
+
+ if notice = response_status_and_flash.delete(:notice)
+ flash[:notice] = notice
+ end
+
+ if other_flashes = response_status_and_flash.delete(:flash)
+ flash.update(other_flashes)
+ end
+
+ super(options, response_status_and_flash)
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 68fa0a0402..c82d9cf369 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -1,5 +1,7 @@
module ActionController
module Head
+ include 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
@@ -21,7 +23,10 @@ module ActionController
headers[key.to_s.dasherize.split(/-/).map { |v| v.capitalize }.join("-")] = value.to_s
end
- render :nothing => true, :status => status, :location => location
+ self.status = status
+ self.location = url_for(location) if location
+ self.content_type = Mime[formats.first]
+ self.response_body = " "
end
end
end \ No newline at end of file
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
index b4325e24ad..d0402e5bad 100644
--- a/actionpack/lib/action_controller/metal/helpers.rb
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -52,7 +52,7 @@ module ActionController
included do
# Set the default directory for helpers
extlib_inheritable_accessor(:helpers_dir) do
- defined?(Rails) ? "#{Rails.root}/app/helpers" : "app/helpers"
+ defined?(Rails.root) ? "#{Rails.root}/app/helpers" : "app/helpers"
end
end
diff --git a/actionpack/lib/action_controller/metal/layouts.rb b/actionpack/lib/action_controller/metal/layouts.rb
deleted file mode 100644
index cc7088248a..0000000000
--- a/actionpack/lib/action_controller/metal/layouts.rb
+++ /dev/null
@@ -1,171 +0,0 @@
-module ActionController
- # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
- # repeated setups. The inclusion pattern has pages that look like this:
- #
- # <%= render "shared/header" %>
- # Hello World
- # <%= render "shared/footer" %>
- #
- # This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
- # and if you ever want to change the structure of these two includes, you'll have to change all the templates.
- #
- # With layouts, you can flip it around and have the common structure know where to insert changing content. This means
- # that the header and footer are only mentioned in one place, like this:
- #
- # // The header part of this layout
- # <%= yield %>
- # // The footer part of this layout
- #
- # And then you have content pages that look like this:
- #
- # hello world
- #
- # At rendering time, the content page is computed and then inserted in the layout, like this:
- #
- # // The header part of this layout
- # hello world
- # // The footer part of this layout
- #
- # == Accessing shared variables
- #
- # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
- # references that won't materialize before rendering time:
- #
- # <h1><%= @page_title %></h1>
- # <%= yield %>
- #
- # ...and content pages that fulfill these references _at_ rendering time:
- #
- # <% @page_title = "Welcome" %>
- # Off-world colonies offers you a chance to start a new life
- #
- # The result after rendering is:
- #
- # <h1>Welcome</h1>
- # Off-world colonies offers you a chance to start a new life
- #
- # == Layout assignment
- #
- # You can either specify a layout declaratively (using the #layout class method) or give
- # it the same name as your controller, and place it in <tt>app/views/layouts</tt>.
- # If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance.
- #
- # For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>,
- # that template will be used for all actions in PostsController and controllers inheriting
- # from PostsController.
- #
- # If you use a module, for instance Weblog::PostsController, you will need a template named
- # <tt>app/views/layouts/weblog/posts.html.erb</tt>.
- #
- # Since all your controllers inherit from ApplicationController, they will use
- # <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified
- # or provided.
- #
- # == Inheritance Examples
- #
- # class BankController < ActionController::Base
- # layout "bank_standard"
- #
- # class InformationController < BankController
- #
- # class TellerController < BankController
- # # teller.html.erb exists
- #
- # class TillController < TellerController
- #
- # class VaultController < BankController
- # layout :access_level_layout
- #
- # class EmployeeController < BankController
- # layout nil
- #
- # The InformationController uses "bank_standard" inherited from the BankController, the VaultController overwrites
- # and picks the layout dynamically, and the EmployeeController doesn't want to use a layout at all.
- #
- # The TellerController uses +teller.html.erb+, and TillController inherits that layout and
- # uses it as well.
- #
- # == Types of layouts
- #
- # Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
- # you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
- # be done either by specifying a method reference as a symbol or using an inline method (as a proc).
- #
- # The method reference is the preferred approach to variable layouts and is used like this:
- #
- # class WeblogController < ActionController::Base
- # layout :writers_and_readers
- #
- # def index
- # # fetching posts
- # end
- #
- # private
- # def writers_and_readers
- # logged_in? ? "writer_layout" : "reader_layout"
- # end
- #
- # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
- # is logged in or not.
- #
- # If you want to use an inline method, such as a proc, do something like this:
- #
- # class WeblogController < ActionController::Base
- # layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
- #
- # 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"
- #
- # 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.
- #
- # == Conditional layouts
- #
- # If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
- # a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
- # <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
- #
- # class WeblogController < ActionController::Base
- # layout "weblog_standard", :except => :rss
- #
- # # ...
- #
- # end
- #
- # This will assign "weblog_standard" as the WeblogController's layout except for the +rss+ action, which will not wrap a layout
- # around the rendered view.
- #
- # Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
- # #<tt>:except => [ :rss, :text_only ]</tt> is valid, as is <tt>:except => :rss</tt>.
- #
- # == Using a different layout in the action render call
- #
- # If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
- # Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
- # You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
- #
- # class WeblogController < ActionController::Base
- # layout "weblog_standard"
- #
- # def help
- # render :action => "help", :layout => "help"
- # end
- # end
- #
- # This will render the help action with the "help" layout instead of the controller-wide "weblog_standard" layout.
- module Layouts
- extend ActiveSupport::Concern
-
- include ActionController::RenderingController
- include AbstractController::Layouts
-
- module ClassMethods
- # If no layout is provided, look for a layout with this name.
- def _implied_layout_name
- controller_path
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/metal/logger.rb b/actionpack/lib/action_controller/metal/logger.rb
new file mode 100644
index 0000000000..4f4370e5f0
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/logger.rb
@@ -0,0 +1,89 @@
+require 'abstract_controller/logger'
+
+module ActionController
+ # Adds instrumentation to <tt>process_action</tt> and a <tt>log_event</tt> method
+ # responsible to log events from ActiveSupport::Notifications. This module handles
+ # :process_action and :render_template events but allows any other module to hook
+ # into log_event and provide its own logging facilities (as in ActionController::Caching).
+ module Logger
+ extend ActiveSupport::Concern
+
+ included do
+ include AbstractController::Logger
+ end
+
+ attr_internal :view_runtime
+
+ def process_action(action)
+ ActiveSupport::Notifications.instrument(:process_action, :controller => self, :action => action) do
+ super
+ end
+ end
+
+ def render(*args, &block)
+ if logger
+ render_output = nil
+
+ self.view_runtime = cleanup_view_runtime do
+ Benchmark.ms { render_output = super }
+ end
+
+ render_output
+ else
+ super
+ end
+ end
+
+ # If you want to remove any time taken into account in :view_runtime
+ # wrongly, you can do it here:
+ #
+ # def cleanup_view_runtime
+ # super - time_taken_in_something_expensive
+ # end
+ #
+ # :api: plugin
+ def cleanup_view_runtime #:nodoc:
+ yield
+ end
+
+ module ClassMethods
+ # This is the hook invoked by ActiveSupport::Notifications.subscribe.
+ # If you need to log any event, overwrite the method and do it here.
+ def log_event(name, before, after, instrumenter_id, payload) #:nodoc:
+ if name == :process_action
+ duration = [(after - before) * 1000, 0.01].max
+ controller = payload[:controller]
+ request = controller.request
+
+ logger.info "\n\nProcessed #{controller.class.name}##{payload[:action]} " \
+ "to #{request.formats} (for #{request.remote_ip} at #{before.to_s(:db)}) " \
+ "[#{request.method.to_s.upcase}]"
+
+ log_process_action(controller)
+
+ message = "Completed in %.0fms" % duration
+ message << " | #{controller.response.status}"
+ message << " [#{request.request_uri rescue "unknown"}]"
+
+ logger.info(message)
+ elsif name == :render_template
+ # TODO Make render_template logging work if you are using just ActionView
+ duration = (after - before) * 1000
+ message = "Rendered #{payload[:identifier]}"
+ message << " within #{payload[:layout]}" if payload[:layout]
+ message << (" (%.1fms)" % duration)
+ logger.info(message)
+ end
+ end
+
+ protected
+
+ # A hook which allows logging what happened during controller process action.
+ # :api: plugin
+ def log_process_action(controller) #:nodoc:
+ view_runtime = controller.send :view_runtime
+ logger.info(" View runtime: %.1fms" % view_runtime.to_f) if view_runtime
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_controller/metal/rack_convenience.rb b/actionpack/lib/action_controller/metal/rack_delegation.rb
index 131d20114d..bb55383631 100644
--- a/actionpack/lib/action_controller/metal/rack_convenience.rb
+++ b/actionpack/lib/action_controller/metal/rack_delegation.rb
@@ -1,8 +1,12 @@
+require 'action_dispatch/http/request'
+require 'action_dispatch/http/response'
+
module ActionController
- module RackConvenience
+ module RackDelegation
extend ActiveSupport::Concern
included do
+ delegate :session, :to => "@_request"
delegate :headers, :status=, :location=, :content_type=,
:status, :location, :content_type, :to => "@_response"
attr_internal :request
@@ -23,5 +27,9 @@ module ActionController
response.body = body if response
super
end
+
+ def reset_session
+ @_request.reset_session
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb
new file mode 100644
index 0000000000..7a2f9a6fc5
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/redirecting.rb
@@ -0,0 +1,90 @@
+module ActionController
+ class RedirectBackError < AbstractController::Error #:nodoc:
+ DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
+
+ def initialize(message = nil)
+ super(message || DEFAULT_MESSAGE)
+ end
+ end
+
+ module Redirecting
+ extend ActiveSupport::Concern
+ include AbstractController::Logger
+
+ # Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
+ #
+ # * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
+ # * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
+ # * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) - 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>: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>
+ #
+ # Examples:
+ # redirect_to :action => "show", :id => 5
+ # redirect_to post
+ # redirect_to "http://www.rubyonrails.org"
+ # redirect_to "/images/screenshot.jpg"
+ # redirect_to articles_url
+ # redirect_to :back
+ #
+ # The redirection happens as a "302 Moved" header unless otherwise specified.
+ #
+ # Examples:
+ # redirect_to post_url(@post), :status => :found
+ # redirect_to :action=>'atom', :status => :moved_permanently
+ # redirect_to post_url(@post), :status => 301
+ # redirect_to :action=>'atom', :status => 302
+ #
+ # 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.
+ #
+ # Examples:
+ # redirect_to post_url(@post), :alert => "Watch it, mister!"
+ # redirect_to post_url(@post), :status=> :found, :notice => "Pay attention to the road"
+ # redirect_to post_url(@post), :status => 301, :flash => { :updated_post_id => @post.id }
+ # redirect_to { :action=>'atom' }, :alert => "Something serious happened"
+ #
+ # When using <tt>redirect_to :back</tt>, if there is no referrer,
+ # 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?
+ raise AbstractController::DoubleRenderError if response_body
+
+ self.status = _extract_redirect_to_status(options, response_status)
+ self.location = _compute_redirect_to_location(options)
+ self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.h(location)}\">redirected</a>.</body></html>"
+
+ logger.info("Redirected to #{location}") if logger && logger.info?
+ end
+
+ private
+ def _extract_redirect_to_status(options, response_status)
+ status = if options.is_a?(Hash) && options.key?(:status)
+ Rack::Utils.status_code(options.delete(:status))
+ elsif response_status.key?(:status)
+ Rack::Utils.status_code(response_status[:status])
+ else
+ 302
+ end
+ end
+
+ def _compute_redirect_to_location(options)
+ case options
+ # The scheme name consist of a letter followed by any combination of
+ # letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
+ # characters; and is terminated by a colon (":").
+ when %r{^\w[\w\d+.-]*:.*}
+ options
+ when String
+ request.protocol + request.host_with_port + options
+ when :back
+ raise RedirectBackError unless refer = request.headers["Referer"]
+ refer
+ else
+ url_for(options)
+ end.gsub(/[\r\n]/, '')
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/redirector.rb b/actionpack/lib/action_controller/metal/redirector.rb
deleted file mode 100644
index b55f5e7bfc..0000000000
--- a/actionpack/lib/action_controller/metal/redirector.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-module ActionController
- class RedirectBackError < AbstractController::Error #:nodoc:
- DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
-
- def initialize(message = nil)
- super(message || DEFAULT_MESSAGE)
- end
- end
-
- module Redirector
- extend ActiveSupport::Concern
- include AbstractController::Logger
-
- def redirect_to(url, status) #:doc:
- raise AbstractController::DoubleRenderError if response_body
- logger.info("Redirected to #{url}") if logger && logger.info?
- self.status = status
- self.location = url.gsub(/[\r\n]/, '')
- self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.h(url)}\">redirected</a>.</body></html>"
- end
- end
-end
diff --git a/actionpack/lib/action_controller/metal/render_options.rb b/actionpack/lib/action_controller/metal/render_options.rb
deleted file mode 100644
index 0d69ca10df..0000000000
--- a/actionpack/lib/action_controller/metal/render_options.rb
+++ /dev/null
@@ -1,103 +0,0 @@
-module ActionController
- module RenderOptions
- extend ActiveSupport::Concern
-
- included do
- extlib_inheritable_accessor :_renderers
- self._renderers = []
- end
-
- module ClassMethods
- def _write_render_options
- renderers = _renderers.map do |r|
- <<-RUBY_EVAL
- if options.key?(:#{r})
- _process_options(options)
- return render_#{r}(options[:#{r}], options)
- end
- RUBY_EVAL
- end
-
- class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- def _handle_render_options(options)
- #{renderers.join}
- end
- RUBY_EVAL
- end
-
- def _add_render_option(name)
- _renderers << name
- _write_render_options
- end
- end
-
- def render_to_body(options)
- _handle_render_options(options) || super
- end
- end
-
- module RenderOption #:nodoc:
- def self.extended(base)
- base.extend ActiveSupport::Concern
- base.send :include, ::ActionController::RenderOptions
-
- def base.register_renderer(name)
- included { _add_render_option(name) }
- end
- end
- end
-
- module RenderOptions
- module Json
- extend RenderOption
- register_renderer :json
-
- def render_json(json, options)
- json = ActiveSupport::JSON.encode(json) unless json.respond_to?(:to_str)
- json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
- self.content_type ||= Mime::JSON
- self.response_body = json
- end
- end
-
- module Js
- extend RenderOption
- register_renderer :js
-
- def render_js(js, options)
- self.content_type ||= Mime::JS
- self.response_body = js.respond_to?(:to_js) ? js.to_js : js
- end
- end
-
- module Xml
- extend RenderOption
- register_renderer :xml
-
- def render_xml(xml, options)
- self.content_type ||= Mime::XML
- self.response_body = xml.respond_to?(:to_xml) ? xml.to_xml : xml
- end
- end
-
- module RJS
- extend RenderOption
- register_renderer :update
-
- def render_update(proc, options)
- generator = ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.new(view_context, &proc)
- self.content_type = Mime::JS
- self.response_body = generator.to_s
- end
- end
-
- module All
- extend ActiveSupport::Concern
-
- include ActionController::RenderOptions::Json
- include ActionController::RenderOptions::Js
- include ActionController::RenderOptions::Xml
- include ActionController::RenderOptions::RJS
- end
- end
-end
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
new file mode 100644
index 0000000000..c1ba47927a
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -0,0 +1,91 @@
+module ActionController
+ def self.add_renderer(key, &block)
+ Renderers.add(key, &block)
+ end
+
+ module Renderers
+ extend ActiveSupport::Concern
+
+ included do
+ extlib_inheritable_accessor :_renderers
+ self._renderers = {}
+ 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[:#{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)
+ args.each do |key|
+ _renderers[key] = RENDERERS[key]
+ end
+ _write_render_options
+ end
+ alias use_renderer use_renderers
+ end
+
+ def render_to_body(options)
+ _handle_render_options(options) || super
+ end
+
+ RENDERERS = {}
+ 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) unless json.respond_to?(:to_str)
+ json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
+ self.content_type ||= Mime::JSON
+ self.response_body = json
+ end
+
+ add :js do |js, options|
+ self.content_type ||= Mime::JS
+ self.response_body = js.respond_to?(:to_js) ? js.to_js : js
+ end
+
+ add :xml do |xml, options|
+ self.content_type ||= Mime::XML
+ self.response_body = xml.respond_to?(:to_xml) ? xml.to_xml : xml
+ end
+
+ add :update do |proc, options|
+ generator = ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.new(view_context, &proc)
+ self.content_type = Mime::JS
+ self.response_body = generator.to_s
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/rendering_controller.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 237299cd30..74e50bb032 100644
--- a/actionpack/lib/action_controller/metal/rendering_controller.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -1,9 +1,9 @@
module ActionController
- module RenderingController
+ module Rendering
extend ActiveSupport::Concern
included do
- include AbstractController::RenderingController
+ include AbstractController::Rendering
include AbstractController::LocalizedCache
end
@@ -20,12 +20,6 @@ module ActionController
def render_to_body(options)
_process_options(options)
-
- if options.key?(:partial)
- options[:partial] = action_name if options[:partial] == true
- options[:_details] = {:formats => formats}
- end
-
super
end
@@ -43,6 +37,12 @@ module ActionController
super
end
+ def _render_partial(options)
+ options[:partial] = action_name if options[:partial] == true
+ options[:_details] = {:formats => formats}
+ super
+ end
+
def format_for_text
formats.first
end
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 113c20a758..f1fb4d7ce5 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -5,7 +5,7 @@ module ActionController #:nodoc:
module RequestForgeryProtection
extend ActiveSupport::Concern
- include AbstractController::Helpers, Session
+ include AbstractController::Helpers
included do
# Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
@@ -13,37 +13,37 @@ module ActionController #:nodoc:
cattr_accessor :request_forgery_protection_token
# Controls whether request forgergy protection is turned on or not. Turned off by default only in test mode.
- class_inheritable_accessor :allow_forgery_protection
+ extlib_inheritable_accessor :allow_forgery_protection
self.allow_forgery_protection = true
helper_method :form_authenticity_token
helper_method :protect_against_forgery?
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
+
+ # 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
+ # 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.
#
# 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
+ # 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.
#
- # 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
+ # 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
+ # 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:
@@ -52,11 +52,11 @@ module ActionController #:nodoc:
#
# 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
+ # * Make sure the session cookies that Rails creates are non-persistent. Check in Firefox and look
# for "Expires: at end of session"
#
module ClassMethods
@@ -92,7 +92,7 @@ module ActionController #:nodoc:
# * is it a GET request? Gets should be safe and idempotent
# * Does the form_authenticity_token match the given token value from the params?
def verified_request?
- !protect_against_forgery? || request.forgery_whitelisted? ||
+ !protect_against_forgery? || request.forgery_whitelisted? ||
form_authenticity_token == params[request_forgery_protection_token]
end
@@ -101,6 +101,11 @@ module ActionController #:nodoc:
session[:_csrf_token] ||= ActiveSupport::SecureRandom.base64(32)
end
+ # The form's authenticity parameter. Override to provide your own.
+ def form_authenticity_param
+ params[request_forgery_protection_token]
+ end
+
def protect_against_forgery?
allow_forgery_protection
end
diff --git a/actionpack/lib/action_controller/metal/rescuable.rb b/actionpack/lib/action_controller/metal/rescue.rb
index bbca1b2179..bbca1b2179 100644
--- a/actionpack/lib/action_controller/metal/rescuable.rb
+++ b/actionpack/lib/action_controller/metal/rescue.rb
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index e0932ff932..6178a59029 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -80,6 +80,11 @@ module ActionController #:nodoc:
class Responder
attr_reader :controller, :request, :format, :resource, :resources, :options
+ ACTIONS_FOR_VERBS = {
+ :post => :new,
+ :put => :edit
+ }
+
def initialize(controller, resources, options={})
@controller = controller
@request = controller.request
@@ -102,9 +107,14 @@ module ActionController #:nodoc:
# not defined, call to_format.
#
def self.call(*args)
- responder = new(*args)
- method = :"to_#{responder.format}"
- responder.respond_to?(method) ? responder.send(method) : responder.to_format
+ new(*args).respond
+ end
+
+ # Main entry point for responder responsible to dispatch to the proper format.
+ #
+ def respond
+ method = :"to_#{format}"
+ respond_to?(method) ? send(method) : to_format
end
# HTML format does not render the resource, it always attempt to render a
@@ -133,7 +143,7 @@ module ActionController #:nodoc:
def navigation_behavior(error)
if get?
raise error
- elsif has_errors?
+ elsif has_errors? && default_action
render :action => default_action
else
redirect_to resource_location
@@ -204,7 +214,7 @@ module ActionController #:nodoc:
# the verb is POST.
#
def default_action
- @action || (request.post? ? :new : :edit)
+ @action ||= ACTIONS_FOR_VERBS[request.method]
end
end
end
diff --git a/actionpack/lib/action_controller/metal/session.rb b/actionpack/lib/action_controller/metal/session.rb
deleted file mode 100644
index bcedd6e1c7..0000000000
--- a/actionpack/lib/action_controller/metal/session.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-module ActionController
- module Session
- extend ActiveSupport::Concern
-
- include RackConvenience
-
- def session
- @_request.session
- end
-
- def reset_session
- @_request.reset_session
- end
- end
-end
diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb
index 43c661bef4..288b5d7c99 100644
--- a/actionpack/lib/action_controller/metal/streaming.rb
+++ b/actionpack/lib/action_controller/metal/streaming.rb
@@ -4,7 +4,7 @@ module ActionController #:nodoc:
module Streaming
extend ActiveSupport::Concern
- include ActionController::RenderingController
+ include ActionController::Rendering
DEFAULT_SEND_FILE_OPTIONS = {
:type => 'application/octet-stream'.freeze,
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index a4a1116d9e..c193a5eff4 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -2,7 +2,7 @@ module ActionController
module Testing
extend ActiveSupport::Concern
- include RackConvenience
+ include RackDelegation
# OMG MEGA HAX
def process_with_new_base_test(request, response)
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index 14c6523045..8c3810ebcb 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -2,7 +2,7 @@ module ActionController
module UrlFor
extend ActiveSupport::Concern
- include RackConvenience
+ include RackDelegation
# Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in
# the form of a hash, just like the one you would use for url_for directly. Example:
diff --git a/actionpack/lib/action_controller/metal/verification.rb b/actionpack/lib/action_controller/metal/verification.rb
index 500cced539..bce942b588 100644
--- a/actionpack/lib/action_controller/metal/verification.rb
+++ b/actionpack/lib/action_controller/metal/verification.rb
@@ -2,7 +2,7 @@ module ActionController #:nodoc:
module Verification #:nodoc:
extend ActiveSupport::Concern
- include AbstractController::Callbacks, Session, Flash, RenderingController
+ include AbstractController::Callbacks, Flash, Rendering
# This module provides a class-level method for specifying that certain
# actions are guarded against being called without certain prerequisites
@@ -35,7 +35,7 @@ module ActionController #:nodoc:
# :add_flash => { "alert" => "Failed to create your message" },
# :redirect_to => :category_url
#
- # Note that these prerequisites are not business rules. They do not examine
+ # Note that these prerequisites are not business rules. They do not examine
# the content of the session or the parameters. That level of validation should
# be encapsulated by your domain model or helper methods in the controller.
module ClassMethods
@@ -43,40 +43,40 @@ module ActionController #:nodoc:
# the user is redirected to a different action. The +options+ parameter
# is a hash consisting of the following key/value pairs:
#
- # <tt>:params</tt>::
- # a single key or an array of keys that must be in the <tt>params</tt>
+ # <tt>:params</tt>::
+ # a single key or an array of keys that must be in the <tt>params</tt>
# hash in order for the action(s) to be safely called.
- # <tt>:session</tt>::
- # a single key or an array of keys that must be in the <tt>session</tt>
+ # <tt>:session</tt>::
+ # a single key or an array of keys that must be in the <tt>session</tt>
# in order for the action(s) to be safely called.
- # <tt>:flash</tt>::
- # a single key or an array of keys that must be in the flash in order
+ # <tt>:flash</tt>::
+ # a single key or an array of keys that must be in the flash in order
# for the action(s) to be safely called.
- # <tt>:method</tt>::
- # a single key or an array of keys--any one of which must match the
- # current request method in order for the action(s) to be safely called.
- # (The key should be a symbol: <tt>:get</tt> or <tt>:post</tt>, for
+ # <tt>:method</tt>::
+ # a single key or an array of keys--any one of which must match the
+ # current request method in order for the action(s) to be safely called.
+ # (The key should be a symbol: <tt>:get</tt> or <tt>:post</tt>, for
# example.)
- # <tt>:xhr</tt>::
- # true/false option to ensure that the request is coming from an Ajax
- # call or not.
- # <tt>:add_flash</tt>::
- # a hash of name/value pairs that should be merged into the session's
+ # <tt>:xhr</tt>::
+ # true/false option to ensure that the request is coming from an Ajax
+ # call or not.
+ # <tt>:add_flash</tt>::
+ # a hash of name/value pairs that should be merged into the session's
# flash if the prerequisites cannot be satisfied.
- # <tt>:add_headers</tt>::
- # a hash of name/value pairs that should be merged into the response's
+ # <tt>:add_headers</tt>::
+ # a hash of name/value pairs that should be merged into the response's
# headers hash if the prerequisites cannot be satisfied.
- # <tt>:redirect_to</tt>::
- # the redirection parameters to be used when redirecting if the
- # prerequisites cannot be satisfied. You can redirect either to named
+ # <tt>:redirect_to</tt>::
+ # the redirection parameters to be used when redirecting if the
+ # prerequisites cannot be satisfied. You can redirect either to named
# route or to the action in some controller.
- # <tt>:render</tt>::
+ # <tt>:render</tt>::
# the render parameters to be used when the prerequisites cannot be satisfied.
- # <tt>:only</tt>::
- # only apply this verification to the actions specified in the associated
+ # <tt>:only</tt>::
+ # only apply this verification to the actions specified in the associated
# array (may also be a single value).
- # <tt>:except</tt>::
- # do not apply this verification to the actions specified in the associated
+ # <tt>:except</tt>::
+ # do not apply this verification to the actions specified in the associated
# array (may also be a single value).
def verify(options={})
before_filter :only => options[:only], :except => options[:except] do
@@ -94,31 +94,31 @@ module ActionController #:nodoc:
apply_remaining_actions(options) unless performed?
end
end
-
+
def prereqs_invalid?(options) # :nodoc:
- verify_presence_of_keys_in_hash_flash_or_params(options) ||
- verify_method(options) ||
+ verify_presence_of_keys_in_hash_flash_or_params(options) ||
+ verify_method(options) ||
verify_request_xhr_status(options)
end
-
+
def verify_presence_of_keys_in_hash_flash_or_params(options) # :nodoc:
[*options[:params] ].find { |v| v && params[v.to_sym].nil? } ||
[*options[:session]].find { |v| session[v].nil? } ||
[*options[:flash] ].find { |v| flash[v].nil? }
end
-
+
def verify_method(options) # :nodoc:
[*options[:method]].all? { |v| request.method != v.to_sym } if options[:method]
end
-
+
def verify_request_xhr_status(options) # :nodoc:
request.xhr? != options[:xhr] unless options[:xhr].nil?
end
-
+
def apply_redirect_to(redirect_to_option) # :nodoc:
(redirect_to_option.is_a?(Symbol) && redirect_to_option != :back) ? self.__send__(redirect_to_option) : redirect_to_option
end
-
+
def apply_remaining_actions(options) # :nodoc:
case
when options[:render] ; render(options[:render])
diff --git a/actionpack/lib/action_controller/notifications.rb b/actionpack/lib/action_controller/notifications.rb
deleted file mode 100644
index 1a4f29e0e2..0000000000
--- a/actionpack/lib/action_controller/notifications.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'active_support/notifications'
-
-ActiveSupport::Notifications.subscribe(/(read|write|cache|expire|exist)_(fragment|page)\??/) do |*args|
- event = ActiveSupport::Notifications::Event.new(*args)
-
- if logger = ActionController::Base.logger
- human_name = event.name.to_s.humanize
- logger.info("#{human_name} (%.1fms)" % event.duration)
- end
-end
diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb
new file mode 100644
index 0000000000..f861d12905
--- /dev/null
+++ b/actionpack/lib/action_controller/railtie.rb
@@ -0,0 +1,96 @@
+require "action_controller"
+require "rails"
+
+module ActionController
+ class Railtie < Rails::Railtie
+ plugin_name :action_controller
+
+ initializer "action_controller.set_configs" do |app|
+ app.config.action_controller.each do |k,v|
+ ActionController::Base.send "#{k}=", v
+ end
+ end
+
+ # TODO: ActionController::Base.logger should delegate to its own config.logger
+ initializer "action_controller.logger" do
+ ActionController::Base.logger ||= Rails.logger
+ end
+
+ # Routing must be initialized after plugins to allow the former to extend the routes
+ initializer "action_controller.initialize_routing" do |app|
+ app.route_configuration_files << app.config.routes_configuration_file
+ app.route_configuration_files << app.config.builtin_routes_configuration_file
+ app.reload_routes!
+ end
+
+ # Include middleware to serve up static assets
+ initializer "action_controller.initialize_static_server" do |app|
+ if app.config.serve_static_assets
+ app.config.middleware.use(ActionDispatch::Static, Rails.public_path)
+ end
+ end
+
+ initializer "action_controller.initialize_middleware_stack" do |app|
+ middleware = app.config.middleware
+ 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::Callbacks, lambda { ActionController::Dispatcher.prepare_each_request })
+ middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
+ middleware.use(ActionDispatch::ParamsParser)
+ middleware.use(::Rack::MethodOverride)
+ middleware.use(::Rack::Head)
+ middleware.use(ActionDispatch::StringCoercion)
+ end
+
+ initializer "action_controller.initialize_framework_caches" do
+ ActionController::Base.cache_store ||= RAILS_CACHE
+ end
+
+ # Sets +ActionController::Base#view_paths+ and +ActionMailer::Base#template_root+
+ # (but only for those frameworks that are to be loaded). If the framework's
+ # paths have already been set, it is not changed, otherwise it is
+ # set to use Configuration#view_path.
+ initializer "action_controller.initialize_framework_views" do |app|
+ # TODO: this should be combined with the logic for default config.action_controller.view_paths
+ view_path = ActionView::PathSet.type_cast(app.config.view_path, app.config.cache_classes)
+ ActionController::Base.view_paths = view_path if ActionController::Base.view_paths.blank?
+ end
+
+ initializer "action_controller.initialize_metal" do |app|
+ Rails::Rack::Metal.requested_metals = app.config.metals
+
+ app.config.middleware.insert_before(:"ActionDispatch::ParamsParser",
+ Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?)
+ end
+
+ # # Prepare dispatcher callbacks and run 'prepare' callbacks
+ initializer "action_controller.prepare_dispatcher" do |app|
+ # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
+ require 'rails/dispatcher'
+
+ Dispatcher.define_dispatcher_callbacks(app.config.cache_classes)
+
+ unless app.config.cache_classes
+ # Setup dev mode route reloading
+ routes_last_modified = app.routes_changed_at
+ reload_routes = lambda do
+ unless app.routes_changed_at == routes_last_modified
+ routes_last_modified = app.routes_changed_at
+ app.reload_routes!
+ end
+ end
+ ActionDispatch::Callbacks.before_dispatch { |callbacks| reload_routes.call }
+ end
+ end
+
+ initializer "action_controller.notifications" do |app|
+ require 'active_support/notifications'
+
+ ActiveSupport::Notifications.subscribe do |*args|
+ ActionController::Base.log_event(*args) if ActionController::Base.logger
+ end
+ end
+
+ end
+end
diff --git a/actionpack/lib/action_controller/testing/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 01a55fe930..398ea52495 100644
--- a/actionpack/lib/action_controller/testing/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -1,5 +1,6 @@
require 'active_support/test_case'
require 'rack/session/abstract/id'
+require 'action_controller/metal/testing'
module ActionController
class TestRequest < ActionDispatch::TestRequest #:nodoc:
@@ -180,7 +181,7 @@ module ActionController
#
# assert_redirected_to page_url(:title => 'foo')
class TestCase < ActiveSupport::TestCase
- include TestProcess
+ include ActionDispatch::TestProcess
# Executes a request simulating GET HTTP method and set/volley the response
def get(action, parameters = nil, session = nil, flash = nil)
diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb
deleted file mode 100644
index 323cce6a2f..0000000000
--- a/actionpack/lib/action_controller/testing/process.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-require 'active_support/core_ext/object/conversions'
-require "rack/test"
-
-module ActionController #:nodoc:
- # Essentially generates a modified Tempfile object similar to the object
- # you'd get from the standard library CGI module in a multipart
- # request. This means you can use an ActionController::TestUploadedFile
- # object in the params of a test request in order to simulate
- # a file upload.
- #
- # Usage example, within a functional test:
- # post :change_avatar, :avatar => ActionController::TestUploadedFile.new(ActionController::TestCase.fixture_path + '/files/spongebob.png', 'image/png')
- #
- # Pass a true third parameter to ensure the uploaded file is opened in binary mode (only required for Windows):
- # post :change_avatar, :avatar => ActionController::TestUploadedFile.new(ActionController::TestCase.fixture_path + '/files/spongebob.png', 'image/png', :binary)
- TestUploadedFile = Rack::Test::UploadedFile
-
- module TestProcess
- def assigns(key = nil)
- assigns = {}
- @controller.instance_variable_names.each do |ivar|
- next if ActionController::Base.protected_instance_variables.include?(ivar)
- assigns[ivar[1..-1]] = @controller.instance_variable_get(ivar)
- end
-
- key.nil? ? assigns : assigns[key.to_s]
- end
-
- def session
- @request.session
- end
-
- def flash
- @request.flash
- end
-
- def cookies
- @request.cookies.merge(@response.cookies)
- end
-
- def redirect_to_url
- @response.redirect_url
- end
-
- def html_document
- xml = @response.content_type =~ /xml$/
- @html_document ||= HTML::Document.new(@response.body, false, xml)
- end
-
- def find_tag(conditions)
- html_document.find(conditions)
- end
-
- def find_all_tag(conditions)
- html_document.find_all(conditions)
- end
-
- def method_missing(selector, *args, &block)
- if @controller && ActionController::Routing::Routes.named_routes.helpers.include?(selector)
- @controller.send(selector, *args, &block)
- else
- super
- end
- end
-
- # Shortcut for <tt>ActionController::TestUploadedFile.new(ActionController::TestCase.fixture_path + path, type)</tt>:
- #
- # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
- #
- # To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
- # This will not affect other platforms:
- #
- # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary)
- def fixture_file_upload(path, mime_type = nil, binary = false)
- fixture_path = ActionController::TestCase.send(:fixture_path) if ActionController::TestCase.respond_to?(:fixture_path)
- ActionController::TestUploadedFile.new("#{fixture_path}#{path}", mime_type, binary)
- end
-
- # A helper to make it easier to test different route configurations.
- # This method temporarily replaces ActionController::Routing::Routes
- # with a new RouteSet instance.
- #
- # The new instance is yielded to the passed block. Typically the block
- # will create some routes using <tt>map.draw { map.connect ... }</tt>:
- #
- # with_routing do |set|
- # set.draw do |map|
- # map.connect ':controller/:action/:id'
- # assert_equal(
- # ['/content/10/show', {}],
- # map.generate(:controller => 'content', :id => 10, :action => 'show')
- # end
- # end
- # end
- #
- def with_routing
- real_routes = ActionController::Routing::Routes
- ActionController::Routing.module_eval { remove_const :Routes }
-
- temporary_routes = ActionController::Routing::RouteSet.new
- ActionController::Routing.module_eval { const_set :Routes, temporary_routes }
-
- yield temporary_routes
- ensure
- if ActionController::Routing.const_defined? :Routes
- ActionController::Routing.module_eval { remove_const :Routes }
- end
- ActionController::Routing.const_set(:Routes, real_routes) if real_routes
- end
- end
-end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner.rb b/actionpack/lib/action_controller/vendor/html-scanner.rb
index f622d195ee..879b31e60e 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner.rb
@@ -1,16 +1,20 @@
$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner"
module HTML
- autoload :CDATA, 'html/node'
- autoload :Document, 'html/document'
- autoload :FullSanitizer, 'html/sanitizer'
- autoload :LinkSanitizer, 'html/sanitizer'
- autoload :Node, 'html/node'
- autoload :Sanitizer, 'html/sanitizer'
- autoload :Selector, 'html/selector'
- autoload :Tag, 'html/node'
- autoload :Text, 'html/node'
- autoload :Tokenizer, 'html/tokenizer'
- autoload :Version, 'html/version'
- autoload :WhiteListSanitizer, 'html/sanitizer'
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :CDATA, 'html/node'
+ autoload :Document, 'html/document'
+ autoload :FullSanitizer, 'html/sanitizer'
+ autoload :LinkSanitizer, 'html/sanitizer'
+ autoload :Node, 'html/node'
+ autoload :Sanitizer, 'html/sanitizer'
+ autoload :Selector, 'html/selector'
+ autoload :Tag, 'html/node'
+ autoload :Text, 'html/node'
+ autoload :Tokenizer, 'html/tokenizer'
+ autoload :Version, 'html/version'
+ autoload :WhiteListSanitizer, 'html/sanitizer'
+ end
end
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 259814a322..1e87a016f9 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -21,6 +21,11 @@
# 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'
+require 'active_support/dependencies/autoload'
+
require 'rack'
module Rack
@@ -28,29 +33,25 @@ module Rack
end
module ActionDispatch
- autoload :Request, 'action_dispatch/http/request'
- autoload :Response, 'action_dispatch/http/response'
- autoload :StatusCodes, 'action_dispatch/http/status_codes'
- autoload :Utils, 'action_dispatch/http/utils'
-
- autoload :Callbacks, 'action_dispatch/middleware/callbacks'
- autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
- autoload :ParamsParser, 'action_dispatch/middleware/params_parser'
- autoload :Rescue, 'action_dispatch/middleware/rescue'
- autoload :ShowExceptions, 'action_dispatch/middleware/show_exceptions'
- autoload :Static, 'action_dispatch/middleware/static'
- autoload :StringCoercion, 'action_dispatch/middleware/string_coercion'
+ extend ActiveSupport::Autoload
- autoload :Routing, 'action_dispatch/routing'
+ autoload_under 'http' do
+ autoload :Request
+ autoload :Response
+ end
- autoload :Assertions, 'action_dispatch/testing/assertions'
- autoload :Integration, 'action_dispatch/testing/integration'
- autoload :IntegrationTest, 'action_dispatch/testing/integration'
- autoload :PerformanceTest, 'action_dispatch/testing/performance_test'
- autoload :TestRequest, 'action_dispatch/testing/test_request'
- autoload :TestResponse, 'action_dispatch/testing/test_response'
+ autoload_under 'middleware' do
+ autoload :Callbacks
+ autoload :Cascade
+ autoload :ParamsParser
+ autoload :Rescue
+ autoload :ShowExceptions
+ autoload :Static
+ autoload :StringCoercion
+ end
- autoload :HTML, 'action_controller/vendor/html-scanner'
+ autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
+ autoload :Routing
module Http
autoload :Headers, 'action_dispatch/http/headers'
@@ -58,13 +59,18 @@ module ActionDispatch
module Session
autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
- autoload :CookieStore, 'action_dispatch/middleware/session/cookie_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'
-
-activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
-$:.unshift activesupport_path if File.directory?(activesupport_path)
-require 'active_support'
diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb
index 2a41b4dbad..1e43104f0a 100644
--- a/actionpack/lib/action_dispatch/http/headers.rb
+++ b/actionpack/lib/action_dispatch/http/headers.rb
@@ -6,13 +6,13 @@ module ActionDispatch
extend ActiveSupport::Memoizable
def initialize(*args)
- if args.size == 1 && args[0].is_a?(Hash)
- super()
- update(args[0])
- else
- super
- end
- end
+ if args.size == 1 && args[0].is_a?(Hash)
+ super()
+ update(args[0])
+ else
+ super
+ end
+ end
def [](header_name)
if include?(header_name)
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index c30897b32a..13c0f2bad0 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -10,8 +10,8 @@ module Mime
%w(<< concat shift unshift push pop []= clear compact! collect!
delete delete_at delete_if flatten! map! insert reject! reverse!
replace slice! sort! uniq!).each do |method|
- module_eval <<-CODE
- def #{method}(*args)
+ module_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{method}(*)
@symbols = nil
super
end
@@ -104,7 +104,7 @@ module Mime
SET << Mime.const_get(symbol.to_s.upcase)
- ([string] + mime_type_synonyms).each { |string| LOOKUP[string] = SET.last } unless skip_lookup
+ ([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
([symbol.to_s] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext] = SET.last }
end
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 6a52854961..6e8a5dcb8a 100755
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -6,6 +6,7 @@ require 'active_support/memoizable'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/string/access'
+require 'action_dispatch/http/headers'
module ActionDispatch
class Request < Rack::Request
@@ -17,7 +18,7 @@ module ActionDispatch
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
- HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env|
+ HTTP_NEGOTIATE HTTP_PRAGMA ].each do |env|
define_method(env.sub(/^HTTP_/n, '').downcase) do
@env[env]
end
@@ -117,7 +118,7 @@ module ActionDispatch
end
end
end
-
+
def if_modified_since
if since = env['HTTP_IF_MODIFIED_SINCE']
Time.rfc2822(since) rescue nil
@@ -464,6 +465,15 @@ EOM
session['flash'] || {}
end
+ # Returns the authorization header regardless of whether it was specified directly or through one of the
+ # proxy alternatives.
+ def authorization
+ @env['HTTP_AUTHORIZATION'] ||
+ @env['X-HTTP_AUTHORIZATION'] ||
+ @env['X_HTTP_AUTHORIZATION'] ||
+ @env['REDIRECT_X_HTTP_AUTHORIZATION']
+ end
+
# Receives an array of mimes and return the first user sent mime that
# matches the order array.
#
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index b3ed7c9d1a..8524bbd993 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -33,7 +33,6 @@ module ActionDispatch # :nodoc:
# end
class Response < Rack::Response
attr_accessor :request, :blank
- attr_reader :cache_control
attr_writer :header, :sending_file
alias_method :headers=, :header=
@@ -50,6 +49,9 @@ module ActionDispatch # :nodoc:
@body, @cookie = [], []
@sending_file = false
+ @blank = false
+ @etag = nil
+
yield self if block_given?
end
@@ -57,14 +59,8 @@ module ActionDispatch # :nodoc:
@cache_control ||= {}
end
- def write(str)
- s = str.to_s
- @writer.call s
- str
- end
-
def status=(status)
- @status = status.to_i
+ @status = Rack::Utils.status_code(status)
end
# The response code of the request
@@ -78,7 +74,7 @@ module ActionDispatch # :nodoc:
end
def message
- StatusCodes::STATUS_CODES[@status]
+ Rack::Utils::HTTP_STATUS_CODES[@status]
end
alias_method :status_message, :message
@@ -149,18 +145,6 @@ module ActionDispatch # :nodoc:
cattr_accessor(:default_charset) { "utf-8" }
- def assign_default_content_type_and_charset!
- return if headers[CONTENT_TYPE].present?
-
- @content_type ||= Mime::HTML
- @charset ||= self.class.default_charset
-
- type = @content_type.to_s.dup
- type << "; charset=#{@charset}" unless @sending_file
-
- headers[CONTENT_TYPE] = type
- end
-
def to_a
assign_default_content_type_and_charset!
handle_conditional_get!
@@ -263,6 +247,18 @@ module ActionDispatch # :nodoc:
!@blank && @body.respond_to?(:all?) && @body.all? { |part| part.is_a?(String) }
end
+ def assign_default_content_type_and_charset!
+ return if headers[CONTENT_TYPE].present?
+
+ @content_type ||= Mime::HTML
+ @charset ||= self.class.default_charset
+
+ type = @content_type.to_s.dup
+ type << "; charset=#{@charset}" unless @sending_file
+
+ headers[CONTENT_TYPE] = type
+ end
+
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate"
def set_conditional_cache_control!
@@ -277,14 +273,13 @@ module ActionDispatch # :nodoc:
max_age = control[:max_age]
options = []
- options << "max-age=#{max_age}" if max_age
+ options << "max-age=#{max_age.to_i}" if max_age
options << (control[:public] ? "public" : "private")
options << "must-revalidate" if control[:must_revalidate]
options.concat(extras) if extras
headers["Cache-Control"] = options.join(", ")
end
-
end
end
end
diff --git a/actionpack/lib/action_dispatch/http/status_codes.rb b/actionpack/lib/action_dispatch/http/status_codes.rb
deleted file mode 100644
index 5bac842ec1..0000000000
--- a/actionpack/lib/action_dispatch/http/status_codes.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-require 'active_support/inflector'
-
-module ActionDispatch
- module StatusCodes #:nodoc:
- STATUS_CODES = Rack::Utils::HTTP_STATUS_CODES.merge({
- 102 => "Processing",
- 207 => "Multi-Status",
- 226 => "IM Used",
- 422 => "Unprocessable Entity",
- 423 => "Locked",
- 424 => "Failed Dependency",
- 426 => "Upgrade Required",
- 507 => "Insufficient Storage",
- 510 => "Not Extended"
- }).freeze
-
- # Provides a symbol-to-fixnum lookup for converting a symbol (like
- # :created or :not_implemented) into its corresponding HTTP status
- # code (like 200 or 501).
- SYMBOL_TO_STATUS_CODE = STATUS_CODES.inject({}) { |hash, (code, message)|
- hash[ActiveSupport::Inflector.underscore(message.gsub(/ /, "")).to_sym] = code
- hash
- }.freeze
-
- private
- # Given a status parameter, determine whether it needs to be converted
- # to a string. If it is a fixnum, use the STATUS_CODES hash to lookup
- # the default message. If it is a symbol, use the SYMBOL_TO_STATUS_CODE
- # hash to convert it.
- def interpret_status(status)
- case status
- when Fixnum then
- "#{status} #{STATUS_CODES[status]}".strip
- when Symbol then
- interpret_status(SYMBOL_TO_STATUS_CODE[status] ||
- "500 Unknown Status #{status.inspect}")
- else
- status.to_s
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/http/utils.rb b/actionpack/lib/action_dispatch/http/utils.rb
deleted file mode 100644
index e04a39935e..0000000000
--- a/actionpack/lib/action_dispatch/http/utils.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-module ActionDispatch
- module Utils
- # TODO: Pull this into rack core
- # http://github.com/halorgium/rack/commit/feaf071c1de743fbd10bc316830180a9af607278
- def parse_config(config)
- if config =~ /\.ru$/
- cfgfile = ::File.read(config)
- if cfgfile[/^#\\(.*)/]
- opts.parse! $1.split(/\s+/)
- end
- inner_app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
- nil, config
- else
- require config
- inner_app = Object.const_get(::File.basename(config, '.rb').capitalize)
- end
- end
- module_function :parse_config
- end
-end
diff --git a/actionpack/lib/action_dispatch/middleware/cascade.rb b/actionpack/lib/action_dispatch/middleware/cascade.rb
new file mode 100644
index 0000000000..9f5c9891f0
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/cascade.rb
@@ -0,0 +1,29 @@
+module ActionDispatch
+ class Cascade
+ def self.new(*apps)
+ apps = apps.flatten
+
+ case apps.length
+ when 0
+ raise ArgumentError, "app is required"
+ when 1
+ apps.first
+ else
+ super(apps)
+ end
+ end
+
+ def initialize(apps)
+ @apps = apps
+ end
+
+ def call(env)
+ result = nil
+ @apps.each do |app|
+ result = app.call(env)
+ break unless result[1]["X-Cascade"] == "pass"
+ end
+ result
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index 32ccb5c931..534390d4aa 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -1,4 +1,5 @@
require 'active_support/json'
+require 'action_dispatch/http/request'
module ActionDispatch
class ParamsParser
@@ -31,41 +32,39 @@ module ActionDispatch
return false unless strategy
case strategy
- when Proc
- strategy.call(request.raw_post)
- when :xml_simple, :xml_node
- request.body.size == 0 ? {} : Hash.from_xml(request.body).with_indifferent_access
- when :yaml
- YAML.load(request.body)
- when :json
- if request.body.size == 0
- {}
- else
- data = ActiveSupport::JSON.decode(request.body)
- data = {:_json => data} unless data.is_a?(Hash)
- data.with_indifferent_access
- end
+ when Proc
+ strategy.call(request.raw_post)
+ when :xml_simple, :xml_node
+ request.body.size == 0 ? {} : Hash.from_xml(request.body).with_indifferent_access
+ when :yaml
+ YAML.load(request.body)
+ when :json
+ if request.body.size == 0
+ {}
else
- false
+ data = ActiveSupport::JSON.decode(request.body)
+ data = {:_json => data} unless data.is_a?(Hash)
+ data.with_indifferent_access
+ end
+ else
+ false
end
rescue Exception => e # YAML, XML or Ruby code block errors
logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
raise
- { "body" => request.raw_post,
- "content_type" => request.content_type,
+ { "body" => request.raw_post,
+ "content_type" => request.content_type,
"content_length" => request.content_length,
- "exception" => "#{e.message} (#{e.class})",
- "backtrace" => e.backtrace }
+ "exception" => "#{e.message} (#{e.class})",
+ "backtrace" => e.backtrace }
end
def content_type_from_legacy_post_data_format_header(env)
if x_post_format = env['HTTP_X_POST_DATA_FORMAT']
case x_post_format.to_s.downcase
- when 'yaml'
- return Mime::YAML
- when 'xml'
- return Mime::XML
+ when 'yaml' then return Mime::YAML
+ when 'xml' then return Mime::XML
end
end
@@ -76,4 +75,4 @@ module ActionDispatch
defined?(Rails.logger) ? Rails.logger : Logger.new($stderr)
end
end
-end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index c5c06f74a2..7d4f0998ce 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -1,4 +1,5 @@
require 'rack/utils'
+require 'rack/request'
module ActionDispatch
module Session
diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
index bd552b458a..04a101dbb2 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -1,4 +1,5 @@
-require "active_support/core_ext/hash/keys"
+require 'active_support/core_ext/hash/keys'
+require 'rack/request'
module ActionDispatch
module Session
@@ -49,7 +50,7 @@ module ActionDispatch
:expire_after => nil,
:httponly => true
}.freeze
-
+
class OptionsHash < Hash
def initialize(by, env, default_options)
@session_data = env[CookieStore::ENV_SESSION_KEY]
@@ -60,7 +61,7 @@ module ActionDispatch
key == :id ? @session_data[:session_id] : super(key)
end
end
-
+
ENV_SESSION_KEY = "rack.session".freeze
ENV_SESSION_OPTIONS_KEY = "rack.session.options".freeze
HTTP_SET_COOKIE = "Set-Cookie".freeze
@@ -102,7 +103,7 @@ module ActionDispatch
def call(env)
env[ENV_SESSION_KEY] = AbstractStore::SessionHash.new(self, env)
env[ENV_SESSION_OPTIONS_KEY] = OptionsHash.new(self, env, @default_options)
-
+
status, headers, body = @app.call(env)
session_data = env[ENV_SESSION_KEY]
@@ -178,7 +179,7 @@ module ActionDispatch
'cookie containing the session data. Use ' +
'config.action_controller.session = { :key => ' +
'"_myapp_session", :secret => "some secret phrase" } in ' +
- 'config/environment.rb'
+ 'config/application.rb'
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index 036deec6d2..4ebc8a2ab9 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -1,9 +1,8 @@
-require "active_support/core_ext/exception"
+require 'active_support/core_ext/exception'
+require 'action_dispatch/http/request'
module ActionDispatch
class ShowExceptions
- include StatusCodes
-
LOCALHOST = '127.0.0.1'.freeze
RESCUES_TEMPLATE_PATH = File.join(File.dirname(__FILE__), 'templates')
@@ -12,8 +11,7 @@ module ActionDispatch
@@rescue_responses = Hash.new(:internal_server_error)
@@rescue_responses.update({
'ActionController::RoutingError' => :not_found,
- # TODO: Clean this up after the switch
- ActionController::UnknownAction.name => :not_found,
+ 'AbstractController::ActionNotFound' => :not_found,
'ActiveRecord::RecordNotFound' => :not_found,
'ActiveRecord::StaleObjectError' => :conflict,
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
@@ -28,8 +26,8 @@ module ActionDispatch
@@rescue_templates.update({
'ActionView::MissingTemplate' => 'missing_template',
'ActionController::RoutingError' => 'routing_error',
- ActionController::UnknownAction.name => 'unknown_action',
- 'ActionView::TemplateError' => 'template_error'
+ 'AbstractController::ActionNotFound' => 'unknown_action',
+ 'ActionView::Template::Error' => 'template_error'
})
FAILSAFE_RESPONSE = [500, {'Content-Type' => 'text/html'},
@@ -104,7 +102,7 @@ module ActionDispatch
end
def status_code(exception)
- interpret_status(@@rescue_responses[exception.class.name]).to_i
+ Rack::Utils.status_code(@@rescue_responses[exception.class.name])
end
def render(status, body)
@@ -119,7 +117,7 @@ module ActionDispatch
return unless logger
ActiveSupport::Deprecation.silence do
- if ActionView::TemplateError === exception
+ if ActionView::Template::Error === exception
logger.fatal(exception.to_s)
else
logger.fatal(
diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb
index 3b27309f58..24be4fee55 100644
--- a/actionpack/lib/action_dispatch/middleware/stack.rb
+++ b/actionpack/lib/action_dispatch/middleware/stack.rb
@@ -93,8 +93,9 @@ module ActionDispatch
alias_method :insert_before, :insert
def insert_after(index, *args, &block)
- index = self.index(index) unless index.is_a?(Integer)
- insert(index + 1, *args, &block)
+ i = index.is_a?(Integer) ? index : self.index(index)
+ raise "No such middleware to insert after: #{index.inspect}" unless i
+ insert(i + 1, *args, &block)
end
def swap(target, *args, &block)
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
index f8f6b424ca..07b4919934 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
@@ -7,7 +7,7 @@
names = traces.collect {|name, trace| name}
%>
-<p><code>RAILS_ROOT: <%= defined?(RAILS_ROOT) ? RAILS_ROOT : "unset" %></code></p>
+<p><code>Rails.root: <%= defined?(Rails) && Rails.respond_to?(:root) ? Rails.root : "unset" %></code></p>
<div id="traces">
<% names.each do |name| %>
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
index 5063ab8072..b598d6f7e2 100644
--- a/actionpack/lib/action_dispatch/routing.rb
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -265,118 +265,11 @@ module ActionDispatch
autoload :RouteSet, 'action_dispatch/routing/route_set'
SEPARATORS = %w( / . ? )
-
HTTP_METHODS = [:get, :head, :post, :put, :delete, :options]
- ALLOWED_REQUIREMENTS_FOR_OPTIMISATION = [:controller, :action].to_set
-
- # The root paths which may contain controller files
- mattr_accessor :controller_paths
- self.controller_paths = []
-
# A helper module to hold URL related helpers.
module Helpers
include ActionController::PolymorphicRoutes
end
-
- class << self
- # Expects an array of controller names as the first argument.
- # Executes the passed block with only the named controllers named available.
- # This method is used in internal Rails testing.
- def with_controllers(names)
- prior_controllers = @possible_controllers
- use_controllers! names
- yield
- ensure
- use_controllers! prior_controllers
- end
-
- # Returns an array of paths, cleaned of double-slashes and relative path references.
- # * "\\\" and "//" become "\\" or "/".
- # * "/foo/bar/../config" becomes "/foo/config".
- # The returned array is sorted by length, descending.
- def normalize_paths(paths)
- # do the hokey-pokey of path normalization...
- paths = paths.collect do |path|
- path = path.
- gsub("//", "/"). # replace double / chars with a single
- gsub("\\\\", "\\"). # replace double \ chars with a single
- gsub(%r{(.)[\\/]$}, '\1') # drop final / or \ if path ends with it
-
- # eliminate .. paths where possible
- re = %r{[^/\\]+[/\\]\.\.[/\\]}
- path.gsub!(re, "") while path.match(re)
- path
- end
-
- # start with longest path, first
- paths = paths.uniq.sort_by { |path| - path.length }
- end
-
- # Returns the array of controller names currently available to ActionController::Routing.
- def possible_controllers
- unless @possible_controllers
- @possible_controllers = []
-
- paths = controller_paths.select { |path| File.directory?(path) && path != "." }
-
- seen_paths = Hash.new {|h, k| h[k] = true; false}
- normalize_paths(paths).each do |load_path|
- Dir["#{load_path}/**/*_controller.rb"].collect do |path|
- next if seen_paths[path.gsub(%r{^\.[/\\]}, "")]
-
- controller_name = path[(load_path.length + 1)..-1]
-
- controller_name.gsub!(/_controller\.rb\Z/, '')
- @possible_controllers << controller_name
- end
- end
-
- # remove duplicates
- @possible_controllers.uniq!
- end
- @possible_controllers
- end
-
- # Replaces the internal list of controllers available to ActionController::Routing with the passed argument.
- # ActionController::Routing.use_controllers!([ "posts", "comments", "admin/comments" ])
- def use_controllers!(controller_names)
- @possible_controllers = controller_names
- end
-
- # Returns a controller path for a new +controller+ based on a +previous+ controller path.
- # Handles 4 scenarios:
- #
- # * stay in the previous controller:
- # controller_relative_to( nil, "groups/discussion" ) # => "groups/discussion"
- #
- # * stay in the previous namespace:
- # controller_relative_to( "posts", "groups/discussion" ) # => "groups/posts"
- #
- # * forced move to the root namespace:
- # controller_relative_to( "/posts", "groups/discussion" ) # => "posts"
- #
- # * previous namespace is root:
- # controller_relative_to( "posts", "anything_with_no_slashes" ) # =>"posts"
- #
- def controller_relative_to(controller, previous)
- if controller.nil? then previous
- elsif controller[0] == ?/ then controller[1..-1]
- elsif %r{^(.*)/} =~ previous then "#{$1}/#{controller}"
- else controller
- end
- end
- end
-
- ActiveSupport::Inflector.module_eval do
- # Ensures that routes are reloaded when Rails inflections are updated.
- def inflections_with_route_reloading(&block)
- returning(inflections_without_route_reloading(&block)) {
- ActionDispatch::Routing::Routes.reload! if block_given?
- }
- end
-
- alias_method_chain :inflections, :route_reloading
- end
end
end
diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
index 0564ba9797..8ce6b2f6d5 100644
--- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb
@@ -113,8 +113,7 @@ module ActionDispatch
end
end
- possible_names = Routing.possible_controllers.collect { |n| Regexp.escape(n) }
- requirements[:controller] ||= Regexp.union(*possible_names)
+ requirements[:controller] ||= @set.controller_constraints
if defaults[:controller]
defaults[:action] ||= 'index'
@@ -176,7 +175,7 @@ module ActionDispatch
optional = false
elsif segment =~ /^:(\w+)$/
if defaults.has_key?($1.to_sym)
- defaults.delete($1.to_sym)
+ defaults.delete($1.to_sym) if defaults[$1.to_sym].nil?
else
optional = false
end
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 7d770dedd0..8f33346a4f 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,143 +1,261 @@
module ActionDispatch
module Routing
class Mapper
- module Resources
- def resource(*resources, &block)
- options = resources.last.is_a?(Hash) ? resources.pop : {}
-
- if resources.length > 1
- raise ArgumentError if block_given?
- resources.each { |r| resource(r, options) }
- return self
+ class Constraints
+ def self.new(app, constraints = [])
+ if constraints.any?
+ super(app, constraints)
+ else
+ app
end
+ end
- resource = resources.pop
+ def initialize(app, constraints = [])
+ @app, @constraints = app, constraints
+ end
- if @scope[:scope_level] == :resources
- member do
- resource(resource, options, &block)
+ def call(env)
+ req = Rack::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'}, [] ]
end
- return self
- end
+ }
- singular = resource.to_s
- plural = singular.pluralize
+ @app.call(env)
+ end
+ end
- controller(plural) do
- namespace(resource) do
- with_scope_level(:resource) do
- yield if block_given?
+ class Mapping
+ def initialize(set, scope, args)
+ @set, @scope = set, scope
+ @path, @options = extract_path_and_options(args)
+ end
- get "", :to => :show, :as => "#{singular}"
- post "", :to => :create
- put "", :to => :update
- delete "", :to => :destroy
- get "new", :to => :new, :as => "new_#{singular}"
- get "edit", :to => :edit, :as => "edit_#{singular}"
- end
+ def to_route
+ [ app, conditions, requirements, defaults, @options[:as] ]
+ end
+
+ private
+ def extract_path_and_options(args)
+ options = args.extract_options!
+
+ case
+ when using_to_shorthand?(args, options)
+ path, to = options.find { |name, value| name.is_a?(String) }
+ options.merge!(:to => to).delete(path) if path
+ when using_match_shorthand?(args, options)
+ path = args.first
+ options = { :to => path.gsub("/", "#"), :as => path.gsub("/", "_") }
+ else
+ path = args.first
end
+
+ [ normalize_path(path), options ]
end
- self
- end
+ # match "account" => "account#index"
+ def using_to_shorthand?(args, options)
+ args.empty? && options.present?
+ end
- def resources(*resources, &block)
- options = resources.last.is_a?(Hash) ? resources.pop : {}
+ # match "account/overview"
+ def using_match_shorthand?(args, options)
+ args.present? && options.except(:via).empty? && !args.first.include?(':')
+ end
- if resources.length > 1
- raise ArgumentError if block_given?
- resources.each { |r| resources(r, options) }
- return self
+ def normalize_path(path)
+ path = nil if path == ""
+ path = "#{@scope[:path]}#{path}" if @scope[:path]
+ path = Rack::Mount::Utils.normalize_path(path) if path
+
+ raise ArgumentError, "path is required" unless path
+
+ path
end
- resource = resources.pop
- if @scope[:scope_level] == :resources
- member do
- resources(resource, options, &block)
- end
- return self
+ def app
+ Constraints.new(
+ to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
+ blocks
+ )
end
- plural = resource.to_s
- singular = plural.singularize
+ def conditions
+ { :path_info => @path }.merge(constraints).merge(request_method_condition)
+ end
- controller(resource) do
- namespace(resource) do
- with_scope_level(:resources) do
- yield if block_given?
+ def requirements
+ @requirements ||= returning(@options[:constraints] || {}) do |requirements|
+ requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
+ @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
+ requirements[:controller] ||= @set.controller_constraints
+ end
+ end
- member do
- get "", :to => :show, :as => "#{singular}"
- put "", :to => :update
- delete "", :to => :destroy
- get "edit", :to => :edit, :as => "edit_#{singular}"
- end
+ def defaults
+ @defaults ||= if to.respond_to?(:call)
+ { }
+ else
+ defaults = case to
+ when String
+ controller, action = to.split('#')
+ { :controller => controller, :action => action }
+ when Symbol
+ { :action => to.to_s }.merge(default_controller ? { :controller => default_controller } : {})
+ else
+ default_controller ? { :controller => default_controller } : {}
+ end
- collection do
- get "", :to => :index, :as => "#{plural}"
- post "", :to => :create
- get "new", :to => :new, :as => "new_#{singular}"
- end
+ if defaults[:controller].blank? && segment_keys.exclude?("controller")
+ raise ArgumentError, "missing :controller"
end
+
+ if defaults[:action].blank? && segment_keys.exclude?("action")
+ raise ArgumentError, "missing :action"
+ end
+
+ defaults
end
end
- self
- end
- def collection
- unless @scope[:scope_level] == :resources
- raise ArgumentError, "can't use collection outside resources scope"
- end
+ def blocks
+ if @options[:constraints].present? && !@options[:constraints].is_a?(Hash)
+ block = @options[:constraints]
+ else
+ block = nil
+ end
- with_scope_level(:collection) do
- yield
+ ((@scope[:blocks] || []) + [ block ]).compact
end
- end
- def member
- unless @scope[:scope_level] == :resources
- raise ArgumentError, "can't use member outside resources scope"
+ def constraints
+ @constraints ||= requirements.reject { |k, v| segment_keys.include?(k.to_s) || k == :controller }
end
- with_scope_level(:member) do
- scope(":id") do
- yield
+ def request_method_condition
+ if via = @options[:via]
+ via = Array(via).map { |m| m.to_s.upcase }
+ { :request_method => Regexp.union(*via) }
+ else
+ { }
end
end
+
+ def segment_keys
+ @segment_keys ||= Rack::Mount::RegexpWithNamedGroups.new(
+ Rack::Mount::Strexp.compile(@path, requirements, SEPARATORS)
+ ).names
+ end
+
+ def to
+ @options[:to]
+ end
+
+ def default_controller
+ @scope[:controller].to_s if @scope[:controller]
+ end
+ end
+
+ module Base
+ def initialize(set)
+ @set = set
+ end
+
+ def root(options = {})
+ match '/', options.reverse_merge(:as => :root)
end
def match(*args)
+ @set.add_route(*Mapping.new(@set, @scope, args).to_route)
+ self
+ end
+ end
+
+ module HttpHelpers
+ def get(*args, &block)
+ map_method(:get, *args, &block)
+ end
+
+ def post(*args, &block)
+ map_method(:post, *args, &block)
+ end
+
+ def put(*args, &block)
+ map_method(:put, *args, &block)
+ end
+
+ def delete(*args, &block)
+ map_method(:delete, *args, &block)
+ end
+
+ def redirect(*args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
- args.push(options)
- case options.delete(:on)
- when :collection
- return collection { match(*args) }
- when :member
- return member { match(*args) }
- end
+ path = args.shift || block
+ path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
+ status = options[:status] || 301
- if @scope[:scope_level] == :resources
- raise ArgumentError, "can't define route directly in resources scope"
- end
+ lambda do |env|
+ req = Rack::Request.new(env)
+ params = path_proc.call(env["action_dispatch.request.path_parameters"])
+ url = req.scheme + '://' + req.host + params
- super
+ [ status, {'Location' => url, 'Content-Type' => 'text/html'}, ['Moved Permanently'] ]
+ end
end
private
- def with_scope_level(kind)
- old, @scope[:scope_level] = @scope[:scope_level], kind
- yield
- ensure
- @scope[:scope_level] = old
+ def map_method(method, *args, &block)
+ options = args.extract_options!
+ options[:via] = method
+ args.push(options)
+ match(*args, &block)
+ self
end
end
module Scoping
+ def initialize(*args)
+ @scope = {}
+ super
+ end
+
def scope(*args)
- options = args.last.is_a?(Hash) ? args.pop : {}
+ options = args.extract_options!
+
+ case args.first
+ when String
+ options[:path] = args.first
+ when Symbol
+ options[:controller] = args.first
+ end
+
+ if path = options.delete(:path)
+ path_set = true
+ path, @scope[:path] = @scope[:path], Rack::Mount::Utils.normalize_path(@scope[:path].to_s + path.to_s)
+ else
+ path_set = false
+ end
+
+ if name_prefix = options.delete(:name_prefix)
+ name_prefix_set = true
+ name_prefix, @scope[:name_prefix] = @scope[:name_prefix], (@scope[:name_prefix] ? "#{@scope[:name_prefix]}_#{name_prefix}" : name_prefix)
+ else
+ name_prefix_set = false
+ end
+
+ if controller = options.delete(:controller)
+ controller_set = true
+ controller, @scope[:controller] = @scope[:controller], controller
+ else
+ controller_set = false
+ end
constraints = options.delete(:constraints) || {}
unless constraints.is_a?(Hash)
@@ -148,27 +266,15 @@ module ActionDispatch
options, @scope[:options] = @scope[:options], (@scope[:options] || {}).merge(options)
- path_set = controller_set = false
-
- case args.first
- when String
- path_set = true
- path = args.first
- path, @scope[:path] = @scope[:path], "#{@scope[:path]}#{Rack::Mount::Utils.normalize_path(path)}"
- when Symbol
- controller_set = true
- controller = args.first
- controller, @scope[:controller] = @scope[:controller], controller
- end
-
yield
self
ensure
- @scope[:path] = path if path_set
- @scope[:controller] = controller if controller_set
- @scope[:options] = options
- @scope[:blocks] = blocks
+ @scope[:path] = path if path_set
+ @scope[:name_prefix] = name_prefix if name_prefix_set
+ @scope[:controller] = controller if controller_set
+ @scope[:options] = options
+ @scope[:blocks] = blocks
@scope[:constraints] = constraints
end
@@ -177,151 +283,255 @@ module ActionDispatch
end
def namespace(path)
- scope(path.to_s) { yield }
+ scope("/#{path}") { yield }
end
def constraints(constraints = {})
scope(:constraints => constraints) { yield }
end
- end
- class Constraints
- def initialize(app, constraints = [])
- @app, @constraints = app, constraints
- end
+ def match(*args)
+ options = args.extract_options!
- def call(env)
- req = Rack::Request.new(env)
+ options = (@scope[:options] || {}).merge(options)
- @constraints.each { |constraint|
- if constraint.respond_to?(:matches?) && !constraint.matches?(req)
- return [417, {}, []]
- elsif constraint.respond_to?(:call) && !constraint.call(req)
- return [417, {}, []]
- end
- }
+ if @scope[:name_prefix] && !options[:as].blank?
+ options[:as] = "#{@scope[:name_prefix]}_#{options[:as]}"
+ elsif @scope[:name_prefix] && options[:as] == ""
+ options[:as] = @scope[:name_prefix].to_s
+ end
- @app.call(env)
+ args.push(options)
+ super(*args)
end
end
- def initialize(set)
- @set = set
- @scope = {}
-
- extend Scoping
- extend Resources
- end
+ module Resources
+ class Resource #:nodoc:
+ attr_reader :plural, :singular
- def get(*args, &block)
- map_method(:get, *args, &block)
- end
+ def initialize(entities, options = {})
+ entities = entities.to_s
- def post(*args, &block)
- map_method(:post, *args, &block)
- end
+ @plural = entities.pluralize
+ @singular = entities.singularize
+ end
- def put(*args, &block)
- map_method(:put, *args, &block)
- end
+ def name
+ plural
+ end
- def delete(*args, &block)
- map_method(:delete, *args, &block)
- end
+ def controller
+ plural
+ end
- def root(options = {})
- match '/', options.merge(:as => :root)
- end
+ def member_name
+ singular
+ end
- def match(*args)
- options = args.last.is_a?(Hash) ? args.pop : {}
+ def collection_name
+ plural
+ end
- if args.length > 1
- args.each { |path| match(path, options) }
- return self
+ def id_segment
+ ":#{singular}_id"
+ end
end
- if args.first.is_a?(Symbol)
- return match(args.first.to_s, options.merge(:to => args.first.to_sym))
+ class SingletonResource < Resource #:nodoc:
+ def initialize(entity, options = {})
+ super
+ end
+
+ def name
+ singular
+ end
end
- path = args.first
+ def resource(*resources, &block)
+ options = resources.extract_options!
- options = (@scope[:options] || {}).merge(options)
- conditions, defaults = {}, {}
+ if resources.length > 1
+ raise ArgumentError if block_given?
+ resources.each { |r| resource(r, options) }
+ return self
+ end
+
+ resource = SingletonResource.new(resources.pop)
- path = nil if path == ""
- path = Rack::Mount::Utils.normalize_path(path) if path
- path = "#{@scope[:path]}#{path}" if @scope[:path]
+ if @scope[:scope_level] == :resources
+ nested do
+ resource(resource.name, options, &block)
+ end
+ return self
+ end
- raise ArgumentError, "path is required" unless path
+ scope(:path => "/#{resource.name}", :controller => resource.controller) do
+ with_scope_level(:resource, resource) do
+ yield if block_given?
- constraints = options[:constraints] || {}
- unless constraints.is_a?(Hash)
- block, constraints = constraints, {}
+ get "(.:format)", :to => :show, :as => resource.member_name
+ post "(.:format)", :to => :create
+ put "(.:format)", :to => :update
+ delete "(.:format)", :to => :destroy
+ get "/new(.:format)", :to => :new, :as => "new_#{resource.singular}"
+ get "/edit(.:format)", :to => :edit, :as => "edit_#{resource.singular}"
+ end
+ end
+
+ self
end
- blocks = ((@scope[:blocks] || []) + [block]).compact
- constraints = (@scope[:constraints] || {}).merge(constraints)
- options.each { |k, v| constraints[k] = v if v.is_a?(Regexp) }
- conditions[:path_info] = path
- requirements = constraints.dup
+ def resources(*resources, &block)
+ options = resources.extract_options!
+
+ if resources.length > 1
+ raise ArgumentError if block_given?
+ resources.each { |r| resources(r, options) }
+ return self
+ end
+
+ resource = Resource.new(resources.pop)
+
+ if @scope[:scope_level] == :resources
+ nested do
+ resources(resource.name, options, &block)
+ end
+ return self
+ end
+
+ scope(:path => "/#{resource.name}", :controller => resource.controller) do
+ with_scope_level(:resources, resource) do
+ yield if block_given?
+
+ with_scope_level(:collection) do
+ get "(.:format)", :to => :index, :as => resource.collection_name
+ post "(.:format)", :to => :create
+
+ with_exclusive_name_prefix :new do
+ get "/new(.:format)", :to => :new, :as => resource.singular
+ end
+ end
+
+ with_scope_level(:member) do
+ scope("/:id") do
+ get "(.:format)", :to => :show, :as => resource.member_name
+ put "(.:format)", :to => :update
+ delete "(.:format)", :to => :destroy
+
+ with_exclusive_name_prefix :edit do
+ get "/edit(.:format)", :to => :edit, :as => resource.singular
+ end
+ end
+ end
+ end
+ end
- path_regexp = Rack::Mount::Strexp.compile(path, constraints, SEPARATORS)
- segment_keys = Rack::Mount::RegexpWithNamedGroups.new(path_regexp).names
- constraints.reject! { |k, v| segment_keys.include?(k.to_s) }
- conditions.merge!(constraints)
+ self
+ end
- if via = options[:via]
- via = Array(via).map { |m| m.to_s.upcase }
- conditions[:request_method] = Regexp.union(*via)
+ def collection
+ unless @scope[:scope_level] == :resources
+ raise ArgumentError, "can't use collection outside resources scope"
+ end
+
+ with_scope_level(:collection) do
+ scope(:name_prefix => parent_resource.collection_name, :as => "") do
+ yield
+ end
+ end
end
- defaults[:controller] = @scope[:controller].to_s if @scope[:controller]
+ def member
+ unless @scope[:scope_level] == :resources
+ raise ArgumentError, "can't use member outside resources scope"
+ end
- if options[:to].respond_to?(:call)
- app = options[:to]
- defaults.delete(:controller)
- defaults.delete(:action)
- elsif options[:to].is_a?(String)
- defaults[:controller], defaults[:action] = options[:to].split('#')
- elsif options[:to].is_a?(Symbol)
- defaults[:action] = options[:to].to_s
+ with_scope_level(:member) do
+ scope("/:id", :name_prefix => parent_resource.member_name, :as => "") do
+ yield
+ end
+ end
end
- app ||= Routing::RouteSet::Dispatcher.new(:defaults => defaults)
- if app.is_a?(Routing::RouteSet::Dispatcher)
- unless defaults.include?(:controller) || segment_keys.include?("controller")
- raise ArgumentError, "missing :controller"
+ def nested
+ unless @scope[:scope_level] == :resources
+ raise ArgumentError, "can't use nested outside resources scope"
end
- unless defaults.include?(:action) || segment_keys.include?("action")
- raise ArgumentError, "missing :action"
+
+ with_scope_level(:nested) do
+ scope("/#{parent_resource.id_segment}", :name_prefix => parent_resource.member_name) do
+ yield
+ end
end
end
- app = Constraints.new(app, blocks) if blocks.any?
- @set.add_route(app, conditions, requirements, defaults, options[:as])
+ def match(*args)
+ options = args.extract_options!
- self
- end
+ if args.length > 1
+ args.each { |path| match(path, options) }
+ return self
+ end
- def redirect(path, options = {})
- status = options[:status] || 301
- lambda { |env|
- req = Rack::Request.new(env)
- url = req.scheme + '://' + req.host + path
- [status, {'Location' => url, 'Content-Type' => 'text/html'}, ['Moved Permanently']]
- }
- end
+ if args.first.is_a?(Symbol)
+ with_exclusive_name_prefix(args.first) do
+ return match("/#{args.first}(.:format)", options.merge(:to => args.first.to_sym))
+ end
+ end
- private
- def map_method(method, *args, &block)
- options = args.last.is_a?(Hash) ? args.pop : {}
- options[:via] = method
args.push(options)
- match(*args, &block)
- self
+
+ case options.delete(:on)
+ when :collection
+ return collection { match(*args) }
+ when :member
+ return member { match(*args) }
+ end
+
+ if @scope[:scope_level] == :resources
+ raise ArgumentError, "can't define route directly in resources scope"
+ end
+
+ super
end
+
+ protected
+ def parent_resource
+ @scope[:scope_level_resource]
+ end
+
+ private
+ def with_exclusive_name_prefix(prefix)
+ begin
+ old_name_prefix = @scope[:name_prefix]
+
+ if !old_name_prefix.blank?
+ @scope[:name_prefix] = "#{prefix}_#{@scope[:name_prefix]}"
+ else
+ @scope[:name_prefix] = prefix.to_s
+ end
+
+ yield
+ ensure
+ @scope[:name_prefix] = old_name_prefix
+ end
+ end
+
+ def with_scope_level(kind, resource = parent_resource)
+ old, @scope[:scope_level] = @scope[:scope_level], kind
+ old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
+ yield
+ ensure
+ @scope[:scope_level] = old
+ @scope[:scope_level_resource] = old_resource
+ end
+ end
+
+ include Base
+ include HttpHelpers
+ include Scoping
+ include Resources
end
end
end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index c28df76f3f..bd397432ce 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -5,7 +5,7 @@ module ActionDispatch
module Routing
class RouteSet #:nodoc:
NotFound = lambda { |env|
- raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect} with #{env.inspect}"
+ raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}"
}
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
@@ -18,31 +18,37 @@ module ActionDispatch
def call(env)
params = env[PARAMETERS_KEY]
+ prepare_params!(params)
+
+ unless controller = controller(params)
+ return [404, {'X-Cascade' => 'pass'}, []]
+ end
+
+ controller.action(params[:action]).call(env)
+ end
+
+ def prepare_params!(params)
merge_default_action!(params)
split_glob_param!(params) if @glob_param
+
params.each do |key, value|
if value.is_a?(String)
value = value.dup.force_encoding(Encoding::BINARY) if value.respond_to?(:force_encoding)
params[key] = URI.unescape(value)
end
end
+ end
- if env['action_controller.recognize']
- [200, {}, params]
- else
- controller = controller(params)
- controller.action(params[:action]).call(env)
+ def controller(params)
+ if params && params.has_key?(:controller)
+ controller = "#{params[:controller].camelize}Controller"
+ ActiveSupport::Inflector.constantize(controller)
end
+ rescue NameError
+ nil
end
private
- def controller(params)
- if params && params.has_key?(:controller)
- controller = "#{params[:controller].camelize}Controller"
- ActiveSupport::Inflector.constantize(controller)
- end
- end
-
def merge_default_action!(params)
params[:action] ||= 'index'
end
@@ -197,26 +203,40 @@ module ActionDispatch
end
end
- attr_accessor :routes, :named_routes, :configuration_files
+ attr_accessor :routes, :named_routes
+ attr_accessor :disable_clear_and_finalize
def initialize
- self.configuration_files = []
-
self.routes = []
self.named_routes = NamedRouteCollection.new
- clear!
+ @disable_clear_and_finalize = false
end
def draw(&block)
- clear!
- Mapper.new(self).instance_exec(DeprecatedMapper.new(self), &block)
+ clear! unless @disable_clear_and_finalize
+
+ mapper = Mapper.new(self)
+ if block.arity == 1
+ mapper.instance_exec(DeprecatedMapper.new(self), &block)
+ else
+ mapper.instance_exec(&block)
+ end
+
+ finalize! unless @disable_clear_and_finalize
+
+ nil
+ end
+
+ def finalize!
@set.add_route(NotFound)
install_helpers
@set.freeze
end
def clear!
+ # Clear the controller cache so we may discover new ones
+ @controller_constraints = nil
routes.clear
named_routes.clear
@set = ::Rack::Mount::RouteSet.new(:parameters_key => PARAMETERS_KEY)
@@ -231,63 +251,38 @@ module ActionDispatch
routes.empty?
end
- def add_configuration_file(path)
- self.configuration_files << path
- end
-
- # Deprecated accessor
- def configuration_file=(path)
- add_configuration_file(path)
- end
-
- # Deprecated accessor
- def configuration_file
- configuration_files
- end
+ CONTROLLER_REGEXP = /[_a-zA-Z0-9]+/
- def load!
- Routing.use_controllers!(nil) # Clear the controller cache so we may discover new ones
- load_routes!
- end
-
- # reload! will always force a reload whereas load checks the timestamp first
- alias reload! load!
-
- def reload
- if configuration_files.any? && @routes_last_modified
- if routes_changed_at == @routes_last_modified
- return # routes didn't change, don't reload
- else
- @routes_last_modified = routes_changed_at
- end
+ def controller_constraints
+ @controller_constraints ||= begin
+ source = controller_namespaces.map { |ns| "#{Regexp.escape(ns)}/#{CONTROLLER_REGEXP.source}" }
+ source << CONTROLLER_REGEXP.source
+ Regexp.compile(source.sort.reverse.join('|'))
end
-
- load!
end
- def load_routes!
- if configuration_files.any?
- configuration_files.each { |config| load(config) }
- @routes_last_modified = routes_changed_at
- else
- draw do |map|
- map.connect ":controller/:action/:id"
- end
- end
- end
+ def controller_namespaces
+ namespaces = Set.new
- def routes_changed_at
- routes_changed_at = nil
-
- configuration_files.each do |config|
- config_changed_at = File.stat(config).mtime
+ # Find any nested controllers already in memory
+ ActionController::Base.subclasses.each do |klass|
+ controller_name = klass.underscore
+ namespaces << controller_name.split('/')[0...-1].join('/')
+ end
- if routes_changed_at.nil? || config_changed_at > routes_changed_at
- routes_changed_at = config_changed_at
+ # TODO: Move this into Railties
+ if defined?(Rails.application)
+ # Find namespaces in controllers/ directory
+ Rails.application.config.controller_paths.each do |load_path|
+ load_path = File.expand_path(load_path)
+ Dir["#{load_path}/**/*_controller.rb"].collect do |path|
+ namespaces << File.dirname(path).sub(/#{load_path}\/?/, '')
+ end
end
end
- routes_changed_at
+ namespaces.delete('')
+ namespaces
end
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil)
@@ -372,14 +367,34 @@ module ActionDispatch
end
recall[:action] = options.delete(:action) if options[:action] == 'index'
- path = _uri(named_route, options, recall)
+ opts = {}
+ opts[:parameterize] = lambda { |name, value|
+ if name == :controller
+ value
+ elsif value.is_a?(Array)
+ value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/')
+ else
+ Rack::Mount::Utils.escape_uri(value.to_param)
+ end
+ }
+
+ unless result = @set.generate(:path_info, named_route, options, recall, opts)
+ raise ActionController::RoutingError, "No route matches #{options.inspect}"
+ end
+
+ path, params = result
+ params.each do |k, v|
+ if v
+ params[k] = v
+ else
+ params.delete(k)
+ end
+ end
+
if path && method == :generate_extras
- uri = URI(path)
- extras = uri.query ?
- Rack::Utils.parse_nested_query(uri.query).keys.map { |k| k.to_sym } :
- []
- [uri.path, extras]
+ [path, params.keys]
elsif path
+ path << "?#{params.to_query}" if params.any?
path
else
raise ActionController::RoutingError, "No route matches #{options.inspect}"
@@ -390,37 +405,11 @@ module ActionDispatch
def call(env)
@set.call(env)
- rescue ActionController::RoutingError => e
- raise e if env['action_controller.rescue_error'] == false
-
- method, path = env['REQUEST_METHOD'].downcase.to_sym, env['PATH_INFO']
-
- # Route was not recognized. Try to find out why (maybe wrong verb).
- allows = HTTP_METHODS.select { |verb|
- begin
- recognize_path(path, {:method => verb}, false)
- rescue ActionController::RoutingError
- nil
- end
- }
-
- if !HTTP_METHODS.include?(method)
- raise ActionController::NotImplemented.new(*allows)
- elsif !allows.empty?
- raise ActionController::MethodNotAllowed.new(*allows)
- else
- raise e
- end
- end
-
- def recognize(request)
- params = recognize_path(request.path, extract_request_environment(request))
- request.path_parameters = params.with_indifferent_access
- "#{params[:controller].to_s.camelize}Controller".constantize
end
- def recognize_path(path, environment = {}, rescue_error = true)
+ def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase
+ path = Rack::Mount::Utils.normalize_path(path)
begin
env = Rack::MockRequest.env_for(path, {:method => method})
@@ -428,70 +417,17 @@ module ActionDispatch
raise ActionController::RoutingError, e.message
end
- env['action_controller.recognize'] = true
- env['action_controller.rescue_error'] = rescue_error
- status, headers, body = call(env)
- body
- end
-
- # Subclasses and plugins may override this method to extract further attributes
- # from the request, for use by route conditions and such.
- def extract_request_environment(request)
- { :method => request.method }
- end
-
- private
- def _uri(named_route, params, recall)
- params = URISegment.wrap_values(params)
- recall = URISegment.wrap_values(recall)
-
- unless result = @set.generate(:path_info, named_route, params, recall)
- return
+ req = Rack::Request.new(env)
+ @set.recognize(req) do |route, params|
+ dispatcher = route.app
+ if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params)
+ dispatcher.prepare_params!(params)
+ return params
end
-
- uri, params = result
- params.each do |k, v|
- if v._value
- params[k] = v._value
- else
- params.delete(k)
- end
- end
-
- uri << "?#{Rack::Mount::Utils.build_nested_query(params)}" if uri && params.any?
- uri
end
- class URISegment < Struct.new(:_value, :_escape)
- EXCLUDED = [:controller]
-
- def self.wrap_values(hash)
- hash.inject({}) { |h, (k, v)|
- h[k] = new(v, !EXCLUDED.include?(k.to_sym))
- h
- }
- end
-
- extend Forwardable
- def_delegators :_value, :==, :eql?, :hash
-
- def to_param
- @to_param ||= begin
- if _value.is_a?(Array)
- _value.map { |v| _escaped(v) }.join('/')
- else
- _escaped(_value)
- end
- end
- end
- alias_method :to_s, :to_param
-
- private
- def _escaped(value)
- v = value.respond_to?(:to_param) ? value.to_param : value
- _escape ? Rack::Mount::Utils.escape_uri(v) : v.to_s
- end
- end
+ raise ActionController::RoutingError, "No route matches #{path.inspect}"
+ 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 9a917f704a..9c215de743 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
@@ -1,3 +1,5 @@
+require 'action_controller/vendor/html-scanner'
+
module ActionDispatch
module Assertions
module DomAssertions
@@ -15,7 +17,7 @@ module ActionDispatch
assert_block(full_message) { expected_dom == actual_dom }
end
-
+
# The negated form of +assert_dom_equivalent+.
#
# ==== Examples
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index 501a7c4dfb..5686bbdbde 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -28,7 +28,7 @@ module ActionDispatch
assert_block("") { true } # to count the assertion
elsif type.is_a?(Fixnum) && @response.response_code == type
assert_block("") { true } # to count the assertion
- elsif type.is_a?(Symbol) && @response.response_code == ActionDispatch::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
+ elsif type.is_a?(Symbol) && @response.response_code == Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
assert_block("") { true } # to count the assertion
else
assert_block(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code)) { false }
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index f0cca9a5f2..0c33539b4a 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -46,7 +46,6 @@ module ActionDispatch
request_method = nil
end
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
request = recognized_request_for(path, request_method)
expected_options = expected_options.clone
@@ -80,7 +79,6 @@ module ActionDispatch
def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
expected_path = "/#{expected_path}" unless expected_path[0] == ?/
# Load routes.rb if it hasn't been loaded.
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults)
found_extras = options.reject {|k, v| ! extra_keys.include? k}
@@ -126,6 +124,46 @@ module ActionDispatch
assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message)
end
+ # A helper to make it easier to test different route configurations.
+ # This method temporarily replaces ActionController::Routing::Routes
+ # with a new RouteSet instance.
+ #
+ # The new instance is yielded to the passed block. Typically the block
+ # will create some routes using <tt>map.draw { map.connect ... }</tt>:
+ #
+ # with_routing do |set|
+ # set.draw do |map|
+ # map.connect ':controller/:action/:id'
+ # assert_equal(
+ # ['/content/10/show', {}],
+ # map.generate(:controller => 'content', :id => 10, :action => 'show')
+ # end
+ # end
+ # end
+ #
+ def with_routing
+ real_routes = ActionController::Routing::Routes
+ ActionController::Routing.module_eval { remove_const :Routes }
+
+ temporary_routes = ActionController::Routing::RouteSet.new
+ ActionController::Routing.module_eval { const_set :Routes, temporary_routes }
+
+ yield temporary_routes
+ ensure
+ if ActionController::Routing.const_defined? :Routes
+ ActionController::Routing.module_eval { remove_const :Routes }
+ end
+ ActionController::Routing.const_set(:Routes, real_routes) if real_routes
+ end
+
+ def method_missing(selector, *args, &block)
+ if @controller && ActionController::Routing::Routes.named_routes.helpers.include?(selector)
+ @controller.send(selector, *args, &block)
+ else
+ super
+ end
+ end
+
private
# Recognizes the route for a given path.
def recognized_request_for(path, request_method = nil)
@@ -134,9 +172,11 @@ module ActionDispatch
# Assume given controller
request = ActionController::TestRequest.new
request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method
- request.path = path
+ request.path = path
+
+ params = ActionController::Routing::Routes.recognize_path(path, { :method => request.method })
+ request.path_parameters = params.with_indifferent_access
- ActionController::Routing::Routes.recognize(request)
request
end
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
index d22adfa749..c2dc591ff7 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -1,3 +1,5 @@
+require 'action_controller/vendor/html-scanner'
+
#--
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
# Under MIT and/or CC By license.
@@ -16,7 +18,7 @@ module ActionDispatch
#
# Use +css_select+ to select elements without making an assertions, either
# from the response HTML or elements selected by the enclosing assertion.
- #
+ #
# In addition to HTML responses, you can make the following assertions:
# * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations.
# * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
@@ -53,8 +55,8 @@ module ActionDispatch
# end
#
# # Selects all list items in unordered lists
- # items = css_select("ul>li")
- #
+ # items = css_select("ul>li")
+ #
# # Selects all form tags and then all inputs inside the form
# forms = css_select("form")
# forms.each do |form|
@@ -212,7 +214,7 @@ module ActionDispatch
# Otherwise just operate on the response document.
root = response_from_page_or_rjs
end
-
+
# First or second argument is the selector: string and we pass
# all remaining arguments. Array and we pass the argument. Also
# accepts selector itself.
@@ -225,7 +227,7 @@ module ActionDispatch
selector = arg
else raise ArgumentError, "Expecting a selector as the first argument"
end
-
+
# Next argument is used for equality tests.
equals = {}
case arg = args.shift
@@ -315,10 +317,10 @@ module ActionDispatch
# Returns all matches elements.
matches
end
-
+
def count_description(min, max) #:nodoc:
pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
-
+
if min && max && (max != min)
"between #{min} and #{max} elements"
elsif min && !(min == 1 && max == 1)
@@ -327,7 +329,7 @@ module ActionDispatch
"at most #{max} #{pluralize['element', max]}"
end
end
-
+
# :call-seq:
# assert_select_rjs(id?) { |elements| ... }
# assert_select_rjs(statement, id?) { |elements| ... }
@@ -344,7 +346,7 @@ module ActionDispatch
# that update or insert an element with that identifier.
#
# Use the first argument to narrow down assertions to only statements
- # of that type. Possible values are <tt>:replace</tt>, <tt>:replace_html</tt>,
+ # of that type. Possible values are <tt>:replace</tt>, <tt>:replace_html</tt>,
# <tt>:show</tt>, <tt>:hide</tt>, <tt>:toggle</tt>, <tt>:remove</tta>,
# <tt>:insert_html</tt> and <tt>:redirect</tt>.
#
@@ -494,7 +496,7 @@ module ActionDispatch
# end
# end
# end
- #
+ #
#
# # Selects all paragraph tags from within the description of an RSS feed
# assert_select_feed :rss, 2.0 do
diff --git a/actionpack/lib/action_dispatch/testing/assertions/tag.rb b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
index ef6867576e..5c735e61b2 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/tag.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
@@ -1,3 +1,5 @@
+require 'action_controller/vendor/html-scanner'
+
module ActionDispatch
module Assertions
# Pair of assertions to testing elements in the HTML output of the response.
@@ -76,10 +78,10 @@ module ActionDispatch
# # Assert that there is a "span" containing between 2 and 4 "em" tags
# # as immediate children
# assert_tag :tag => "span",
- # :children => { :count => 2..4, :only => { :tag => "em" } }
+ # :children => { :count => 2..4, :only => { :tag => "em" } }
#
# # Get funky: assert that there is a "div", with an "ul" ancestor
- # # and an "li" parent (with "class" = "enum"), and containing a
+ # # and an "li" parent (with "class" = "enum"), and containing a
# # "span" descendant that contains text matching /hello world/
# assert_tag :tag => "div",
# :ancestor => { :tag => "ul" },
@@ -98,7 +100,7 @@ module ActionDispatch
tag = find_tag(opts)
assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
end
-
+
# Identical to +assert_tag+, but asserts that a matching tag does _not_
# exist. (See +assert_tag+ for a full discussion of the syntax.)
#
@@ -118,6 +120,19 @@ module ActionDispatch
tag = find_tag(opts)
assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
end
+
+ def find_tag(conditions)
+ html_document.find(conditions)
+ end
+
+ def find_all_tag(conditions)
+ html_document.find_all(conditions)
+ end
+
+ def html_document
+ xml = @response.content_type =~ /xml$/
+ @html_document ||= HTML::Document.new(@response.body, false, xml)
+ end
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 40d6f97b2a..2a5f5dcd5c 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -2,9 +2,7 @@ require 'stringio'
require 'uri'
require 'active_support/test_case'
require 'active_support/core_ext/object/metaclass'
-
-# TODO: Remove circular dependency on ActionController
-require 'action_controller/testing/process'
+require 'rack/test'
module ActionDispatch
module Integration #:nodoc:
@@ -128,9 +126,7 @@ module ActionDispatch
DEFAULT_HOST = "www.example.com"
include Test::Unit::Assertions
- include ActionDispatch::Assertions
- include ActionController::TestProcess
- include RequestHelpers
+ include TestProcess, RequestHelpers, Assertions
%w( status status_message headers body redirect? ).each do |method|
delegate method, :to => :response, :allow_nil => true
@@ -415,7 +411,7 @@ module ActionDispatch
# At its simplest, you simply extend IntegrationTest and write your tests
# using the get/post methods:
#
- # require "#{File.dirname(__FILE__)}/test_helper"
+ # require "test_helper"
#
# class ExampleTest < ActionController::IntegrationTest
# fixtures :people
@@ -439,7 +435,7 @@ module ActionDispatch
# powerful testing DSL that is specific for your application. You can even
# reference any named routes you happen to have defined!
#
- # require "#{File.dirname(__FILE__)}/test_helper"
+ # require "test_helper"
#
# class AdvancedTest < ActionController::IntegrationTest
# fixtures :people, :rooms
diff --git a/actionpack/lib/action_dispatch/testing/performance_test.rb b/actionpack/lib/action_dispatch/testing/performance_test.rb
index b1ed9d31f4..1b9a6c18b7 100644
--- a/actionpack/lib/action_dispatch/testing/performance_test.rb
+++ b/actionpack/lib/action_dispatch/testing/performance_test.rb
@@ -1,15 +1,17 @@
require 'active_support/testing/performance'
require 'active_support/testing/default'
-module ActionDispatch
- # An integration test that runs a code profiler on your test methods.
- # Profiling output for combinations of each test method, measurement, and
- # output format are written to your tmp/performance directory.
- #
- # By default, process_time is measured and both flat and graph_html output
- # 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
+if defined?(ActiveSupport::Testing::Performance)
+ module ActionDispatch
+ # An integration test that runs a code profiler on your test methods.
+ # Profiling output for combinations of each test method, measurement, and
+ # output format are written to your tmp/performance directory.
+ #
+ # By default, process_time is measured and both flat and graph_html output
+ # 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
-end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
new file mode 100644
index 0000000000..eae703e1b6
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -0,0 +1,42 @@
+module ActionDispatch
+ module TestProcess
+ def assigns(key = nil)
+ assigns = {}
+ @controller.instance_variable_names.each do |ivar|
+ next if ActionController::Base.protected_instance_variables.include?(ivar)
+ assigns[ivar[1..-1]] = @controller.instance_variable_get(ivar)
+ end
+
+ key.nil? ? assigns : assigns[key.to_s]
+ end
+
+ def session
+ @request.session
+ end
+
+ def flash
+ @request.flash
+ end
+
+ def cookies
+ @request.cookies.merge(@response.cookies)
+ end
+
+ def redirect_to_url
+ @response.redirect_url
+ end
+
+ # Shortcut for <tt>ARack::Test::UploadedFile.new(ActionController::TestCase.fixture_path + path, type)</tt>:
+ #
+ # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
+ #
+ # To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
+ # This will not affect other platforms:
+ #
+ # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary)
+ def fixture_file_upload(path, mime_type = nil, binary = false)
+ fixture_path = ActionController::TestCase.send(:fixture_path) if ActionController::TestCase.respond_to?(:fixture_path)
+ Rack::Test::UploadedFile.new("#{fixture_path}#{path}", mime_type, binary)
+ end
+ end
+end
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index e95e84aeb5..8ce6e82524 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -21,38 +21,40 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-require File.join(File.dirname(__FILE__), "action_pack")
+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'
+
+require 'action_pack'
module ActionView
- def self.load_all!
- [Context, Base, InlineTemplate, TemplateError]
- end
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Context
+ autoload :Template
+ autoload :Helpers
+ autoload :SafeBuffer
+
+ autoload_under "render" do
+ autoload :Partials
+ autoload :Rendering
+ end
- autoload :Base, 'action_view/base'
- autoload :Context, 'action_view/context'
- autoload :Helpers, 'action_view/helpers'
- autoload :MissingTemplate, 'action_view/base'
- autoload :Partials, 'action_view/render/partials'
- autoload :Resolver, 'action_view/template/resolver'
- autoload :PathResolver, 'action_view/template/resolver'
- autoload :PathSet, 'action_view/paths'
- autoload :Rendering, 'action_view/render/rendering'
- autoload :Template, 'action_view/template/template'
- autoload :TemplateError, 'action_view/template/error'
- autoload :TemplateHandler, 'action_view/template/handler'
- autoload :TemplateHandlers, 'action_view/template/handlers'
- autoload :TextTemplate, 'action_view/template/text'
- autoload :Helpers, 'action_view/helpers'
- autoload :FileSystemResolverWithFallback, 'action_view/template/resolver'
- autoload :SafeBuffer, 'action_view/safe_buffer'
+ autoload :MissingTemplate, 'action_view/base'
+ autoload :Resolver, 'action_view/template/resolver'
+ autoload :PathResolver, 'action_view/template/resolver'
+ autoload :PathSet, 'action_view/paths'
+ autoload :FileSystemResolverWithFallback, 'action_view/template/resolver'
+
+ autoload :TemplateError, 'action_view/template/error'
+ autoload :TemplateHandler, 'action_view/template'
+ autoload :TemplateHandlers, 'action_view/template'
+ end
end
require 'action_view/erb/util'
-
+require 'action_view/base'
I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
-
-activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
-$:.unshift activesupport_path if File.directory?(activesupport_path)
-require 'active_support'
-require 'active_support/core_ext/class/attribute_accessors'
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index c33695770f..4970c768e8 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -196,7 +196,7 @@ module ActionView #:nodoc:
end
class << self
- delegate :erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB'
+ delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
delegate :logger, :to => 'ActionController::Base', :allow_nil => true
end
@@ -274,6 +274,7 @@ module ActionView #:nodoc:
end
def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil, formats = nil)#:nodoc:
+ @config = nil
@formats = formats
@assigns = assigns_for_first_render.each { |key, value| instance_variable_set("@#{key}", value) }
@controller = controller
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index d0c66eda60..81c9c88820 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -504,8 +504,9 @@ module ActionView
end
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
- # assigned to the template (identified by +object+). The text of label will default to the attribute name unless you specify
- # it explicitly. Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
+ # assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
+ # is found in the current I18n locale (through views.labels.<modelname>.<attribute>) or you specify it explicitly.
+ # Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
# target labels for radio_button tags (where the value is used in the ID of the input tag).
#
@@ -513,6 +514,29 @@ module ActionView
# label(:post, :title)
# # => <label for="post_title">Title</label>
#
+ # You can localize your labels based on model and attribute names.
+ # For example you can define the following in your locale (e.g. en.yml)
+ #
+ # views:
+ # labels:
+ # post:
+ # body: "Write your entire text here"
+ #
+ # Which then will result in
+ #
+ # label(:post, :body)
+ # # => <label for="post_body">Write your entire text here</label>
+ #
+ # Localization can also be based purely on the translation of the attribute-name like this:
+ #
+ # activemodel:
+ # attribute:
+ # post:
+ # cost: "Total cost"
+ #
+ # label(:post, :cost)
+ # # => <label for="post_cost">Total cost</label>
+ #
# label(:post, :title, "A short title")
# # => <label for="post_title">A short title</label>
#
@@ -751,7 +775,19 @@ module ActionView
add_default_name_and_id_for_value(tag_value, name_and_id)
options.delete("index")
options["for"] ||= name_and_id["id"]
- content = (text.blank? ? nil : text.to_s) || method_name.humanize
+
+ content = if text.blank?
+ I18n.t("views.labels.#{object_name}.#{method_name}", :default => "").presence
+ else
+ text.to_s
+ end
+
+ content ||= if object && object.class.respond_to?(:human_attribute_name)
+ object.class.human_attribute_name(method_name)
+ end
+
+ content ||= method_name.humanize
+
label_tag(name_and_id["id"], content, options)
end
diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb
index 1f7ecc0ef8..657d26f0a2 100644
--- a/actionpack/lib/action_view/helpers/sanitize_helper.rb
+++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb
@@ -1,3 +1,4 @@
+require 'action_controller/vendor/html-scanner'
require 'action_view/helpers/tag_helper'
module ActionView
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
index 564f12c955..35c431d78d 100644
--- a/actionpack/lib/action_view/helpers/translation_helper.rb
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -12,7 +12,7 @@ module ActionView
# prepend the key with a period, nothing is converted.
def translate(key, options = {})
options[:raise] = true
- I18n.translate(scope_key_by_partial(key), options)
+ I18n.translate(scope_key_by_partial(key), options).html_safe!
rescue I18n::MissingTranslationData => e
keys = I18n.send(:normalize_translation_keys, e.locale, e.key, e.options[:scope])
content_tag('span', keys.join(', '), :class => 'translation_missing')
diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb
index 23bde61f9c..0059b79e5f 100644
--- a/actionpack/lib/action_view/paths.rb
+++ b/actionpack/lib/action_view/paths.rb
@@ -4,7 +4,7 @@ module ActionView #:nodoc:
# TODO: Clean this up
if obj.is_a?(String)
if cache.nil?
- cache = !defined?(Rails) || Rails.application.config.cache_classes
+ cache = !defined?(Rails.application) || Rails.application.config.cache_classes
end
FileSystemResolverWithFallback.new(obj, :cache => cache)
else
diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb
new file mode 100644
index 0000000000..a90e0636b9
--- /dev/null
+++ b/actionpack/lib/action_view/railtie.rb
@@ -0,0 +1,2 @@
+require "action_view"
+require "rails" \ No newline at end of file
diff --git a/actionpack/lib/action_view/render/partials.rb b/actionpack/lib/action_view/render/partials.rb
index 2eb88ae3e5..5158415c20 100644
--- a/actionpack/lib/action_view/render/partials.rb
+++ b/actionpack/lib/action_view/render/partials.rb
@@ -181,55 +181,70 @@ module ActionView
def initialize(view_context, options, block)
@view = view_context
@partial_names = PARTIAL_NAMES[@view.controller.class]
-
+
key = Thread.current[:format_locale_key]
@templates = TEMPLATES[key] if key
-
+
setup(options, block)
end
-
+
def setup(options, block)
partial = options[:partial]
-
- @options = options
- @locals = options[:locals] || {}
- @block = block
-
+
+ @options = options
+ @locals = options[:locals] || {}
+ @block = block
+
if String === partial
- @object = options[:object]
- @path = partial
+ @object = options[:object]
+ @path = partial
+ @collection = collection
else
@object = partial
- @path = partial_path(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
- if @collection = collection
- render_collection
+ options = @options
+
+ if @collection
+ ActiveSupport::Notifications.instrument(:render_collection, :path => @path,
+ :count => @collection.size) do
+ render_collection
+ end
else
- @template = template = find_template
- render_template(template, @object || @locals[template.variable_name])
+ content = ActiveSupport::Notifications.instrument(:render_partial, :path => @path) do
+ render_partial
+ end
+
+ if !@block && options[:layout]
+ content = @view._render_layout(find_template(options[:layout]), @locals){ content }
+ end
+ content
end
end
def render_collection
@template = template = find_template
-
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(template) : collection_without_template
+ result = template ? collection_with_template : collection_without_template
result.join(spacer).html_safe!
end
- def collection_with_template(template)
- options = @options
-
- segments, locals, as = [], @locals, options[:as] || template.variable_name
+ def collection_with_template(template = @template)
+ segments, locals, as = [], @locals, @options[:as] || template.variable_name
counter_name = template.counter_name
locals[counter_name] = -1
@@ -240,21 +255,19 @@ module ActionView
segments << template.render(@view, locals)
end
-
+
@template = template
segments
end
- def collection_without_template
- options = @options
-
- segments, locals, as = [], @locals, options[:as]
+ def collection_without_template(collection_paths = @collection_paths)
+ segments, locals, as = [], @locals, @options[:as]
index, template = -1, nil
- @collection.each do |object|
- template = find_template(partial_path(object))
+ @collection.each_with_index do |object, i|
+ template = find_template(collection_paths[i])
locals[template.counter_name] = (index += 1)
- locals[template.variable_name] = object
+ locals[as || template.variable_name] = object
segments << template.render(@view, locals)
end
@@ -263,18 +276,15 @@ module ActionView
segments
end
- def render_template(template, object = @object)
- options, locals, view = @options, @locals, @view
- locals[options[:as] || template.variable_name] = object
+ def render_partial(object = @object)
+ @template = template = find_template
+ locals, view = @locals, @view
- content = template.render(view, locals) do |*name|
- @view._layout_for(*name, &@block)
- end
+ object ||= locals[template.variable_name]
+ locals[@options[:as] || template.variable_name] = object
- if @block || !options[:layout]
- content
- else
- find_template(options[:layout]).render(@view, @locals) { content }
+ template.render(view, locals) do |*name|
+ view._layout_for(*name, &@block)
end
end
@@ -294,7 +304,7 @@ module ActionView
path && @templates[path] ||= _find_template(path)
end
end
-
+
def _find_template(path)
if controller = @view.controller
prefix = controller.controller_path unless path.include?(?/)
@@ -305,9 +315,9 @@ module ActionView
def partial_path(object = @object)
@partial_names[object.class] ||= begin
- return nil unless object.respond_to?(:to_model)
+ object = object.to_model if object.respond_to?(:to_model)
- object.to_model.class.model_name.partial_path.dup.tap do |partial|
+ object.class.model_name.partial_path.dup.tap do |partial|
path = @view.controller_path
partial.insert(0, "#{File.dirname(path)}/") if path.include?(?/)
end
@@ -319,7 +329,7 @@ module ActionView
_evaluate_assigns_and_ivars
details = options[:_details]
-
+
# Is this needed
self.formats = details[:formats] if details
renderer = PartialRenderer.new(self, options, nil)
@@ -329,12 +339,12 @@ module ActionView
end
def _render_partial(options, &block) #:nodoc:
- if @renderer
+ if defined? @renderer
@renderer.setup(options, block)
else
@renderer = PartialRenderer.new(self, options, block)
end
-
+
@renderer.render
end
diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb
index 7006a5b968..48316cac53 100644
--- a/actionpack/lib/action_view/render/rendering.rb
+++ b/actionpack/lib/action_view/render/rendering.rb
@@ -22,15 +22,18 @@ module ActionView
return _render_partial(options)
end
- layout = find(layout, {:formats => formats}) if layout
+ template = if options[:file]
+ find(options[:file], {:formats => formats})
+ elsif options[:inline]
+ handler = Template.handler_class_for_extension(options[:type] || "erb")
+ Template.new(options[:inline], "inline template", handler, {})
+ elsif options[:text]
+ Template::Text.new(options[:text])
+ end
- if file = options[:file]
- template = find(file, {:formats => formats})
+ if template
+ layout = find(layout, {:formats => formats}) if layout
_render_template(template, layout, :locals => options[:locals])
- elsif inline = options[:inline]
- _render_inline(inline, layout, options)
- elsif text = options[:text]
- _render_text(text, layout, options[:locals])
end
when :update
update_page(&block)
@@ -73,51 +76,25 @@ module ActionView
# would be <html>Hello David</html>.
def _layout_for(name = nil, &block)
return @_content_for[name || :layout] if !block_given? || name
-
capture(&block)
end
- def _render_inline(inline, layout, options)
- handler = Template.handler_class_for_extension(options[:type] || "erb")
- template = Template.new(options[:inline],
- "inline #{options[:inline].inspect}", handler, {})
-
- locals = options[:locals]
- content = template.render(self, locals)
- _render_text(content, layout, locals)
- end
-
- def _render_text(content, layout, locals)
- content = layout.render(self, locals) do |*name|
- _layout_for(*name) { content }
- end if layout
- content
- end
-
# This is the API to render a ViewContext's template from a controller.
#
# Internal Options:
# _template:: The Template object to render
# _layout:: The layout, if any, to wrap the Template in
- # _partial:: true if the template is a partial
def render_template(options)
_evaluate_assigns_and_ivars
- template, layout, partial = options.values_at(:_template, :_layout, :_partial)
- _render_template(template, layout, options, partial)
+ template, layout = options.values_at(:_template, :_layout)
+ _render_template(template, layout, options)
end
- def _render_template(template, layout = nil, options = {}, partial = nil)
- logger && logger.info do
- msg = "Rendering #{template.inspect}"
- msg << " (#{options[:status]})" if options[:status]
- msg
- end
-
+ def _render_template(template, layout = nil, options = {})
locals = options[:locals] || {}
- content = if partial
- _render_partial_object(template, options)
- else
+ content = ActiveSupport::Notifications.instrument(:render_template,
+ :identifier => template.identifier, :layout => (layout ? layout.identifier : nil)) do
template.render(self, locals)
end
@@ -125,10 +102,16 @@ module ActionView
if layout
@_layout = layout.identifier
- logger.info("Rendering template within #{layout.inspect}") if logger
- content = layout.render(self, locals) {|*name| _layout_for(*name) }
+ content = _render_layout(layout, locals)
end
+
content
end
+
+ def _render_layout(layout, locals, &block)
+ ActiveSupport::Notifications.instrument(:render_layout, :identifier => layout.identifier) do
+ layout.render(self, locals){ |*name| _layout_for(*name, &block) }
+ end
+ end
end
end
diff --git a/actionpack/lib/action_view/safe_buffer.rb b/actionpack/lib/action_view/safe_buffer.rb
index 09f44ab26f..6be05b9e1e 100644
--- a/actionpack/lib/action_view/safe_buffer.rb
+++ b/actionpack/lib/action_view/safe_buffer.rb
@@ -1,4 +1,3 @@
-
module ActionView #:nodoc:
class SafeBuffer < String
def <<(value)
diff --git a/actionpack/lib/action_view/template/template.rb b/actionpack/lib/action_view/template.rb
index d1970ca3c7..adaf6544a7 100644
--- a/actionpack/lib/action_view/template/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -6,7 +6,16 @@ require "action_view/template/resolver"
module ActionView
class Template
- extend TemplateHandlers
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Error
+ autoload :Handler
+ autoload :Handlers
+ autoload :Text
+ end
+
+ extend Template::Handlers
attr_reader :source, :identifier, :handler, :mime_type, :formats, :details
def initialize(source, identifier, handler, details)
@@ -27,16 +36,14 @@ module ActionView
end
def render(view, locals, &block)
- ActiveSupport::Notifications.instrument(:render_template, :identifier => identifier) do
- method_name = compile(locals, view)
- view.send(method_name, locals, &block)
- end
+ method_name = compile(locals, view)
+ view.send(method_name, locals, &block)
rescue Exception => e
- if e.is_a?(TemplateError)
+ if e.is_a?(Template::Error)
e.sub_template_of(self)
raise e
else
- raise TemplateError.new(self, view.assigns, e)
+ raise Template::Error.new(self, view.assigns, e)
end
end
@@ -103,25 +110,10 @@ module ActionView
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
end
- raise ActionView::TemplateError.new(self, {}, e)
+ raise ActionView::Template::Error.new(self, {}, e)
end
end
- class LocalsKey
- @hash_keys = Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] = {} } }
-
- def self.get(*locals)
- @hash_keys[*locals] ||= new(klass, format, locale)
- end
-
- attr_accessor :hash
- def initialize(klass, format, locale)
- @hash = locals.hash
- end
-
- alias_method :eql?, :equal?
- end
-
def build_method_name(locals)
# TODO: is locals.keys.hash reliably the same?
@method_names[locals.keys.hash] ||=
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
index aa21606f76..648f708d3d 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -1,101 +1,105 @@
require "active_support/core_ext/enumerable"
module ActionView
- # The TemplateError 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.
- class TemplateError < ActionViewError #:nodoc:
- SOURCE_CODE_RADIUS = 3
+ 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.
+ class Error < ActionViewError #:nodoc:
+ SOURCE_CODE_RADIUS = 3
- attr_reader :original_exception
+ attr_reader :original_exception
- def initialize(template, assigns, original_exception)
- @template, @assigns, @original_exception = template, assigns.dup, original_exception
- @backtrace = compute_backtrace
- end
+ def initialize(template, assigns, original_exception)
+ @template, @assigns, @original_exception = template, assigns.dup, original_exception
+ @backtrace = compute_backtrace
+ end
- def file_name
- @template.identifier
- end
+ def file_name
+ @template.identifier
+ end
- def message
- ActiveSupport::Deprecation.silence { original_exception.message }
- end
+ def message
+ ActiveSupport::Deprecation.silence { original_exception.message }
+ end
- def clean_backtrace
- if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner)
- Rails.backtrace_cleaner.clean(original_exception.backtrace)
- else
- original_exception.backtrace
+ def clean_backtrace
+ if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner)
+ Rails.backtrace_cleaner.clean(original_exception.backtrace)
+ else
+ original_exception.backtrace
+ end
end
- end
- def sub_template_message
- if @sub_templates
- "Trace of template inclusion: " +
- @sub_templates.collect { |template| template.inspect }.join(", ")
- else
- ""
+ def sub_template_message
+ if @sub_templates
+ "Trace of template inclusion: " +
+ @sub_templates.collect { |template| template.inspect }.join(", ")
+ else
+ ""
+ end
end
- end
- def source_extract(indentation = 0)
- return unless num = line_number
- num = num.to_i
+ def source_extract(indentation = 0)
+ return unless num = line_number
+ num = num.to_i
- source_code = @template.source.split("\n")
+ source_code = @template.source.split("\n")
- start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
- end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
+ start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
+ end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
- indent = ' ' * indentation
- line_counter = start_on_line
- return unless source_code = source_code[start_on_line..end_on_line]
+ indent = ' ' * indentation
+ line_counter = start_on_line
+ return unless source_code = source_code[start_on_line..end_on_line]
- source_code.sum do |line|
- line_counter += 1
- "#{indent}#{line_counter}: #{line}\n"
+ source_code.sum do |line|
+ line_counter += 1
+ "#{indent}#{line_counter}: #{line}\n"
+ end
end
- end
-
- def sub_template_of(template_path)
- @sub_templates ||= []
- @sub_templates << template_path
- end
-
- def line_number
- @line_number ||=
- if file_name
- regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
- $1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp }
- end
- end
+ def sub_template_of(template_path)
+ @sub_templates ||= []
+ @sub_templates << template_path
+ end
- def to_s
- "\n#{self.class} (#{message}) #{source_location}:\n" +
- "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
- end
+ def line_number
+ @line_number ||=
+ if file_name
+ regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
- # don't do anything nontrivial here. Any raised exception from here becomes fatal
- # (and can't be rescued).
- def backtrace
- @backtrace
- end
+ $1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp }
+ end
+ end
- private
- def compute_backtrace
- [
- "#{source_location.capitalize}\n\n#{source_extract(4)}\n " +
- clean_backtrace.join("\n ")
- ]
+ def to_s
+ "\n#{self.class} (#{message}) #{source_location}:\n" +
+ "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
end
- def source_location
- if line_number
- "on line ##{line_number} of "
- else
- 'in '
- end + file_name
+ # don't do anything nontrivial here. Any raised exception from here becomes fatal
+ # (and can't be rescued).
+ def backtrace
+ @backtrace
end
+
+ private
+ def compute_backtrace
+ [
+ "#{source_location.capitalize}\n\n#{source_extract(4)}\n " +
+ clean_backtrace.join("\n ")
+ ]
+ end
+
+ def source_location
+ if line_number
+ "on line ##{line_number} of "
+ else
+ 'in '
+ end + file_name
+ end
+ end
end
-end \ No newline at end of file
+
+ TemplateError = Template::Error
+end
diff --git a/actionpack/lib/action_view/template/handler.rb b/actionpack/lib/action_view/template/handler.rb
index 4bf58b9fa8..221d1bd5c5 100644
--- a/actionpack/lib/action_view/template/handler.rb
+++ b/actionpack/lib/action_view/template/handler.rb
@@ -3,34 +3,39 @@ require "action_dispatch/http/mime_type"
# Legacy TemplateHandler stub
module ActionView
- module TemplateHandlers #:nodoc:
- module Compilable
- def self.included(base)
- base.extend(ClassMethods)
- end
+ class Template
+ module Handlers #:nodoc:
+ module Compilable
+ def self.included(base)
+ base.extend(ClassMethods)
+ end
- module ClassMethods
- def call(template)
- new.compile(template)
+ module ClassMethods
+ def call(template)
+ new.compile(template)
+ end
end
- end
- def compile(template)
- raise "Need to implement #{self.class.name}#compile(template)"
- end
+ def compile(template)
+ raise "Need to implement #{self.class.name}#compile(template)"
+ end
+ end
end
- end
- class TemplateHandler
- extlib_inheritable_accessor :default_format
- self.default_format = Mime::HTML
+ class Template::Handler
+ extlib_inheritable_accessor :default_format
+ self.default_format = Mime::HTML
- def self.call(template)
- raise "Need to implement #{self.class.name}#call(template)"
- end
+ def self.call(template)
+ raise "Need to implement #{self.class.name}#call(template)"
+ end
- def render(template, local_assigns)
- raise "Need to implement #{self.class.name}#render(template, local_assigns)"
+ def render(template, local_assigns)
+ raise "Need to implement #{self.class.name}#render(template, local_assigns)"
+ 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 faf54b9fe5..35488c0391 100644
--- a/actionpack/lib/action_view/template/handlers.rb
+++ b/actionpack/lib/action_view/template/handlers.rb
@@ -1,52 +1,54 @@
module ActionView #:nodoc:
- module TemplateHandlers #:nodoc:
- autoload :ERB, 'action_view/template/handlers/erb'
- autoload :RJS, 'action_view/template/handlers/rjs'
- autoload :Builder, 'action_view/template/handlers/builder'
-
- def self.extended(base)
- base.register_default_template_handler :erb, TemplateHandlers::ERB
- base.register_template_handler :rjs, TemplateHandlers::RJS
- base.register_template_handler :builder, TemplateHandlers::Builder
-
- # TODO: Depreciate old template extensions
- base.register_template_handler :rhtml, TemplateHandlers::ERB
- base.register_template_handler :rxml, TemplateHandlers::Builder
- end
-
- @@template_handlers = {}
- @@default_template_handlers = nil
+ class Template
+ module Handlers #:nodoc:
+ autoload :ERB, 'action_view/template/handlers/erb'
+ autoload :RJS, 'action_view/template/handlers/rjs'
+ 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
+ end
+
+ @@template_handlers = {}
+ @@default_template_handlers = nil
- def self.extensions
- @@template_handlers.keys
- end
-
- # Register a class that knows how to handle template files with the given
- # extension. This can be used to implement new template types.
- # The constructor for the class must take the ActiveView::Base instance
- # as a parameter, and the class must implement a +render+ method that
- # takes the contents of the template to render as well as the Hash of
- # local assigns available to the template. The +render+ method ought to
- # return the rendered template as a string.
- def register_template_handler(extension, klass)
- @@template_handlers[extension.to_sym] = klass
- end
-
- def template_handler_extensions
- @@template_handlers.keys.map {|key| key.to_s }.sort
- end
-
- def registered_template_handler(extension)
- extension && @@template_handlers[extension.to_sym]
- end
-
- def register_default_template_handler(extension, klass)
- register_template_handler(extension, klass)
- @@default_template_handlers = klass
- end
-
- def handler_class_for_extension(extension)
- (extension && registered_template_handler(extension.to_sym)) || @@default_template_handlers
+ def self.extensions
+ @@template_handlers.keys
+ end
+
+ # Register a class that knows how to handle template files with the given
+ # extension. This can be used to implement new template types.
+ # The constructor for the class must take the ActiveView::Base instance
+ # as a parameter, and the class must implement a +render+ method that
+ # takes the contents of the template to render as well as the Hash of
+ # local assigns available to the template. The +render+ method ought to
+ # return the rendered template as a string.
+ def register_template_handler(extension, klass)
+ @@template_handlers[extension.to_sym] = klass
+ end
+
+ def template_handler_extensions
+ @@template_handlers.keys.map {|key| key.to_s }.sort
+ end
+
+ def registered_template_handler(extension)
+ extension && @@template_handlers[extension.to_sym]
+ end
+
+ def register_default_template_handler(extension, klass)
+ register_template_handler(extension, klass)
+ @@default_template_handlers = klass
+ end
+
+ def handler_class_for_extension(extension)
+ (extension && registered_template_handler(extension.to_sym)) || @@default_template_handlers
+ end
end
end
end
diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb
index 5f381f7bf0..a93cfca8aa 100644
--- a/actionpack/lib/action_view/template/handlers/builder.rb
+++ b/actionpack/lib/action_view/template/handlers/builder.rb
@@ -1,6 +1,6 @@
module ActionView
- module TemplateHandlers
- class Builder < TemplateHandler
+ module Template::Handlers
+ class Builder < Template::Handler
include Compilable
self.default_format = Mime::XML
diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb
index 88aeb4b053..93a4315108 100644
--- a/actionpack/lib/action_view/template/handlers/erb.rb
+++ b/actionpack/lib/action_view/template/handlers/erb.rb
@@ -3,14 +3,15 @@ require 'active_support/core_ext/string/output_safety'
require 'erubis'
module ActionView
- module TemplateHandlers
+ module Template::Handlers
class Erubis < ::Erubis::Eruby
def add_preamble(src)
src << "@output_buffer = ActionView::SafeBuffer.new;"
end
def add_text(src, text)
- src << "@output_buffer << ('" << escape_text(text) << "'.html_safe!);"
+ return if text.empty?
+ src << "@output_buffer.safe_concat('" << escape_text(text) << "');"
end
def add_expr_literal(src, code)
@@ -26,7 +27,7 @@ module ActionView
end
end
- class ERB < TemplateHandler
+ class ERB < Template::Handler
include Compilable
##
diff --git a/actionpack/lib/action_view/template/handlers/rjs.rb b/actionpack/lib/action_view/template/handlers/rjs.rb
index b1d15dc209..63e7dc0902 100644
--- a/actionpack/lib/action_view/template/handlers/rjs.rb
+++ b/actionpack/lib/action_view/template/handlers/rjs.rb
@@ -1,6 +1,6 @@
module ActionView
- module TemplateHandlers
- class RJS < TemplateHandler
+ module Template::Handlers
+ class RJS < Template::Handler
include Compilable
self.default_format = Mime::JS
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
index 7336114e1b..c6a17907ff 100644
--- a/actionpack/lib/action_view/template/resolver.rb
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -1,6 +1,6 @@
require "pathname"
require "active_support/core_ext/class"
-require "action_view/template/template"
+require "action_view/template"
module ActionView
# Abstract superclass
@@ -20,7 +20,7 @@ module ActionView
register_detail(:locale) { [I18n.locale] }
register_detail(:formats) { Mime::SET.symbols }
register_detail(:handlers, :allow_nil => false) do
- TemplateHandlers.extensions
+ Template::Handlers.extensions
end
def initialize(options = {})
@@ -65,7 +65,7 @@ module ActionView
# as well as incorrectly putting part of the path in the template
# name instead of the prefix.
def normalize_name(name, prefix)
- handlers = TemplateHandlers.extensions.join('|')
+ handlers = Template::Handlers.extensions.join('|')
name = name.to_s.gsub(/\.(?:#{handlers})$/, '')
parts = name.split('/')
@@ -108,13 +108,9 @@ module ActionView
query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << '}'
end
- Dir[query].map do |path|
- next if File.directory?(path)
- source = File.read(path)
- identifier = Pathname.new(path).expand_path.to_s
-
- Template.new(source, identifier, *path_to_details(path))
- end.compact
+ Dir[query].reject { |p| File.directory?(p) }.map do |p|
+ Template.new(File.read(p), File.expand_path(p), *path_to_details(p))
+ end
end
# # TODO: fix me
@@ -162,4 +158,4 @@ module ActionView
@paths.first.to_s
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/template/text.rb b/actionpack/lib/action_view/template/text.rb
index f6e011a5ab..67e086d8bd 100644
--- a/actionpack/lib/action_view/template/text.rb
+++ b/actionpack/lib/action_view/template/text.rb
@@ -1,38 +1,40 @@
module ActionView #:nodoc:
- class TextTemplate < String #:nodoc:
- HTML = Mime[:html]
-
- def initialize(string, content_type = HTML)
- super(string.to_s)
- @content_type = Mime[content_type] || content_type
- end
-
- def details
- {:formats => [@content_type.to_sym]}
- end
-
- def identifier
- self
- end
-
- def inspect
- 'text template'
- end
-
- def render(*args)
- to_s
- end
-
- def mime_type
- @content_type
- end
-
- def formats
- [mime_type]
- end
-
- def partial?
- false
+ class Template
+ class Text < String #:nodoc:
+ HTML = Mime[:html]
+
+ def initialize(string, content_type = HTML)
+ super(string.to_s)
+ @content_type = Mime[content_type] || content_type
+ end
+
+ def details
+ {:formats => [@content_type.to_sym]}
+ end
+
+ def identifier
+ self
+ end
+
+ def inspect
+ 'text template'
+ end
+
+ def render(*args)
+ to_s
+ end
+
+ def mime_type
+ @content_type
+ end
+
+ def formats
+ [mime_type]
+ 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 86bbad822d..be9a2ed50d 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -1,5 +1,5 @@
require 'active_support/test_case'
-require 'action_controller/testing/test_case'
+require 'action_controller/test_case'
module ActionView
class Base
@@ -39,8 +39,7 @@ module ActionView
end
end
- include ActionDispatch::Assertions
- include ActionController::TestProcess
+ include ActionDispatch::Assertions, ActionDispatch::TestProcess
include ActionView::Context
include ActionController::PolymorphicRoutes
diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb
index 524381509d..4ad87d9762 100644
--- a/actionpack/test/abstract/abstract_controller_test.rb
+++ b/actionpack/test/abstract/abstract_controller_test.rb
@@ -28,7 +28,7 @@ module AbstractController
# Test Render mixin
# ====
class RenderingController < AbstractController::Base
- include ::AbstractController::RenderingController
+ include ::AbstractController::Rendering
def _prefix() end
diff --git a/actionpack/test/abstract/helper_test.rb b/actionpack/test/abstract/helper_test.rb
index efcd68e5c8..ade29140ba 100644
--- a/actionpack/test/abstract/helper_test.rb
+++ b/actionpack/test/abstract/helper_test.rb
@@ -6,7 +6,7 @@ module AbstractController
module Testing
class ControllerWithHelpers < AbstractController::Base
- include AbstractController::RenderingController
+ include AbstractController::Rendering
include Helpers
def with_module
diff --git a/actionpack/test/abstract/layouts_test.rb b/actionpack/test/abstract/layouts_test.rb
index ae2f1bf1f2..df73d948f0 100644
--- a/actionpack/test/abstract/layouts_test.rb
+++ b/actionpack/test/abstract/layouts_test.rb
@@ -6,7 +6,7 @@ module AbstractControllerTests
# Base controller for these tests
class Base < AbstractController::Base
- include AbstractController::RenderingController
+ include AbstractController::Rendering
include AbstractController::Layouts
self.view_paths = [ActionView::FixtureResolver.new(
@@ -23,7 +23,7 @@ module AbstractControllerTests
self.view_paths = []
def index
- render :_template => ActionView::TextTemplate.new("Hello blank!")
+ render :_template => ActionView::Template::Text.new("Hello blank!")
end
end
@@ -31,19 +31,19 @@ module AbstractControllerTests
layout "hello"
def index
- render :_template => ActionView::TextTemplate.new("Hello string!")
+ render :_template => ActionView::Template::Text.new("Hello string!")
end
def overwrite_default
- render :_template => ActionView::TextTemplate.new("Hello string!"), :layout => :default
+ render :_template => ActionView::Template::Text.new("Hello string!"), :layout => :default
end
def overwrite_false
- render :_template => ActionView::TextTemplate.new("Hello string!"), :layout => false
+ render :_template => ActionView::Template::Text.new("Hello string!"), :layout => false
end
def overwrite_string
- render :_template => ActionView::TextTemplate.new("Hello string!"), :layout => "omg"
+ render :_template => ActionView::Template::Text.new("Hello string!"), :layout => "omg"
end
def overwrite_skip
@@ -72,7 +72,7 @@ module AbstractControllerTests
layout :hello
def index
- render :_template => ActionView::TextTemplate.new("Hello symbol!")
+ render :_template => ActionView::Template::Text.new("Hello symbol!")
end
private
def hello
@@ -84,7 +84,7 @@ module AbstractControllerTests
layout :no_hello
def index
- render :_template => ActionView::TextTemplate.new("Hello missing symbol!")
+ render :_template => ActionView::Template::Text.new("Hello missing symbol!")
end
private
def no_hello
@@ -96,7 +96,7 @@ module AbstractControllerTests
layout :nilz
def index
- render :_template => ActionView::TextTemplate.new("Hello nilz!")
+ render :_template => ActionView::Template::Text.new("Hello nilz!")
end
def nilz() end
@@ -106,7 +106,7 @@ module AbstractControllerTests
layout :objekt
def index
- render :_template => ActionView::TextTemplate.new("Hello nilz!")
+ render :_template => ActionView::Template::Text.new("Hello nilz!")
end
def objekt
@@ -118,7 +118,7 @@ module AbstractControllerTests
layout :omg_no_method
def index
- render :_template => ActionView::TextTemplate.new("Hello boom!")
+ render :_template => ActionView::Template::Text.new("Hello boom!")
end
end
@@ -126,7 +126,7 @@ module AbstractControllerTests
layout "missing"
def index
- render :_template => ActionView::TextTemplate.new("Hello missing!")
+ render :_template => ActionView::Template::Text.new("Hello missing!")
end
end
@@ -134,7 +134,7 @@ module AbstractControllerTests
layout false
def index
- render :_template => ActionView::TextTemplate.new("Hello false!")
+ render :_template => ActionView::Template::Text.new("Hello false!")
end
end
@@ -142,7 +142,7 @@ module AbstractControllerTests
layout nil
def index
- render :_template => ActionView::TextTemplate.new("Hello nil!")
+ render :_template => ActionView::Template::Text.new("Hello nil!")
end
end
diff --git a/actionpack/test/abstract/localized_cache_test.rb b/actionpack/test/abstract/localized_cache_test.rb
index 6f9bb693f7..8b0b0fff03 100644
--- a/actionpack/test/abstract/localized_cache_test.rb
+++ b/actionpack/test/abstract/localized_cache_test.rb
@@ -4,7 +4,7 @@ module AbstractController
module Testing
class CachedController < AbstractController::Base
- include AbstractController::RenderingController
+ include AbstractController::Rendering
include AbstractController::LocalizedCache
self.view_paths = [ActionView::FixtureResolver.new(
diff --git a/actionpack/test/abstract/render_test.rb b/actionpack/test/abstract/render_test.rb
index 45a4763fe4..be0478b638 100644
--- a/actionpack/test/abstract/render_test.rb
+++ b/actionpack/test/abstract/render_test.rb
@@ -4,7 +4,7 @@ module AbstractController
module Testing
class ControllerRenderer < AbstractController::Base
- include AbstractController::RenderingController
+ include AbstractController::Rendering
self.view_paths = [ActionView::FixtureResolver.new(
"default.erb" => "With Default",
@@ -38,7 +38,7 @@ module AbstractController
end
def object
- render :_template => ActionView::TextTemplate.new("With Object")
+ render :_template => ActionView::Template::Text.new("With Object")
end
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 775cfc82bf..8c65087898 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -1,12 +1,9 @@
-root = File.expand_path('../../..', __FILE__)
begin
- require "#{root}/vendor/gems/environment"
+ require File.expand_path('../../../vendor/gems/environment', __FILE__)
rescue LoadError
- $:.unshift "#{root}/activesupport/lib"
- $:.unshift "#{root}/activemodel/lib"
end
-lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
+lib = File.expand_path('../../lib', __FILE__)
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
$:.unshift(File.dirname(__FILE__) + '/lib')
@@ -16,18 +13,20 @@ $:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers')
ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp')
require 'test/unit'
-require 'active_support'
-require 'active_support/test_case'
require 'abstract_controller'
require 'action_controller'
require 'action_view'
require 'action_view/base'
require 'action_dispatch'
-require 'active_model'
require 'fixture_template'
+require 'active_support/test_case'
require 'action_view/test_case'
require 'active_support/dependencies'
+activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
+$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
+require 'active_model'
+
begin
require 'ruby-debug'
Debugger.settings[:autoeval] = true
@@ -51,6 +50,14 @@ ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
FIXTURES = Pathname.new(FIXTURE_LOAD_PATH)
+# Turn on notifications
+require 'active_support/notifications'
+Thread.abort_on_exception = true
+
+ActiveSupport::Notifications.subscribe do |*args|
+ ActionController::Base.log_event(*args) if ActionController::Base.logger
+end
+
module SetupOnce
extend ActiveSupport::Concern
@@ -83,11 +90,26 @@ class ActiveSupport::TestCase
# have been loaded.
setup_once do
ActionController::Routing::Routes.draw do |map|
- map.connect ':controller/:action/:id'
+ match ':controller(/:action(/:id))'
end
end
end
+class MockLogger
+ attr_reader :logged
+ attr_accessor :level
+
+ def initialize
+ @level = Logger::DEBUG
+ @logged = []
+ end
+
+ def method_missing(method, *args, &blk)
+ @logged << args.first
+ @logged << blk.call if block_given?
+ end
+end
+
class ActionController::IntegrationTest < ActiveSupport::TestCase
def self.build_app(routes = nil)
ActionDispatch::MiddlewareStack.new { |middleware|
@@ -191,26 +213,14 @@ class ::ApplicationController < ActionController::Base
end
module ActionController
- module Routing
- def self.possible_controllers
- @@possible_controllers ||= []
- end
- end
-
class Base
include ActionController::Testing
-
- def self.inherited(klass)
- name = klass.name.underscore.sub(/_controller$/, '')
- ActionController::Routing.possible_controllers << name unless name.blank?
- super
- end
end
Base.view_paths = FIXTURE_LOAD_PATH
class TestCase
- include TestProcess
+ include ActionDispatch::TestProcess
def assert_template(options = {}, message = nil)
validate_request!
diff --git a/actionpack/test/active_record_unit.rb b/actionpack/test/active_record_unit.rb
index 9e0c66055d..9a094cf66b 100644
--- a/actionpack/test/active_record_unit.rb
+++ b/actionpack/test/active_record_unit.rb
@@ -11,19 +11,15 @@ class ActiveRecordTestConnector
end
# Try to grab AR
-if defined?(ActiveRecord) && defined?(Fixtures)
- $stderr.puts 'Active Record is already loaded, running tests'
-else
- $stderr.print 'Attempting to load Active Record... '
+unless defined?(ActiveRecord) && defined?(Fixtures)
begin
PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib"
raise LoadError, "#{PATH_TO_AR} doesn't exist" unless File.directory?(PATH_TO_AR)
$LOAD_PATH.unshift PATH_TO_AR
require 'active_record'
require 'active_record/fixtures'
- $stderr.puts 'success'
rescue LoadError => e
- $stderr.print "failed. Skipping Active Record assertion tests: #{e}"
+ $stderr.print "Failed to load Active Record. Skipping Active Record assertion tests: #{e}"
ActiveRecordTestConnector.able_to_connect = false
end
end
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index c6c079f88c..61bee1b66c 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -155,7 +155,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
def with_test_route_set(options = {})
with_routing do |set|
set.draw do |map|
- map.connect "/:action", :controller => "active_record_store_test/test"
+ match ':action', :to => 'active_record_store_test/test'
end
@app = ActiveRecord::SessionStore.new(set, options.reverse_merge(:key => '_session_id'))
yield
diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb
new file mode 100644
index 0000000000..0f534da14b
--- /dev/null
+++ b/actionpack/test/activerecord/controller_runtime_test.rb
@@ -0,0 +1,39 @@
+require 'active_record_unit'
+require 'active_record/railties/controller_runtime'
+require 'fixtures/project'
+
+ActionController::Base.send :include, ActiveRecord::Railties::ControllerRuntime
+
+class ARLoggingController < ActionController::Base
+ def show
+ render :inline => "<%= Project.all %>"
+ end
+end
+
+class ARLoggingTest < ActionController::TestCase
+ tests ARLoggingController
+
+ def setup
+ super
+ set_logger
+ end
+
+ def wait
+ ActiveSupport::Notifications.notifier.wait
+ end
+
+ def test_log_with_active_record
+ get :show
+ wait
+ assert_match /ActiveRecord runtime/, logs[3]
+ end
+
+ private
+ def set_logger
+ @controller.logger = MockLogger.new
+ end
+
+ def logs
+ @logs ||= @controller.logger.logged.compact.map {|l| l.to_s.strip}
+ end
+end
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 901cb940ea..d54be9bdc0 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -221,8 +221,8 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_assert_redirect_to_named_route
with_routing do |set|
set.draw do |map|
- map.route_one 'route_one', :controller => 'action_pack_assertions', :action => 'nothing'
- map.connect ':controller/:action/:id'
+ match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one
+ match ':controller/:action'
end
set.install_helpers
@@ -235,9 +235,9 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_assert_redirect_to_named_route_failure
with_routing do |set|
set.draw do |map|
- map.route_one 'route_one', :controller => 'action_pack_assertions', :action => 'nothing', :id => 'one'
- map.route_two 'route_two', :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two'
- map.connect ':controller/:action/:id'
+ 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'
end
process :redirect_to_named_route
assert_raise(ActiveSupport::TestCase::Assertion) do
@@ -255,8 +255,8 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_assert_redirect_to_nested_named_route
with_routing do |set|
set.draw do |map|
- map.admin_inner_module 'admin/inner_module', :controller => 'admin/inner_module', :action => 'index'
- map.connect ':controller/:action/:id'
+ match 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module
+ match ':controller/:action'
end
@controller = Admin::InnerModuleController.new
process :redirect_to_index
@@ -268,8 +268,8 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_assert_redirected_to_top_level_named_route_from_nested_controller
with_routing do |set|
set.draw do |map|
- map.top_level '/action_pack_assertions/:id', :controller => 'action_pack_assertions', :action => 'index'
- map.connect ':controller/:action/:id'
+ match '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level
+ match ':controller/:action'
end
@controller = Admin::InnerModuleController.new
process :redirect_to_top_level_named_route
@@ -282,8 +282,8 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
with_routing do |set|
set.draw do |map|
# this controller exists in the admin namespace as well which is the only difference from previous test
- map.top_level '/user/:id', :controller => 'user', :action => 'index'
- map.connect ':controller/:action/:id'
+ match '/user/:id', :to => 'user#index', :as => :top_level
+ match ':controller/:action'
end
@controller = Admin::InnerModuleController.new
process :redirect_to_top_level_named_route
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index b57550a69a..65118f9bc9 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -158,13 +158,6 @@ class PerformActionTest < ActionController::TestCase
assert_raise(ActionController::UnknownAction) { get :hidden_action }
assert_raise(ActionController::UnknownAction) { get :another_hidden_action }
end
-
- def test_namespaced_action_should_log_module_name
- use_controller Submodule::ContainedNonEmptyController
- @controller.logger = MockLogger.new
- get :public_action
- assert_match /Processing\sSubmodule::ContainedNonEmptyController#public_action/, @controller.logger.logged[1]
- end
end
class DefaultUrlOptionsTest < ActionController::TestCase
@@ -179,8 +172,8 @@ class DefaultUrlOptionsTest < ActionController::TestCase
def test_default_url_options_are_used_if_set
with_routing do |set|
set.draw do |map|
- map.default_url_options 'default_url_options', :controller => 'default_url_options'
- map.connect ':controller/:action/:id'
+ match 'default_url_options', :to => 'default_url_options#default_url_options_action', :as => :default_url_options
+ match ':controller/:action'
end
get :default_url_options_action # Make a dummy request so that the controller is initialized properly.
@@ -210,7 +203,7 @@ class EnsureNamedRoutesWorksTicket22BugTest < ActionController::TestCase
def test_named_routes_still_work
with_routing do |set|
set.draw do |map|
- map.resources :things
+ resources :things
end
EmptyController.send :include, ActionController::UrlWriter
diff --git a/actionpack/test/controller/benchmark_test.rb b/actionpack/test/controller/benchmark_test.rb
deleted file mode 100644
index 66ebfcf20a..0000000000
--- a/actionpack/test/controller/benchmark_test.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-require 'abstract_unit'
-
-# Provide some static controllers.
-class BenchmarkedController < ActionController::Base
- def public_action
- render :nothing => true
- end
-
- def rescue_action(e)
- raise e
- end
-end
-
-class BenchmarkTest < ActionController::TestCase
- tests BenchmarkedController
-
- class MockLogger
- def method_missing(*args)
- end
- end
-
- def setup
- super
- # benchmark doesn't do anything unless a logger is set
- @controller.logger = MockLogger.new
- @request.host = "test.actioncontroller.i"
- end
-
- def test_with_http_1_0_request
- @request.host = nil
- assert_nothing_raised { get :public_action }
- end
-end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index 3ce90b6ccf..679eaf7b38 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -70,8 +70,8 @@ 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|
- map.main '', :controller => 'posts', :format => nil
- map.formatted_posts 'posts.:format', :controller => 'posts'
+ match 'posts.:format', :to => 'posts#index', :as => :formatted_posts
+ match '/', :to => 'posts#index', :as => :main
end
@params[:format] = 'rss'
assert_equal '/posts.rss', @rewriter.rewrite(@params)
@@ -422,8 +422,7 @@ class ActionCacheTest < ActionController::TestCase
def test_xml_version_of_resource_is_treated_as_different_cache
with_routing do |set|
set.draw do |map|
- map.connect ':controller/:action.:format'
- map.connect ':controller/:action'
+ match ':controller(/:action(.:format))'
end
get :index, :format => 'xml'
@@ -632,13 +631,16 @@ class FragmentCachingTest < ActionController::TestCase
def test_fragment_for_logging
fragment_computed = false
- ActiveSupport::Notifications.queue.expects(:publish).times(2)
+ events = []
+ ActiveSupport::Notifications.subscribe { |*args| events << args }
buffer = 'generated till now -> '
@controller.fragment_for(buffer, 'expensive') { fragment_computed = true }
assert fragment_computed
assert_equal 'generated till now -> ', buffer
+ ActiveSupport::Notifications.notifier.wait
+ assert_equal [:exist_fragment?, :write_fragment], events.map(&:first)
end
end
diff --git a/actionpack/test/controller/cookie_test.rb b/actionpack/test/controller/cookie_test.rb
index 53d4364576..c8e8b3857e 100644
--- a/actionpack/test/controller/cookie_test.rb
+++ b/actionpack/test/controller/cookie_test.rb
@@ -1,5 +1,7 @@
require 'abstract_unit'
+ActionController::Base.cookie_verifier_secret = "thisISverySECRET123"
+
class CookieTest < ActionController::TestCase
class TestController < ActionController::Base
def authenticate
@@ -47,6 +49,21 @@ class CookieTest < ActionController::TestCase
cookies["user_name"] = { :value => "david", :httponly => true }
head :ok
end
+
+ def set_permanent_cookie
+ cookies.permanent[:user_name] = "Jamie"
+ head :ok
+ end
+
+ def set_signed_cookie
+ cookies.signed[:user_id] = 45
+ head :ok
+ end
+
+ def set_permanent_signed_cookie
+ cookies.permanent.signed[:remember_me] = 100
+ head :ok
+ end
end
tests TestController
@@ -134,6 +151,24 @@ class CookieTest < ActionController::TestCase
response = get :authenticate
assert response.headers["Set-Cookie"] =~ /user_name=david/
end
+
+ 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"]
+ end
+
+ def test_signed_cookie
+ get :set_signed_cookie
+ assert_equal 45, @controller.send(:cookies).signed[:user_id]
+ end
+
+ def test_permanent_signed_cookie
+ get :set_permanent_signed_cookie
+ assert_match %r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"]
+ assert_equal 100, @controller.send(:cookies).signed[:remember_me]
+ end
+
private
def assert_cookie_header(expected)
diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb
index 622d67287d..64f1ad7610 100644
--- a/actionpack/test/controller/dispatcher_test.rb
+++ b/actionpack/test/controller/dispatcher_test.rb
@@ -15,7 +15,6 @@ class DispatcherTest < Test::Unit::TestCase
ActionDispatch::Callbacks.reset_callbacks(:call)
ActionController::Routing::Routes.stubs(:call).returns([200, {}, 'response'])
- ActionController::Routing::Routes.stubs(:reload)
Dispatcher.stubs(:require_dependency)
end
@@ -28,18 +27,6 @@ class DispatcherTest < Test::Unit::TestCase
dispatch(false)
end
- def test_reloads_routes_before_dispatch_if_in_loading_mode
- ActionController::Routing::Routes.expects(:reload).once
- dispatch(false)
- end
-
- def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode
- ActionController::Routing::Routes.expects(:reload).never
- ActiveSupport::Dependencies.expects(:clear).never
-
- dispatch
- end
-
def test_prepare_callbacks
a = b = c = nil
ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 }
diff --git a/actionpack/test/controller/filter_params_test.rb b/actionpack/test/controller/filter_params_test.rb
index 43bef34885..420ebeacf4 100644
--- a/actionpack/test/controller/filter_params_test.rb
+++ b/actionpack/test/controller/filter_params_test.rb
@@ -70,9 +70,9 @@ class FilterParamTest < ActionController::TestCase
FilterParamController.filter_parameter_logging(:lifo, :amount)
get :payment, :lifo => 'Pratik', :amount => '420', :step => '1'
+ ActiveSupport::Notifications.notifier.wait
filtered_params_logs = logs.detect {|l| l =~ /\AParameters/ }
-
assert filtered_params_logs.index('"amount"=>"[FILTERED]"')
assert filtered_params_logs.index('"lifo"=>"[FILTERED]"')
assert filtered_params_logs.index('"step"=>"1"')
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index c448f36cb3..a9b60386f1 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -34,7 +34,7 @@ class FlashTest < ActionController::TestCase
flash.keep
render :inline => "hello"
end
-
+
def use_flash_and_update_it
flash.update("this" => "hello again")
@flash_copy = {}.update flash
@@ -72,6 +72,18 @@ class FlashTest < ActionController::TestCase
redirect_to :action => "std_action"
@flash_copy = {}.update(flash)
end
+
+ def redirect_with_alert
+ redirect_to '/nowhere', :alert => "Beware the nowheres!"
+ end
+
+ def redirect_with_notice
+ redirect_to '/somewhere', :notice => "Good luck in the somewheres!"
+ end
+
+ def redirect_with_other_flashes
+ redirect_to '/wonderland', :flash => { :joyride => "Horses!" }
+ end
end
tests TestController
@@ -89,7 +101,7 @@ class FlashTest < ActionController::TestCase
def test_keep_flash
get :set_flash
-
+
get :use_flash_and_keep_it
assert_equal "hello", assigns["flash_copy"]["that"]
assert_equal "hello", assigns["flashy"]
@@ -100,7 +112,7 @@ class FlashTest < ActionController::TestCase
get :use_flash
assert_nil assigns["flash_copy"]["that"], "On third flash"
end
-
+
def test_flash_now
get :set_flash_now
assert_equal "hello", assigns["flash_copy"]["that"]
@@ -111,8 +123,8 @@ class FlashTest < ActionController::TestCase
assert_nil assigns["flash_copy"]["that"]
assert_nil assigns["flash_copy"]["foo"]
assert_nil assigns["flashy"]
- end
-
+ end
+
def test_update_flash
get :set_flash
get :use_flash_and_update_it
@@ -128,7 +140,7 @@ class FlashTest < ActionController::TestCase
assert_equal "hello", assigns["flashy_that"]
assert_equal "good-bye", assigns["flashy_this"]
assert_nil assigns["flashy_that_reset"]
- end
+ end
def test_does_not_set_the_session_if_the_flash_is_empty
get :std_action
@@ -153,11 +165,26 @@ class FlashTest < ActionController::TestCase
assert_equal(:foo_indeed, flash.discard(:foo)) # valid key passed
assert_nil flash.discard(:unknown) # non existant key passed
assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard()) # nothing passed
- assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard(nil)) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard(nil)) # nothing passed
assert_equal(:foo_indeed, flash.keep(:foo)) # valid key passed
assert_nil flash.keep(:unknown) # non existant key passed
assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep()) # nothing passed
- assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep(nil)) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep(nil)) # nothing passed
+ end
+
+ def test_redirect_to_with_alert
+ get :redirect_with_alert
+ assert_equal "Beware the nowheres!", @controller.send(:flash)[:alert]
+ end
+
+ def test_redirect_to_with_notice
+ get :redirect_with_notice
+ assert_equal "Good luck in the somewheres!", @controller.send(:flash)[:notice]
+ end
+
+ def test_redirect_to_with_other_flashes
+ get :redirect_with_other_flashes
+ assert_equal "Horses!", @controller.send(:flash)[:joyride]
end
-end
+end \ No newline at end of file
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index b9be163904..9030e562bb 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -191,7 +191,7 @@ class IsolatedHelpersTest < Test::Unit::TestCase
end
def test_helper_in_a
- assert_raise(ActionView::TemplateError) { call_controller(A, "index") }
+ assert_raise(ActionView::Template::Error) { call_controller(A, "index") }
end
def test_helper_in_b
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index feb2f81cc1..f635253156 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -115,7 +115,7 @@ class RendersNoLayoutController < LayoutTest
end
class LayoutSetInResponseTest < ActionController::TestCase
- include ActionView::TemplateHandlers
+ include ActionView::Template::Handlers
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
diff --git a/actionpack/test/controller/logging_test.rb b/actionpack/test/controller/logging_test.rb
index 2b5e8d8bde..4206dffa7e 100644
--- a/actionpack/test/controller/logging_test.rb
+++ b/actionpack/test/controller/logging_test.rb
@@ -1,48 +1,74 @@
require 'abstract_unit'
-class LoggingController < ActionController::Base
- def show
- render :nothing => true
- end
-end
-
-class LoggingTest < ActionController::TestCase
- tests LoggingController
-
- class MockLogger
- attr_reader :logged
- attr_accessor :level
+module Another
+ class LoggingController < ActionController::Base
+ layout "layouts/standard"
- def initialize
- @level = Logger::DEBUG
+ def show
+ render :nothing => true
end
- def method_missing(method, *args, &blk)
- @logged ||= []
- @logged << args.first
- @logged << blk.call if block_given?
+ def with_layout
+ render :template => "test/hello_world", :layout => true
end
end
+end
+
+class LoggingTest < ActionController::TestCase
+ tests Another::LoggingController
def setup
super
set_logger
end
+ def get(*args)
+ super
+ wait
+ end
+
+ def wait
+ ActiveSupport::Notifications.notifier.wait
+ end
+
def test_logging_without_parameters
get :show
- assert_equal 3, logs.size
+ assert_equal 4, logs.size
assert_nil logs.detect {|l| l =~ /Parameters/ }
end
def test_logging_with_parameters
get :show, :id => '10'
- assert_equal 4, logs.size
+ assert_equal 5, logs.size
params = logs.detect {|l| l =~ /Parameters/ }
assert_equal 'Parameters: {"id"=>"10"}', params
end
+ def test_log_controller_with_namespace_and_action
+ get :show
+ assert_match /Processed\sAnother::LoggingController#show/, logs[1]
+ end
+
+ def test_log_view_runtime
+ get :show
+ assert_match /View runtime/, logs[2]
+ end
+
+ def test_log_completed_status_and_request_uri
+ get :show
+ last = logs.last
+ assert_match /Completed/, last
+ assert_match /200/, last
+ assert_match /another\/logging\/show/, last
+ end
+
+ def test_logger_prints_layout_and_template_rendering_info
+ get :with_layout
+ logged = logs.find {|l| l =~ /render/i }
+ assert_match /Rendered (.*)test\/hello_world.erb within (.*)layouts\/standard.html.erb/, logged
+ end
+
private
def set_logger
@controller.logger = MockLogger.new
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index fee9cf46f9..6b9cace9cd 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -507,6 +507,13 @@ class RespondWithController < ActionController::Base
end
end
+ def using_responder_with_respond
+ responder = Class.new(ActionController::Responder) do
+ def respond; @controller.render :text => "respond #{format}"; end
+ end
+ respond_with(Customer.new("david", 13), :responder => responder)
+ end
+
protected
def _render_js(js, options)
@@ -592,14 +599,18 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
- def test_using_resource_for_post_with_html
+ def test_using_resource_for_post_with_html_redirects_on_success
with_test_route_set do
post :using_resource
assert_equal "text/html", @response.content_type
assert_equal 302, @response.status
assert_equal "http://www.example.com/customers/13", @response.location
assert @response.redirect?
+ end
+ end
+ def test_using_resource_for_post_with_html_rerender_on_failure
+ with_test_route_set do
errors = { :name => :invalid }
Customer.any_instance.stubs(:errors).returns(errors)
post :using_resource
@@ -610,16 +621,20 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
- def test_using_resource_for_post_with_xml
+ def test_using_resource_for_post_with_xml_yields_created_on_success
with_test_route_set do
@request.accept = "application/xml"
-
post :using_resource
assert_equal "application/xml", @response.content_type
assert_equal 201, @response.status
assert_equal "<name>david</name>", @response.body
assert_equal "http://www.example.com/customers/13", @response.location
+ end
+ end
+ def test_using_resource_for_post_with_xml_yields_unprocessable_entity_on_failure
+ with_test_route_set do
+ @request.accept = "application/xml"
errors = { :name => :invalid }
Customer.any_instance.stubs(:errors).returns(errors)
post :using_resource
@@ -630,14 +645,18 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
- def test_using_resource_for_put_with_html
+ def test_using_resource_for_put_with_html_redirects_on_success
with_test_route_set do
put :using_resource
assert_equal "text/html", @response.content_type
assert_equal 302, @response.status
assert_equal "http://www.example.com/customers/13", @response.location
assert @response.redirect?
+ end
+ end
+ def test_using_resource_for_put_with_html_rerender_on_failure
+ with_test_route_set do
errors = { :name => :invalid }
Customer.any_instance.stubs(:errors).returns(errors)
put :using_resource
@@ -648,14 +667,16 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
- def test_using_resource_for_put_with_xml
+ def test_using_resource_for_put_with_xml_yields_ok_on_success
@request.accept = "application/xml"
-
put :using_resource
assert_equal "application/xml", @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 }
Customer.any_instance.stubs(:errors).returns(errors)
put :using_resource
@@ -665,7 +686,7 @@ class RespondWithControllerTest < ActionController::TestCase
assert_nil @response.location
end
- def test_using_resource_for_delete_with_html
+ def test_using_resource_for_delete_with_html_redirects_on_success
with_test_route_set do
Customer.any_instance.stubs(:destroyed?).returns(true)
delete :using_resource
@@ -675,7 +696,7 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
- def test_using_resource_for_delete_with_xml
+ def test_using_resource_for_delete_with_xml_yields_ok_on_success
Customer.any_instance.stubs(:destroyed?).returns(true)
@request.accept = "application/xml"
delete :using_resource
@@ -684,6 +705,18 @@ class RespondWithControllerTest < ActionController::TestCase
assert_equal " ", @response.body
end
+ def test_using_resource_for_delete_with_html_redirects_on_failure
+ with_test_route_set do
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ Customer.any_instance.stubs(:destroyed?).returns(false)
+ delete :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 302, @response.status
+ assert_equal "http://www.example.com/customers/13", @response.location
+ end
+ end
+
def test_using_resource_with_parent_for_get
@request.accept = "application/xml"
get :using_resource_with_parent
@@ -735,6 +768,16 @@ class RespondWithControllerTest < ActionController::TestCase
assert_equal "foo - #{[:html].to_s}", @controller.response_body
end
+ def test_respond_as_responder_entry_point
+ @request.accept = "text/html"
+ get :using_responder_with_respond
+ assert_equal "respond html", @response.body
+
+ @request.accept = "application/xml"
+ get :using_responder_with_respond
+ assert_equal "respond xml", @response.body
+ end
+
def test_clear_respond_to
@controller = InheritedRespondWithController.new
@request.accept = "text/html"
@@ -810,9 +853,11 @@ class RespondWithControllerTest < ActionController::TestCase
def with_test_route_set
with_routing do |set|
set.draw do |map|
- map.resources :customers
- map.resources :quiz_stores, :has_many => :customers
- map.connect ":controller/:action/:id"
+ resources :customers
+ resources :quiz_stores do
+ resources :customers
+ end
+ match ":controller/:action"
end
yield
end
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index ea278fd8f0..570ff4a41b 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -233,8 +233,8 @@ class RedirectTest < ActionController::TestCase
def test_redirect_to_record
with_routing do |set|
set.draw do |map|
- map.resources :workshops
- map.connect ':controller/:action/:id'
+ resources :workshops
+ match ':controller/:action'
end
get :redirect_to_existing_record
diff --git a/actionpack/test/controller/render_other_test.rb b/actionpack/test/controller/render_other_test.rb
index 51c3c55545..dfc4f2db8c 100644
--- a/actionpack/test/controller/render_other_test.rb
+++ b/actionpack/test/controller/render_other_test.rb
@@ -2,6 +2,11 @@ require 'abstract_unit'
require 'controller/fake_models'
require 'pathname'
+ActionController.add_renderer :simon do |says, options|
+ self.content_type = Mime::TEXT
+ self.response_body = "Simon says: #{says}"
+end
+
class RenderOtherTest < ActionController::TestCase
class TestController < ActionController::Base
protect_from_forgery
@@ -109,6 +114,10 @@ class RenderOtherTest < ActionController::TestCase
end
end
+ def render_simon_says
+ render :simon => "foo"
+ end
+
private
def default_render
if @alternate_default_render
@@ -240,4 +249,9 @@ class RenderOtherTest < ActionController::TestCase
xhr :get, :render_alternate_default
assert_equal %(Element.replace("foo", "partial html");), @response.body
end
+
+ def test_using_custom_render_option
+ get :render_simon_says
+ assert_equal "Simon says: foo", @response.body
+ end
end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index b32325fa20..2c3dc2a72d 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -10,19 +10,6 @@ module Fun
end
end
-class MockLogger
- attr_reader :logged
-
- def initialize
- @logged = []
- end
-
- def method_missing(method, *args, &blk)
- @logged << args.first
- @logged << blk.call if block_given?
- end
-end
-
class TestController < ActionController::Base
protect_from_forgery
@@ -39,35 +26,35 @@ class TestController < ActionController::Base
render :action => 'hello_world'
end
end
-
+
def conditional_hello_with_public_header
if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true)
render :action => 'hello_world'
end
end
-
+
def conditional_hello_with_public_header_and_expires_at
expires_in 1.minute
if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true)
render :action => 'hello_world'
end
end
-
+
def conditional_hello_with_expires_in
- expires_in 1.minute
+ expires_in 60.1.seconds
render :action => 'hello_world'
end
-
+
def conditional_hello_with_expires_in_with_public
expires_in 1.minute, :public => true
render :action => 'hello_world'
end
-
+
def conditional_hello_with_expires_in_with_public_with_more_keys
expires_in 1.minute, :public => true, 'max-stale' => 5.hours
render :action => 'hello_world'
end
-
+
def conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax
expires_in 1.minute, :public => true, :private => nil, 'max-stale' => 5.hours
render :action => 'hello_world'
@@ -272,7 +259,7 @@ class TestController < ActionController::Base
def builder_layout_test
render :action => "hello", :layout => "layouts/builder"
end
-
+
# :move: test this in ActionView
def builder_partial_test
render :action => "hello_world_container"
@@ -1093,8 +1080,8 @@ class RenderTest < ActionController::TestCase
def test_head_with_location_object
with_routing do |set|
set.draw do |map|
- map.resources :customers
- map.connect ':controller/:action/:id'
+ resources :customers
+ match ':controller/:action'
end
get :head_with_location_object
@@ -1125,7 +1112,7 @@ class RenderTest < ActionController::TestCase
assert !@response.headers.include?('Content-Length')
assert_response :no_content
- ActionDispatch::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code|
+ Rack::Utils::SYMBOL_TO_STATUS_CODE.each do |status, code|
get :head_with_symbolic_status, :status => status.to_s
assert_equal code, @response.response_code
assert_response status
@@ -1133,7 +1120,7 @@ class RenderTest < ActionController::TestCase
end
def test_head_with_integer_status
- ActionDispatch::StatusCodes::STATUS_CODES.each do |code, message|
+ Rack::Utils::HTTP_STATUS_CODES.each do |code, message|
get :head_with_integer_status, :status => code.to_s
assert_equal message, @response.message
end
@@ -1306,22 +1293,22 @@ class ExpiresInRenderTest < ActionController::TestCase
def setup
@request.host = "www.nextangle.com"
end
-
+
def test_expires_in_header
get :conditional_hello_with_expires_in
assert_equal "max-age=60, private", @response.headers["Cache-Control"]
end
-
+
def test_expires_in_header_with_public
get :conditional_hello_with_expires_in_with_public
assert_equal "max-age=60, public", @response.headers["Cache-Control"]
end
-
+
def test_expires_in_header_with_additional_headers
get :conditional_hello_with_expires_in_with_public_with_more_keys
assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"]
end
-
+
def test_expires_in_old_syntax
get :conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax
assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"]
@@ -1425,12 +1412,12 @@ class EtagRenderTest < ActionController::TestCase
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']
@@ -1500,21 +1487,4 @@ class LastModifiedRenderTest < ActionController::TestCase
get :conditional_hello_with_bangs
assert_response :success
end
-end
-
-class RenderingLoggingTest < ActionController::TestCase
- tests TestController
-
- def setup
- super
- @request.host = "www.nextangle.com"
- end
-
- def test_logger_prints_layout_and_template_rendering_info
- @controller.logger = MockLogger.new
- get :layout_test
- logged = @controller.logger.logged.find_all {|l| l =~ /render/i }
- assert logged[0] =~ %r{Rendering.*test/hello_world}
- assert logged[1] =~ %r{Rendering template within.*layouts/standard}
- end
-end
+end \ No newline at end of file
diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb
index 68a52c3e8c..b5b0d0b9d5 100644
--- a/actionpack/test/controller/render_xml_test.rb
+++ b/actionpack/test/controller/render_xml_test.rb
@@ -61,8 +61,8 @@ class RenderXmlTest < ActionController::TestCase
def test_rendering_with_object_location_should_set_header_with_url_for
with_routing do |set|
set.draw do |map|
- map.resources :customers
- map.connect ':controller/:action/:id'
+ resources :customers
+ match ':controller/:action'
end
get :render_with_object_location
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 7111796f8d..09003adf73 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -18,7 +18,7 @@ module RequestForgeryProtectionActions
def unsafe
render :text => 'pwn'
end
-
+
def rescue_action(e) raise e end
end
@@ -40,6 +40,13 @@ class FreeCookieController < RequestForgeryProtectionController
end
end
+class CustomAuthenticityParamController < RequestForgeryProtectionController
+ def form_authenticity_param
+ 'foobar'
+ end
+end
+
+
# common test methods
module RequestForgeryProtectionTests
@@ -241,3 +248,14 @@ class FreeCookieControllerTest < ActionController::TestCase
end
end
end
+
+class CustomAuthenticityParamControllerTest < ActionController::TestCase
+ def setup
+ ActionController::Base.request_forgery_protection_token = :authenticity_token
+ end
+
+ def test_should_allow_custom_token
+ post :index, :authenticity_token => 'foobar'
+ assert_response :ok
+ end
+end
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index 04e9acf855..1a03396ae9 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -403,7 +403,7 @@ class ResourcesTest < ActionController::TestCase
with_restful_routing :messages do
assert_restful_routes_for :messages do |options|
assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get)
- assert_raise(ActionController::MethodNotAllowed) do
+ assert_raise(ActionController::RoutingError) do
ActionController::Routing::Routes.recognize_path("/messages/new", :method => :post)
end
end
@@ -689,11 +689,11 @@ class ResourcesTest < ActionController::TestCase
options = { :controller => controller_name.to_s }
collection_path = "/#{controller_name}"
- assert_raise(ActionController::MethodNotAllowed) do
+ assert_raise(ActionController::RoutingError) do
assert_recognizes(options.merge(:action => 'update'), :path => collection_path, :method => :put)
end
- assert_raise(ActionController::MethodNotAllowed) do
+ assert_raise(ActionController::RoutingError) do
assert_recognizes(options.merge(:action => 'destroy'), :path => collection_path, :method => :delete)
end
end
@@ -1378,7 +1378,7 @@ class ResourcesTest < ActionController::TestCase
end
def assert_not_recognizes(expected_options, path)
- assert_raise ActionController::RoutingError, ActionController::MethodNotAllowed, Assertion do
+ assert_raise ActionController::RoutingError, Assertion do
assert_recognizes(expected_options, path)
end
end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 3971aacadb..c15eaade58 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -51,30 +51,6 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase
end
end
-class RoutingTest < Test::Unit::TestCase
- def test_normalize_unix_paths
- load_paths = %w(. config/../app/controllers config/../app//helpers script/../config/../vendor/rails/actionpack/lib vendor/rails/railties/builtin/rails_info app/models lib script/../config/../foo/bar/../../app/models .foo/../.bar foo.bar/../config)
- paths = ActionController::Routing.normalize_paths(load_paths)
- assert_equal %w(vendor/rails/railties/builtin/rails_info vendor/rails/actionpack/lib app/controllers app/helpers app/models config .bar lib .), paths
- end
-
- def test_normalize_windows_paths
- load_paths = %w(. config\\..\\app\\controllers config\\..\\app\\\\helpers script\\..\\config\\..\\vendor\\rails\\actionpack\\lib vendor\\rails\\railties\\builtin\\rails_info app\\models lib script\\..\\config\\..\\foo\\bar\\..\\..\\app\\models .foo\\..\\.bar foo.bar\\..\\config)
- paths = ActionController::Routing.normalize_paths(load_paths)
- assert_equal %w(vendor\\rails\\railties\\builtin\\rails_info vendor\\rails\\actionpack\\lib app\\controllers app\\helpers app\\models config .bar lib .), paths
- end
-
- def test_routing_helper_module
- assert_kind_of Module, ActionController::Routing::Helpers
-
- h = ActionController::Routing::Helpers
- c = Class.new
- assert ! c.ancestors.include?(h)
- ActionController::Routing::Routes.install_helpers c
- assert c.ancestors.include?(h)
- end
-end
-
class MockController
attr_accessor :routes
@@ -578,10 +554,6 @@ class LegacyRouteSetTests < Test::Unit::TestCase
end
def setup_request_method_routes_for(method)
- @request = ActionController::TestRequest.new
- @request.env["REQUEST_METHOD"] = method
- @request.request_uri = "/match"
-
rs.draw do |r|
r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
@@ -593,8 +565,8 @@ class LegacyRouteSetTests < Test::Unit::TestCase
%w(GET POST PUT DELETE).each do |request_method|
define_method("test_request_method_recognized_with_#{request_method}") do
setup_request_method_routes_for(request_method)
- assert_nothing_raised { rs.recognize(@request) }
- assert_equal request_method.downcase, @request.path_parameters[:action]
+ params = rs.recognize_path("/match", :method => request_method)
+ assert_equal request_method.downcase, params[:action]
end
end
@@ -604,18 +576,11 @@ class LegacyRouteSetTests < Test::Unit::TestCase
r.connect '/match', :controller => 'books', :action => 'not_get_or_post'
end
- @request = ActionController::TestRequest.new
- @request.env["REQUEST_METHOD"] = 'POST'
- @request.request_uri = "/match"
- assert_nothing_raised { rs.recognize(@request) }
- assert_equal 'get_or_post', @request.path_parameters[:action]
+ params = rs.recognize_path("/match", :method => :post)
+ assert_equal 'get_or_post', params[:action]
- # have to recreate or else the RouteSet uses a cached version:
- @request = ActionController::TestRequest.new
- @request.env["REQUEST_METHOD"] = 'PUT'
- @request.request_uri = "/match"
- assert_nothing_raised { rs.recognize(@request) }
- assert_equal 'not_get_or_post', @request.path_parameters[:action]
+ params = rs.recognize_path("/match", :method => :put)
+ assert_equal 'not_get_or_post', params[:action]
end
def test_subpath_recognized
@@ -769,9 +734,7 @@ class RouteSetTest < ActiveSupport::TestCase
set.draw do |map|
map.connect '/users/index', :controller => :users, :action => :index
end
- @request = ActionController::TestRequest.new
- @request.request_uri = '/users/index'
- assert_nothing_raised { set.recognize(@request) }
+ params = set.recognize_path('/users/index', :method => :get)
assert_equal 1, set.routes.size
end
@@ -1004,55 +967,34 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
- request.request_uri = "/people"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("index", request.path_parameters[:action])
- request.recycle!
+ params = set.recognize_path("/people", :method => :get)
+ assert_equal("index", params[:action])
- request.env["REQUEST_METHOD"] = "POST"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("create", request.path_parameters[:action])
- request.recycle!
+ params = set.recognize_path("/people", :method => :post)
+ assert_equal("create", params[:action])
- request.env["REQUEST_METHOD"] = "PUT"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("update", request.path_parameters[:action])
- request.recycle!
+ params = set.recognize_path("/people", :method => :put)
+ assert_equal("update", params[:action])
- assert_raise(ActionController::UnknownHttpMethod) {
- request.env["REQUEST_METHOD"] = "BACON"
- set.recognize(request)
+ assert_raise(ActionController::RoutingError) {
+ set.recognize_path("/people", :method => :bacon)
}
- request.recycle!
- request.request_uri = "/people/5"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("show", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
+ params = set.recognize_path("/people/5", :method => :get)
+ assert_equal("show", params[:action])
+ assert_equal("5", params[:id])
- request.env["REQUEST_METHOD"] = "PUT"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("update", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
+ params = set.recognize_path("/people/5", :method => :put)
+ assert_equal("update", params[:action])
+ assert_equal("5", params[:id])
- request.env["REQUEST_METHOD"] = "DELETE"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("destroy", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
+ params = set.recognize_path("/people/5", :method => :delete)
+ assert_equal("destroy", params[:action])
+ assert_equal("5", params[:id])
- begin
- request.env["REQUEST_METHOD"] = "POST"
- set.recognize(request)
- flunk 'Should have raised MethodNotAllowed'
- rescue ActionController::MethodNotAllowed => e
- assert_equal [:get, :put, :delete], e.allowed_methods
- end
- request.recycle!
+ assert_raise(ActionController::RoutingError) {
+ set.recognize_path("/people/5", :method => :post)
+ }
end
def test_recognize_with_alias_in_conditions
@@ -1062,17 +1004,13 @@ class RouteSetTest < ActiveSupport::TestCase
map.root :people
end
- request.path = "/people"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("people", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
+ params = set.recognize_path("/people", :method => :get)
+ assert_equal("people", params[:controller])
+ assert_equal("index", params[:action])
- request.path = "/"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("people", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
+ params = set.recognize_path("/", :method => :get)
+ assert_equal("people", params[:controller])
+ assert_equal("index", params[:action])
end
def test_typo_recognition
@@ -1082,14 +1020,12 @@ class RouteSetTest < ActiveSupport::TestCase
:year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/
end
- request.path = "/articles/2005/11/05/a-very-interesting-article"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("permalink", request.path_parameters[:action])
- assert_equal("2005", request.path_parameters[:year])
- assert_equal("11", request.path_parameters[:month])
- assert_equal("05", request.path_parameters[:day])
- assert_equal("a-very-interesting-article", request.path_parameters[:title])
+ params = set.recognize_path("/articles/2005/11/05/a-very-interesting-article", :method => :get)
+ assert_equal("permalink", params[:action])
+ assert_equal("2005", params[:year])
+ assert_equal("11", params[:month])
+ assert_equal("05", params[:day])
+ assert_equal("a-very-interesting-article", params[:title])
end
def test_routing_traversal_does_not_load_extra_classes
@@ -1098,9 +1034,7 @@ class RouteSetTest < ActiveSupport::TestCase
map.connect '/profile', :controller => 'profile'
end
- request.path = '/profile'
-
- set.recognize(request) rescue nil
+ params = set.recognize_path("/profile") rescue nil
assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
end
@@ -1114,24 +1048,17 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
- request.request_uri = "/people/5"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("show", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- request.recycle!
+ params = set.recognize_path("/people/5", :method => :get)
+ assert_equal("show", params[:action])
+ assert_equal("5", params[:id])
- request.env["REQUEST_METHOD"] = "PUT"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("update", request.path_parameters[:action])
- request.recycle!
+ params = set.recognize_path("/people/5", :method => :put)
+ assert_equal("update", params[:action])
- request.request_uri = "/people/5.png"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("show", request.path_parameters[:action])
- assert_equal("5", request.path_parameters[:id])
- assert_equal("png", request.path_parameters[:_format])
+ params = set.recognize_path("/people/5.png", :method => :get)
+ assert_equal("show", params[:action])
+ assert_equal("5", params[:id])
+ assert_equal("png", params[:_format])
end
def test_generate_with_default_action
@@ -1147,11 +1074,9 @@ class RouteSetTest < ActiveSupport::TestCase
def test_root_map
set.draw { |map| map.root :controller => "people" }
- request.path = ""
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("people", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
+ params = set.recognize_path("", :method => :get)
+ assert_equal("people", params[:controller])
+ assert_equal("index", params[:action])
end
def test_namespace
@@ -1163,11 +1088,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
- request.path = "/api/inventory"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("api/products", request.path_parameters[:controller])
- assert_equal("inventory", request.path_parameters[:action])
+ params = set.recognize_path("/api/inventory", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("inventory", params[:action])
end
def test_namespaced_root_map
@@ -1179,11 +1102,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
- request.path = "/api"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("api/products", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
+ params = set.recognize_path("/api", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("index", params[:action])
end
def test_namespace_with_path_prefix
@@ -1193,11 +1114,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
- request.path = "/prefix/inventory"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("api/products", request.path_parameters[:controller])
- assert_equal("inventory", request.path_parameters[:action])
+ params = set.recognize_path("/prefix/inventory", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("inventory", params[:action])
end
def test_namespace_with_blank_path_prefix
@@ -1207,11 +1126,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
- request.path = "/inventory"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("api/products", request.path_parameters[:controller])
- assert_equal("inventory", request.path_parameters[:action])
+ params = set.recognize_path("/inventory", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("inventory", params[:action])
end
def test_generate_changes_controller_module
@@ -1340,11 +1257,9 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
- request.path = "/projects/1/milestones"
- request.env["REQUEST_METHOD"] = "GET"
- assert_nothing_raised { set.recognize(request) }
- assert_equal("milestones", request.path_parameters[:controller])
- assert_equal("index", request.path_parameters[:action])
+ params = set.recognize_path("/projects/1/milestones", :method => :get)
+ assert_equal("milestones", params[:controller])
+ assert_equal("index", params[:action])
end
def test_setting_root_in_namespace_using_symbol
@@ -1418,6 +1333,7 @@ class RouteSetTest < ActiveSupport::TestCase
:action => 'show',
:requirements => {:name => /(david|jamis)/i}
end
+
url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
assert_equal "/page/david", url
assert_raise ActionController::RoutingError do
@@ -1459,6 +1375,7 @@ class RouteSetTest < ActiveSupport::TestCase
jamis #The Deployer
)/x}
end
+
url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
assert_equal "/page/david", url
assert_raise ActionController::RoutingError do
@@ -1480,6 +1397,7 @@ class RouteSetTest < ActiveSupport::TestCase
jamis #The Deployer
)/xi}
end
+
url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
assert_equal "/page/JAMIS", url
end
@@ -1638,7 +1556,7 @@ class RouteSetTest < ActiveSupport::TestCase
end
def test_expand_array_build_query_string
- assert_uri_equal '/foo?x%5B%5D=1&x%5B%5D=2', default_route_set.generate({:controller => 'foo', :x => [1, 2]})
+ assert_uri_equal '/foo?x[]=1&x[]=2', default_route_set.generate({:controller => 'foo', :x => [1, 2]})
end
def test_escape_spaces_build_query_string_selected_keys
@@ -1656,9 +1574,7 @@ class RouteSetTest < ActiveSupport::TestCase
map.connect ':controller/:action/:id'
end
- pending do
- assert_equal '/ibocorp', set.generate({:controller => 'ibocorp', :page => 1})
- end
+ assert_equal '/ibocorp', set.generate({:controller => 'ibocorp', :page => 1})
end
def test_generate_with_optional_params_recalls_last_request
@@ -1691,9 +1607,7 @@ class RouteSetTest < ActiveSupport::TestCase
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))
- pending do
- assert_equal("/blog/2006/07/28", set.generate({:year => 2006}, last_request))
- end
+ assert_equal("/blog/2006", set.generate({:year => 2006}, last_request))
assert_equal("/blog/2006", set.generate({:year => 2006, :month => nil}, last_request))
end
@@ -1709,85 +1623,6 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
-class RouteLoadingTest < Test::Unit::TestCase
- def setup
- routes.instance_variable_set '@routes_last_modified', nil
- Object.remove_const(:RAILS_ROOT) if defined?(::RAILS_ROOT)
- Object.const_set :RAILS_ROOT, '.'
- routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb'))
-
- @stat = stub_everything
- end
-
- def teardown
- ActionController::Routing::Routes.configuration_files.clear
- Object.send :remove_const, :RAILS_ROOT
- end
-
- def test_load
- File.expects(:stat).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/))
-
- routes.reload
- end
-
- def test_no_reload_when_not_modified
- @stat.expects(:mtime).times(2).returns(1)
- File.expects(:stat).times(2).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/)).at_most_once
-
- 2.times { routes.reload }
- end
-
- def test_reload_when_modified
- @stat.expects(:mtime).at_least(2).returns(1, 2)
- File.expects(:stat).at_least(2).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
-
- 2.times { routes.reload }
- end
-
- def test_bang_forces_reload
- @stat.expects(:mtime).at_least(2).returns(1)
- File.expects(:stat).at_least(2).returns(@stat)
- routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
-
- 2.times { routes.reload! }
- end
-
- def test_adding_inflections_forces_reload
- ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment')
- routes.expects(:reload!)
-
- ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') }
- end
-
- def test_load_with_configuration
- routes.configuration_files.clear
- routes.add_configuration_file("foobarbaz")
- File.expects(:stat).returns(@stat)
- routes.expects(:load).with("foobarbaz")
-
- routes.reload
- end
-
- def test_load_multiple_configurations
- routes.add_configuration_file("engines.rb")
-
- File.expects(:stat).at_least_once.returns(@stat)
-
- routes.expects(:load).with('./config/routes.rb')
- routes.expects(:load).with('engines.rb')
-
- routes.reload
- end
-
- private
- def routes
- ActionController::Routing::Routes
- end
-end
-
class RackMountIntegrationTests < ActiveSupport::TestCase
Model = Struct.new(:to_param)
@@ -1877,11 +1712,9 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
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 => '01', :day => '01'}, @routes.recognize_path('/blog/2009/01/01', :method => :get))
- assert_raise(ActionController::ActionControllerError) { @routes.recognize_path('/blog/123456789', :method => :get) }
assert_equal({:controller => 'archive', :action => 'index', :year => '2010'}, @routes.recognize_path('/archive/2010'))
assert_equal({:controller => 'archive', :action => 'index'}, @routes.recognize_path('/archive'))
- assert_raise(ActionController::ActionControllerError) { @routes.recognize_path('/archive/january') }
assert_equal({:controller => 'people', :action => 'index'}, @routes.recognize_path('/people', :method => :get))
assert_equal({:controller => 'people', :action => 'index', :format => 'xml'}, @routes.recognize_path('/people.xml', :method => :get))
@@ -2040,9 +1873,9 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
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%5B%5D=bar&foo%5B%5D=baz', @routes.generate(:controller => 'posts', :foo => ['bar', 'baz'])
+ 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%5Bfoo%5D%5Ba%5D=b', @routes.generate(:controller => 'posts', :q => { :foo => { :a => 'b'}})
+ 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)
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index 375878b755..0f074b32e6 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -456,8 +456,8 @@ XML
def test_array_path_parameter_handled_properly
with_routing do |set|
set.draw do |map|
- map.connect 'file/*path', :controller => 'test_test/test', :action => 'test_params'
- map.connect ':controller/:action/:id'
+ match 'file/*path', :to => 'test_test/test#test_params'
+ match ':controller/:action'
end
get :test_params, :path => ['hello', 'world']
@@ -563,7 +563,7 @@ XML
expected = File.read(path)
expected.force_encoding(Encoding::BINARY) if expected.respond_to?(:force_encoding)
- file = ActionController::TestUploadedFile.new(path, content_type)
+ file = Rack::Test::UploadedFile.new(path, content_type)
assert_equal filename, file.original_filename
assert_equal content_type, file.content_type
assert_equal file.path, file.local_path
@@ -580,10 +580,10 @@ XML
path = "#{FILES_DIR}/#{filename}"
content_type = 'image/png'
- binary_uploaded_file = ActionController::TestUploadedFile.new(path, content_type, :binary)
+ binary_uploaded_file = Rack::Test::UploadedFile.new(path, content_type, :binary)
assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read
- plain_uploaded_file = ActionController::TestUploadedFile.new(path, content_type)
+ plain_uploaded_file = Rack::Test::UploadedFile.new(path, content_type)
assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
end
@@ -605,7 +605,7 @@ XML
end
def test_test_uploaded_file_exception_when_file_doesnt_exist
- assert_raise(RuntimeError) { ActionController::TestUploadedFile.new('non_existent_file') }
+ assert_raise(RuntimeError) { Rack::Test::UploadedFile.new('non_existent_file') }
end
def test_redirect_url_only_cares_about_location_header
@@ -628,17 +628,6 @@ XML
assert_nothing_raised(NoMethodError) { @response.binary_content }
end
end
-
- protected
- def with_foo_routing
- with_routing do |set|
- set.draw do |map|
- map.generate_url 'foo', :controller => 'test'
- map.connect ':controller/:action/:id'
- end
- yield set
- end
- end
end
class InferringClassNameTest < ActionController::TestCase
@@ -673,7 +662,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| map.resources :contents }
+ set.draw { |map| 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_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index 3b14cbb2d8..428f40b9f8 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -247,7 +247,7 @@ class UrlWriterTests < ActionController::TestCase
with_routing do |set|
set.draw do |map|
- map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index'
+ match '/home/sweet/home/:user', :to => 'home#index', :as => :home
end
kls = Class.new { include ActionController::UrlWriter }
@@ -264,7 +264,7 @@ class UrlWriterTests < ActionController::TestCase
with_routing do |set|
set.draw do |map|
match 'home/sweet/home/:user', :to => 'home#index', :as => :home
- map.connect ':controller/:action/:id'
+ match ':controller/:action/:id'
end
# We need to create a new class in order to install the new named route.
@@ -331,8 +331,8 @@ class UrlWriterTests < ActionController::TestCase
def test_named_routes_with_nil_keys
with_routing do |set|
set.draw do |map|
- map.main '', :controller => 'posts', :format => nil
- map.resources :posts
+ match 'posts.:format', :to => 'posts#index', :as => :posts
+ match '/', :to => 'posts#index', :as => :main
end
# We need to create a new class in order to install the new named route.
@@ -350,7 +350,7 @@ class UrlWriterTests < ActionController::TestCase
def test_formatted_url_methods_are_deprecated
with_routing do |set|
set.draw do |map|
- map.resources :posts
+ resources :posts
end
# We need to create a new class in order to install the new named route.
kls = Class.new { include ActionController::UrlWriter }
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index 0514c098bf..5882a8cfa3 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -255,9 +255,7 @@ class WebServiceTest < ActionController::IntegrationTest
def with_test_route_set
with_routing do |set|
set.draw do |map|
- map.with_options :controller => "web_service_test/test" do |c|
- c.connect "/", :action => "assign_parameters"
- end
+ match '/', :to => 'web_service_test/test#assign_parameters'
end
yield
end
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 301080842e..40c5ac2d09 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -151,7 +151,7 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
def with_test_routing
with_routing do |set|
set.draw do |map|
- map.connect ':action', :controller => "multipart_params_parsing_test/test"
+ match ':action', :to => 'multipart_params_parsing_test/test'
end
yield
end
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 256ed06a45..02f63f7006 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -7,7 +7,6 @@ class ResponseTest < ActiveSupport::TestCase
test "simple output" do
@response.body = "Hello, World!"
- @response.prepare!
status, headers, body = @response.to_a
assert_equal 200, status
@@ -25,7 +24,6 @@ class ResponseTest < ActiveSupport::TestCase
test "utf8 output" do
@response.body = [1090, 1077, 1089, 1090].pack("U*")
- @response.prepare!
status, headers, body = @response.to_a
assert_equal 200, status
@@ -41,7 +39,6 @@ class ResponseTest < ActiveSupport::TestCase
@response.body = Proc.new do |response, output|
5.times { |n| output.write(n) }
end
- @response.prepare!
status, headers, body = @response.to_a
assert_equal 200, status
@@ -59,14 +56,12 @@ class ResponseTest < ActiveSupport::TestCase
test "content type" do
[204, 304].each do |c|
@response.status = c.to_s
- @response.prepare!
status, headers, body = @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
- @response.prepare!
status, headers, body = @response.to_a
assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
end
@@ -74,7 +69,6 @@ class ResponseTest < ActiveSupport::TestCase
test "does not include Status header" do
@response.status = "200 OK"
- @response.prepare!
status, headers, body = @response.to_a
assert !headers.has_key?('Status')
end
@@ -114,15 +108,126 @@ class ResponseTest < ActiveSupport::TestCase
test "cookies" do
@response.set_cookie("user_name", :value => "david", :path => "/")
- @response.prepare!
status, headers, body = @response.to_a
assert_equal "user_name=david; path=/", headers["Set-Cookie"]
assert_equal({"user_name" => "david"}, @response.cookies)
@response.set_cookie("login", :value => "foo&bar", :path => "/", :expires => Time.utc(2005, 10, 10,5))
- @response.prepare!
status, headers, body = @response.to_a
assert_equal "user_name=david; path=/\nlogin=foo%26bar; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT", headers["Set-Cookie"]
assert_equal({"login" => "foo&bar", "user_name" => "david"}, @response.cookies)
end
+
+ test "read cache control" do
+ resp = ActionDispatch::Response.new.tap { |resp|
+ resp.cache_control[:public] = true
+ resp.etag = '123'
+ resp.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('"202cb962ac59075b964b07152d234b70"', resp.etag)
+ assert_equal({:public => true}, resp.cache_control)
+
+ assert_equal('public', resp.headers['Cache-Control'])
+ assert_equal('"202cb962ac59075b964b07152d234b70"', resp.headers['ETag'])
+ end
+
+ test "read charset and content type" do
+ resp = ActionDispatch::Response.new.tap { |resp|
+ resp.charset = 'utf-16'
+ resp.content_type = Mime::XML
+ resp.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('utf-16', resp.charset)
+ assert_equal(Mime::XML, resp.content_type)
+
+ assert_equal('application/xml; charset=utf-16', resp.headers['Content-Type'])
+ end
+end
+
+class ResponseIntegrationTest < ActionDispatch::IntegrationTest
+ def app
+ @app
+ end
+
+ test "response cache control from railsish app" do
+ @app = lambda { |env|
+ ActionDispatch::Response.new.tap { |resp|
+ resp.cache_control[:public] = true
+ resp.etag = '123'
+ resp.body = 'Hello'
+ }.to_a
+ }
+
+ get '/'
+ assert_response :success
+
+ assert_equal('public', @response.headers['Cache-Control'])
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.headers['ETag'])
+
+ pending do
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag)
+ assert_equal({:public => true}, @response.cache_control)
+ end
+ end
+
+ test "response cache control from rackish app" do
+ @app = lambda { |env|
+ [200,
+ {'ETag' => '"202cb962ac59075b964b07152d234b70"',
+ 'Cache-Control' => 'public'}, ['Hello']]
+ }
+
+ get '/'
+ assert_response :success
+
+ assert_equal('public', @response.headers['Cache-Control'])
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.headers['ETag'])
+
+ pending do
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag)
+ assert_equal({:public => true}, @response.cache_control)
+ end
+ end
+
+ test "response charset and content type from railsish app" do
+ @app = lambda { |env|
+ ActionDispatch::Response.new.tap { |resp|
+ resp.charset = 'utf-16'
+ resp.content_type = Mime::XML
+ resp.body = 'Hello'
+ }.to_a
+ }
+
+ get '/'
+ assert_response :success
+
+ pending do
+ assert_equal('utf-16', @response.charset)
+ assert_equal(Mime::XML, @response.content_type)
+ end
+
+ assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type'])
+ end
+
+ test "response charset and content type from rackish app" do
+ @app = lambda { |env|
+ [200,
+ {'Content-Type' => 'application/xml; charset=utf-16'},
+ ['Hello']]
+ }
+
+ get '/'
+ assert_response :success
+
+ pending do
+ assert_equal('utf-16', @response.charset)
+ assert_equal(Mime::XML, @response.content_type)
+ end
+
+ assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type'])
+ end
end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index ca07bc7a28..c4b0b9cdbf 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -14,31 +14,37 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
stub_controllers do |routes|
Routes = routes
- Routes.draw do |map|
+ Routes.draw do
controller :sessions do
- get 'login', :to => :new, :as => :login
- post 'login', :to => :create
+ get 'login' => :new, :as => :login
+ post 'login' => :create
- delete 'logout', :to => :destroy, :as => :logout
+ delete 'logout' => :destroy, :as => :logout
end
+ match 'account/logout' => redirect("/logout"), :as => :logout_redirect
match 'account/login', :to => redirect("/login")
+ match 'account/overview'
+
+ match 'account/modulo/:name', :to => redirect("/%{name}s")
+ match 'account/proc/:name', :to => redirect {|params| "/#{params[:name].pluralize}" }
+
match 'openid/login', :via => [:get, :post], :to => "openid#login"
controller(:global) do
- match 'global/:action'
+ get 'global/hide_notice'
match 'global/export', :to => :export, :as => :export_request
- match 'global/hide_notice', :to => :hide_notice, :as => :hide_notice
match '/export/:id/:file', :to => :export, :as => :export_download, :constraints => { :file => /.*/ }
+ match 'global/:action'
end
constraints(:ip => /192\.168\.1\.\d\d\d/) do
- get 'admin', :to => "queenbee#index"
+ get 'admin' => "queenbee#index"
end
constraints ::TestRoutingMapper::IpRestrictor do
- get 'admin/accounts', :to => "queenbee#accounts"
+ get 'admin/accounts' => "queenbee#accounts"
end
resources :projects, :controller => :project do
@@ -58,8 +64,10 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
resources :people do
- namespace ":access_token" do
- resource :avatar
+ nested do
+ namespace ":access_token" do
+ resource :avatar
+ end
end
member do
@@ -80,7 +88,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- match 'sprockets.js', :to => ::TestRoutingMapper::SprocketsApp
+ match 'sprockets.js' => ::TestRoutingMapper::SprocketsApp
match 'people/:id/update', :to => 'people#update', :as => :update_person
match '/projects/:project_id/people/:id/update', :to => 'people#update', :as => :update_project_person
@@ -93,9 +101,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
controller :articles do
- scope 'articles' do
- scope ':title', :title => /[a-z]+/, :as => :with_title do
- match ':id', :to => :with_id
+ scope '/articles', :name_prefix => 'article' do
+ scope :path => '/:title', :title => /[a-z]+/, :as => :with_title do
+ match '/:id', :to => :with_id
end
end
end
@@ -103,6 +111,10 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
scope ':access_token', :constraints => { :access_token => /\w{5,5}/ } do
resources :rooms
end
+
+ match '/info' => 'projects#info', :as => 'info'
+
+ root :to => 'projects#index'
end
end
@@ -143,6 +155,34 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_logout_redirect_without_to
+ with_test_routes do
+ assert_equal '/account/logout', logout_redirect_path
+ get '/account/logout'
+ assert_equal 301, @response.status
+ assert_equal 'http://www.example.com/logout', @response.headers['Location']
+ assert_equal 'Moved Permanently', @response.body
+ end
+ end
+
+ def test_redirect_modulo
+ with_test_routes do
+ get '/account/modulo/name'
+ assert_equal 301, @response.status
+ assert_equal 'http://www.example.com/names', @response.headers['Location']
+ assert_equal 'Moved Permanently', @response.body
+ end
+ end
+
+ def test_redirect_proc
+ with_test_routes do
+ get '/account/proc/person'
+ assert_equal 301, @response.status
+ assert_equal 'http://www.example.com/people', @response.headers['Location']
+ assert_equal 'Moved Permanently', @response.body
+ end
+ end
+
def test_openid
with_test_routes do
get '/openid/login'
@@ -183,7 +223,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal 'global#export', @response.body
assert_equal '/global/export', export_request_path
- assert_equal '/global/hide_notice', hide_notice_path
+ assert_equal '/global/hide_notice', global_hide_notice_path
assert_equal '/export/123/foo.txt', export_download_path(:id => 123, :file => 'foo.txt')
end
end
@@ -194,14 +234,26 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal 'projects#index', @response.body
assert_equal '/projects', projects_path
+ get '/projects.xml'
+ assert_equal 'projects#index', @response.body
+ assert_equal '/projects.xml', projects_path(:format => 'xml')
+
get '/projects/new'
assert_equal 'projects#new', @response.body
assert_equal '/projects/new', new_project_path
+ get '/projects/new.xml'
+ assert_equal 'projects#new', @response.body
+ assert_equal '/projects/new.xml', new_project_path(:format => 'xml')
+
get '/projects/1'
assert_equal 'projects#show', @response.body
assert_equal '/projects/1', project_path(:id => '1')
+ get '/projects/1.xml'
+ assert_equal 'projects#show', @response.body
+ assert_equal '/projects/1.xml', project_path(:id => '1', :format => 'xml')
+
get '/projects/1/edit'
assert_equal 'projects#edit', @response.body
assert_equal '/projects/1/edit', edit_project_path(:id => '1')
@@ -212,9 +264,25 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/projects/1/involvements'
assert_equal 'involvements#index', @response.body
+ assert_equal '/projects/1/involvements', project_involvements_path(:project_id => '1')
+
+ get '/projects/1/involvements/new'
+ assert_equal 'involvements#new', @response.body
+ assert_equal '/projects/1/involvements/new', new_project_involvement_path(:project_id => '1')
get '/projects/1/involvements/1'
assert_equal 'involvements#show', @response.body
+ assert_equal '/projects/1/involvements/1', project_involvement_path(:project_id => '1', :id => '1')
+
+ put '/projects/1/involvements/1'
+ assert_equal 'involvements#update', @response.body
+
+ delete '/projects/1/involvements/1'
+ assert_equal 'involvements#destroy', @response.body
+
+ get '/projects/1/involvements/1/edit'
+ assert_equal 'involvements#edit', @response.body
+ assert_equal '/projects/1/involvements/1/edit', edit_project_involvement_path(:project_id => '1', :id => '1')
end
end
@@ -222,6 +290,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/projects/1/attachments'
assert_equal 'attachments#index', @response.body
+ assert_equal '/projects/1/attachments', project_attachments_path(:project_id => '1')
end
end
@@ -229,9 +298,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/projects/1/participants'
assert_equal 'participants#index', @response.body
+ assert_equal '/projects/1/participants', project_participants_path(:project_id => '1')
put '/projects/1/participants/update_all'
assert_equal 'participants#update_all', @response.body
+ assert_equal '/projects/1/participants/update_all', update_all_project_participants_path(:project_id => '1')
end
end
@@ -239,12 +310,15 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/projects/1/companies'
assert_equal 'companies#index', @response.body
+ assert_equal '/projects/1/companies', project_companies_path(:project_id => '1')
get '/projects/1/companies/1/people'
assert_equal 'people#index', @response.body
+ assert_equal '/projects/1/companies/1/people', project_company_people_path(:project_id => '1', :company_id => '1')
get '/projects/1/companies/1/avatar'
assert_equal 'avatars#show', @response.body
+ assert_equal '/projects/1/companies/1/avatar', project_company_avatar_path(:project_id => '1', :company_id => '1')
end
end
@@ -252,9 +326,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/projects/1/images'
assert_equal 'images#index', @response.body
+ assert_equal '/projects/1/images', project_images_path(:project_id => '1')
post '/projects/1/images/1/revise'
assert_equal 'images#revise', @response.body
+ assert_equal '/projects/1/images/1/revise', revise_project_image_path(:project_id => '1', :id => '1')
end
end
@@ -262,21 +338,27 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/projects/1/people'
assert_equal 'people#index', @response.body
+ assert_equal '/projects/1/people', project_people_path(:project_id => '1')
get '/projects/1/people/1'
assert_equal 'people#show', @response.body
+ assert_equal '/projects/1/people/1', project_person_path(:project_id => '1', :id => '1')
get '/projects/1/people/1/7a2dec8/avatar'
assert_equal 'avatars#show', @response.body
+ assert_equal '/projects/1/people/1/7a2dec8/avatar', project_person_avatar_path(:project_id => '1', :person_id => '1', :access_token => '7a2dec8')
put '/projects/1/people/1/accessible_projects'
assert_equal 'people#accessible_projects', @response.body
+ assert_equal '/projects/1/people/1/accessible_projects', accessible_projects_project_person_path(:project_id => '1', :id => '1')
post '/projects/1/people/1/resend'
assert_equal 'people#resend', @response.body
+ assert_equal '/projects/1/people/1/resend', resend_project_person_path(:project_id => '1', :id => '1')
post '/projects/1/people/1/generate_new_password'
assert_equal 'people#generate_new_password', @response.body
+ assert_equal '/projects/1/people/1/generate_new_password', generate_new_password_project_person_path(:project_id => '1', :id => '1')
end
end
@@ -284,24 +366,31 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
with_test_routes do
get '/projects/1/posts'
assert_equal 'posts#index', @response.body
+ assert_equal '/projects/1/posts', project_posts_path(:project_id => '1')
get '/projects/1/posts/archive'
assert_equal 'posts#archive', @response.body
+ assert_equal '/projects/1/posts/archive', archive_project_posts_path(:project_id => '1')
get '/projects/1/posts/toggle_view'
assert_equal 'posts#toggle_view', @response.body
+ assert_equal '/projects/1/posts/toggle_view', toggle_view_project_posts_path(:project_id => '1')
post '/projects/1/posts/1/preview'
assert_equal 'posts#preview', @response.body
+ assert_equal '/projects/1/posts/1/preview', preview_project_post_path(:project_id => '1', :id => '1')
get '/projects/1/posts/1/subscription'
assert_equal 'subscriptions#show', @response.body
+ assert_equal '/projects/1/posts/1/subscription', project_post_subscription_path(:project_id => '1', :post_id => '1')
get '/projects/1/posts/1/comments'
assert_equal 'comments#index', @response.body
+ assert_equal '/projects/1/posts/1/comments', project_post_comments_path(:project_id => '1', :post_id => '1')
post '/projects/1/posts/1/comments/preview'
assert_equal 'comments#preview', @response.body
+ assert_equal '/projects/1/posts/1/comments/preview', preview_project_post_comments_path(:project_id => '1', :post_id => '1')
end
end
@@ -359,7 +448,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_raise(ActionController::RoutingError) { get '/articles/123/1' }
- assert_equal '/articles/rails/1', with_title_path(:title => 'rails', :id => 1)
+ assert_equal '/articles/rails/1', article_with_title_path(:title => 'rails', :id => 1)
end
end
@@ -376,6 +465,38 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_root
+ with_test_routes do
+ assert_equal '/', root_path
+ get '/'
+ assert_equal 'projects#index', @response.body
+ 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_index
+ with_test_routes do
+ assert_equal '/info', info_path
+ get '/info'
+ assert_equal 'projects#info', @response.body
+ end
+ end
+
+ def test_convention_match_with_no_scope
+ with_test_routes do
+ assert_equal '/account/overview', account_overview_path
+ get '/account/overview'
+ assert_equal 'account#overview', @response.body
+ end
+ end
+
private
def with_test_routes
real_routes, temp_routes = ActionController::Routing::Routes, Routes
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index 5da02b2ea6..e42ade73d1 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -18,7 +18,7 @@ class TestRequestTest < ActiveSupport::TestCase
assert_equal "0.0.0.0", env.delete("REMOTE_ADDR")
assert_equal "Rails Testing", env.delete("HTTP_USER_AGENT")
- assert_equal [1, 0], env.delete("rack.version")
+ assert_equal [1, 1], env.delete("rack.version")
assert_equal "", env.delete("rack.input").string
assert_kind_of StringIO, env.delete("rack.errors")
assert_equal true, env.delete("rack.multithread")
diff --git a/actionpack/test/lib/controller/fake_controllers.rb b/actionpack/test/lib/controller/fake_controllers.rb
index 250327e6dc..09692f77b5 100644
--- a/actionpack/test/lib/controller/fake_controllers.rb
+++ b/actionpack/test/lib/controller/fake_controllers.rb
@@ -1,37 +1,48 @@
class << Object; alias_method :const_available?, :const_defined?; end
class ContentController < ActionController::Base; end
-class NotAController; end
module Admin
class << self; alias_method :const_available?, :const_defined?; end
+ class AccountsController < ActionController::Base; end
class NewsFeedController < ActionController::Base; end
class PostsController < ActionController::Base; end
class StuffController < ActionController::Base; end
class UserController < ActionController::Base; end
+ class UsersController < ActionController::Base; end
end
module Api
+ class UsersController < ActionController::Base; end
class ProductsController < ActionController::Base; end
end
# TODO: Reduce the number of test controllers we use
+class AccountController < ActionController::Base; end
class AddressesController < ActionController::Base; end
+class ArchiveController < ActionController::Base; end
class ArticlesController < ActionController::Base; end
class BarController < ActionController::Base; end
+class BlogController < ActionController::Base; end
class BooksController < ActionController::Base; end
class BraveController < ActionController::Base; end
+class CarsController < ActionController::Base; end
+class CcController < ActionController::Base; end
class CController < ActionController::Base; end
class ElsewhereController < ActionController::Base; end
class FooController < ActionController::Base; end
+class GeocodeController < ActionController::Base; end
class HiController < ActionController::Base; end
class ImageController < ActionController::Base; end
+class NewsController < ActionController::Base; end
class NotesController < ActionController::Base; end
class PeopleController < ActionController::Base; end
class PostsController < ActionController::Base; end
class SessionsController < ActionController::Base; end
class StuffController < ActionController::Base; end
class SubpathBooksController < ActionController::Base; end
+class SymbolsController < ActionController::Base; end
+class UserController < ActionController::Base; end
class WeblogController < ActionController::Base; end
# For speed test
diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb
index 823de8bdc7..b0e5d7a94c 100644
--- a/actionpack/test/lib/controller/fake_models.rb
+++ b/actionpack/test/lib/controller/fake_models.rb
@@ -54,6 +54,7 @@ end
class Post < Struct.new(:title, :author_name, :body, :secret, :written_on, :cost)
extend ActiveModel::Naming
include ActiveModel::Conversion
+ extend ActiveModel::Translation
alias_method :secret?, :secret
diff --git a/actionpack/test/template/ajax_test.rb b/actionpack/test/template/ajax_test.rb
index 670ba92697..aeb7c09b09 100644
--- a/actionpack/test/template/ajax_test.rb
+++ b/actionpack/test/template/ajax_test.rb
@@ -6,7 +6,7 @@ class AjaxTestCase < ActiveSupport::TestCase
def assert_html(html, matches)
matches.each do |match|
- assert_match Regexp.new(Regexp.escape(match)), html
+ assert_match(Regexp.new(Regexp.escape(match)), html)
end
end
@@ -52,18 +52,18 @@ class LinkToRemoteTest < AjaxTestCase
test "with a hash for :update" do
link = link(:update => {:success => "#posts", :failure => "#error"})
- assert_match /data-update-success="#posts"/, link
- assert_match /data-update-failure="#error"/, link
+ assert_match(/data-update-success="#posts"/, link)
+ assert_match(/data-update-failure="#error"/, link)
end
test "with positional parameters" do
link = link(:position => :top, :update => "#posts")
- assert_match /data\-update\-position="top"/, link
+ assert_match(/data\-update\-position="top"/, link)
end
test "with an optional method" do
link = link(:method => "delete")
- assert_match /data-method="delete"/, link
+ assert_match(/data-method="delete"/, link)
end
class LegacyLinkToRemoteTest < AjaxTestCase
@@ -99,7 +99,7 @@ class ButtonToRemoteTest < AjaxTestCase
button = button({:url => {:action => "whatnot"}}, {:class => "fine"})
[/input/, /class="fine"/, /type="button"/, /value="Remote outpost"/,
/data-url="\/whatnot"/].each do |match|
- assert_match match, button
+ assert_match(match, button)
end
end
end
diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb
index 6a5fb0acff..347cb98303 100644
--- a/actionpack/test/template/atom_feed_helper_test.rb
+++ b/actionpack/test/template/atom_feed_helper_test.rb
@@ -187,10 +187,9 @@ class ScrollsController < ActionController::Base
end
protected
-
- def rescue_action(e)
- raise(e)
- end
+ def rescue_action(e)
+ raise(e)
+ end
end
class AtomFeedTest < ActionController::TestCase
@@ -311,11 +310,12 @@ class AtomFeedTest < ActionController::TestCase
assert_select "summary div p", :text => "after 2"
end
end
-private
+
+ private
def with_restful_routing(resources)
with_routing do |set|
set.draw do |map|
- map.resources(resources)
+ resources(resources)
end
yield
end
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 44734abb18..b1e9fe99a2 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -6,6 +6,25 @@ class FormHelperTest < ActionView::TestCase
def setup
super
+
+ # Create "label" locale for testing I18n label helpers
+ I18n.backend.store_translations 'label', {
+ :activemodel => {
+ :attributes => {
+ :post => {
+ :cost => "Total cost"
+ }
+ }
+ },
+ :views => {
+ :labels => {
+ :post => {
+ :body => "Write entire text here"
+ }
+ }
+ }
+ }
+
@post = Post.new
@comment = Comment.new
def @post.errors()
@@ -51,6 +70,27 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal('<label for="post_secret">Secret?</label>', label(:post, :secret?))
end
+ def test_label_with_locales_strings
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_body">Write entire text here</label>', label("post", "body"))
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_human_attribute_name
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_cost">Total cost</label>', label(:post, :cost))
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_locales_symbols
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_body">Write entire text here</label>', label(:post, :body))
+ ensure
+ I18n.locale = old_locale
+ end
+
def test_label_with_for_attribute_as_symbol
assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for"))
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 35c51ca7ea..fdf3db1cdb 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -106,8 +106,8 @@ module RenderTestCases
def test_render_partial_with_errors
@view.render(:partial => "test/raise")
- flunk "Render did not raise TemplateError"
- rescue ActionView::TemplateError => e
+ flunk "Render did not raise Template::Error"
+ rescue ActionView::Template::Error => e
assert_match "undefined local variable or method `doesnt_exist'", e.message
assert_equal "", e.sub_template_message
assert_equal "1", e.line_number
@@ -116,8 +116,8 @@ module RenderTestCases
def test_render_sub_template_with_errors
@view.render(:file => "test/sub_template_raise")
- flunk "Render did not raise TemplateError"
- rescue ActionView::TemplateError => e
+ flunk "Render did not raise Template::Error"
+ rescue ActionView::Template::Error => e
assert_match "undefined local variable or method `doesnt_exist'", e.message
assert_equal "Trace of template inclusion: #{File.expand_path("#{FIXTURE_LOAD_PATH}/test/sub_template_raise.html.erb")}", e.sub_template_message
assert_equal "1", e.line_number
diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb
index 05a409d05a..9a448ce328 100644
--- a/actionpack/test/template/test_case_test.rb
+++ b/actionpack/test/template/test_case_test.rb
@@ -114,7 +114,7 @@ module ActionView
test "is able to use named routes" do
with_routing do |set|
- set.draw { |map| map.resources :contents }
+ set.draw { |map| resources :contents }
assert_equal 'http://test.host/contents/new', new_content_url
assert_equal 'http://test.host/contents/1', content_url(:id => 1)
end
@@ -122,7 +122,7 @@ module ActionView
test "named routes can be used from helper included in view" do
with_routing do |set|
- set.draw { |map| map.resources :contents }
+ set.draw { |map| resources :contents }
_helpers.module_eval do
def render_from_helper
new_content_url
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index a20f3c394c..d67d2c7911 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -9,7 +9,7 @@ class TranslationHelperTest < Test::Unit::TestCase
end
def test_delegates_to_i18n_setting_the_raise_option
- I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true)
+ I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true).returns("")
translate :foo, :locale => 'en'
end
@@ -26,7 +26,7 @@ class TranslationHelperTest < Test::Unit::TestCase
def test_scoping_by_partial
expects(:template).returns(stub(:path_without_format_and_extension => "people/index"))
- I18n.expects(:translate).with("people.index.foo", :locale => 'en', :raise => true)
+ I18n.expects(:translate).with("people.index.foo", :locale => 'en', :raise => true).returns("")
translate ".foo", :locale => 'en'
end
end
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index bf0b4ad3a7..d4b58efe1e 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -391,54 +391,47 @@ class UrlHelperTest < ActionView::TestCase
end
end
-class UrlHelperController < ActionController::Base
- def self.controller_path; 'url_helper_with_controller' end
+class UrlHelperControllerTest < ActionController::TestCase
+ class UrlHelperController < ActionController::Base
+ def show_url_for
+ render :inline => "<%= url_for :controller => 'url_helper_controller_test/url_helper', :action => 'show_url_for' %>"
+ end
- def show_url_for
- render :inline => "<%= url_for :controller => 'url_helper_with_controller', :action => 'show_url_for' %>"
- end
+ def show_named_route
+ render :inline => "<%= show_named_route_#{params[:kind]} %>"
+ end
- def show_named_route
- render :inline => "<%= show_named_route_#{params[:kind]} %>"
- end
+ def nil_url_for
+ render :inline => '<%= url_for(nil) %>'
+ end
- def nil_url_for
- render :inline => '<%= url_for(nil) %>'
+ def rescue_action(e) raise e end
end
- def rescue_action(e) raise e end
-end
-
-class UrlHelperWithControllerTest < ActionController::TestCase
- def setup
- super
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = UrlHelperController.new
- end
+ tests UrlHelperController
def test_url_for_shows_only_path
get :show_url_for
- assert_equal '/url_helper_with_controller/show_url_for', @response.body
+ assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body
end
def test_named_route_url_shows_host_and_path
with_url_helper_routing do
get :show_named_route, :kind => 'url'
- assert_equal 'http://test.host/url_helper_with_controller/show_named_route', @response.body
+ assert_equal 'http://test.host/url_helper_controller_test/url_helper/show_named_route', @response.body
end
end
def test_named_route_path_shows_only_path
with_url_helper_routing do
get :show_named_route, :kind => 'path'
- assert_equal '/url_helper_with_controller/show_named_route', @response.body
+ assert_equal '/url_helper_controller_test/url_helper/show_named_route', @response.body
end
end
def test_url_for_nil_returns_current_path
get :nil_url_for
- assert_equal '/url_helper/nil_url_for', @response.body
+ assert_equal '/url_helper_controller_test/url_helper/nil_url_for', @response.body
end
def test_named_route_should_show_host_and_path_using_controller_default_url_options
@@ -450,7 +443,7 @@ class UrlHelperWithControllerTest < ActionController::TestCase
with_url_helper_routing do
get :show_named_route, :kind => 'url'
- assert_equal 'http://testtwo.host/url_helper_with_controller/show_named_route', @response.body
+ assert_equal 'http://testtwo.host/url_helper_controller_test/url_helper/show_named_route', @response.body
end
end
@@ -458,7 +451,7 @@ class UrlHelperWithControllerTest < ActionController::TestCase
def with_url_helper_routing
with_routing do |set|
set.draw do |map|
- map.show_named_route 'url_helper_with_controller/show_named_route', :controller => 'url_helper', :action => 'show_named_route'
+ match 'url_helper_controller_test/url_helper/show_named_route', :to => 'url_helper_controller_test/url_helper#show_named_route', :as => :show_named_route
end
yield
end
@@ -512,7 +505,7 @@ class LinkToUnlessCurrentWithControllerTest < ActionController::TestCase
def with_restful_routing
with_routing do |set|
set.draw do |map|
- map.resources :tasks
+ resources :tasks
end
yield
end
@@ -632,8 +625,8 @@ class PolymorphicControllerTest < ActionController::TestCase
def with_restful_routing
with_routing do |set|
set.draw do |map|
- map.resources :workshops do |w|
- w.resources :sessions
+ resources :workshops do
+ resources :sessions
end
end
yield
diff --git a/activemodel/Rakefile b/activemodel/Rakefile
index 1f4a8466c9..f098ce0671 100755
--- a/activemodel/Rakefile
+++ b/activemodel/Rakefile
@@ -15,7 +15,6 @@ task :default => :test
Rake::TestTask.new do |t|
t.libs << "#{dir}/test"
t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb").sort
- t.verbose = true
t.warning = true
end
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index 505e16c195..f14016027c 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -21,34 +21,41 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
-$:.unshift(activesupport_path) if File.directory?(activesupport_path)
+activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
+$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
require 'active_support'
+
module ActiveModel
- autoload :AttributeMethods, 'active_model/attribute_methods'
- autoload :Conversion, 'active_model/conversion'
- autoload :DeprecatedErrorMethods, 'active_model/deprecated_error_methods'
- autoload :Dirty, 'active_model/dirty'
- autoload :Errors, 'active_model/errors'
- autoload :Lint, 'active_model/lint'
+ extend ActiveSupport::Autoload
+
+ autoload :AttributeMethods
+ autoload :Callbacks
+ autoload :Conversion
+ autoload :DeprecatedErrorMethods
+ autoload :Dirty
+ autoload :Errors
+ autoload :Lint
autoload :Name, 'active_model/naming'
- autoload :Naming, 'active_model/naming'
+ autoload :Naming
autoload :Observer, 'active_model/observing'
- autoload :Observing, 'active_model/observing'
- autoload :Serialization, 'active_model/serialization'
- autoload :StateMachine, 'active_model/state_machine'
- autoload :TestCase, 'active_model/test_case'
- autoload :Translation, 'active_model/translation'
- autoload :Validations, 'active_model/validations'
- autoload :ValidationsRepairHelper, 'active_model/validations_repair_helper'
- autoload :Validator, 'active_model/validator'
- autoload :VERSION, 'active_model/version'
+ autoload :Observing
+ autoload :Serialization
+ autoload :StateMachine
+ autoload :Translation
+ autoload :Validations
+ autoload :Validator
+ autoload :EachValidator, 'active_model/validator'
+ autoload :BlockValidator, 'active_model/validator'
+ autoload :VERSION
module Serializers
- autoload :JSON, 'active_model/serializers/json'
- autoload :Xml, 'active_model/serializers/xml'
+ extend ActiveSupport::Autoload
+
+ autoload :JSON
+ autoload :Xml
end
end
+require 'active_support/i18n'
I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
new file mode 100644
index 0000000000..f66a1ddcaa
--- /dev/null
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -0,0 +1,91 @@
+require 'active_support/callbacks'
+
+module ActiveModel
+ module Callbacks
+ def self.extended(base)
+ base.class_eval do
+ include ActiveSupport::Callbacks
+ end
+ end
+
+ # Define callbacks similar to ActiveRecord ones. It means:
+ #
+ # * The callback chain is aborted whenever the block given to
+ # _run_callbacks returns false.
+ #
+ # * If a class is given to the fallback, it will search for
+ # before_create, around_create and after_create methods.
+ #
+ # == Usage
+ #
+ # First you need to define which callbacks your model will have:
+ #
+ # class MyModel
+ # define_model_callbacks :create
+ # end
+ #
+ # This will define three class methods: before_create, around_create,
+ # and after_create. They accept a symbol, a string, an object or a block.
+ #
+ # After you create a callback, you need to tell when they are executed.
+ # For example, you could do:
+ #
+ # def create
+ # _run_create_callbacks do
+ # super
+ # end
+ # end
+ #
+ # == Options
+ #
+ # define_model_callbacks accepts all options define_callbacks does, in
+ # case 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
+ #
+ def define_model_callbacks(*callbacks)
+ options = callbacks.extract_options!
+ options = { :terminator => "result == false", :scope => [:kind, :name] }.merge(options)
+
+ types = Array(options.delete(:only))
+ types = [:before, :around, :after] if types.empty?
+
+ callbacks.each do |callback|
+ define_callbacks(callback, options)
+
+ types.each do |type|
+ send(:"_define_#{type}_model_callback", self, callback)
+ end
+ end
+ end
+
+ def _define_before_model_callback(klass, callback) #:nodoc:
+ klass.class_eval <<-CALLBACK, __FILE__, __LINE__
+ def self.before_#{callback}(*args, &block)
+ set_callback(:#{callback}, :before, *args, &block)
+ end
+ CALLBACK
+ end
+
+ def _define_around_model_callback(klass, callback) #:nodoc:
+ klass.class_eval <<-CALLBACK, __FILE__, __LINE__
+ def self.around_#{callback}(*args, &block)
+ set_callback(:#{callback}, :around, *args, &block)
+ end
+ CALLBACK
+ end
+
+ def _define_after_model_callback(klass, callback) #:nodoc:
+ klass.class_eval <<-CALLBACK, __FILE__, __LINE__
+ def self.after_#{callback}(*args, &block)
+ options = args.extract_options!
+ options[:prepend] = true
+ options[:if] = Array(options[:if]) << "!halted && value != false"
+ set_callback(:#{callback}, :after, *(args << options), &block)
+ end
+ CALLBACK
+ end
+ end
+end \ No newline at end of file
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index e8bb62953d..abc084a74b 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -97,18 +97,19 @@ module ActiveModel
full_messages = []
each do |attribute, messages|
- messages = Array.wrap(messages)
+ messages = Array(messages)
next if messages.empty?
if attribute == :base
messages.each {|m| full_messages << m }
else
- attr_name = @base.class.human_attribute_name(attribute)
- options = { :default => ' ', :scope => @base.class.i18n_scope }
- prefix = attr_name + I18n.t(:"errors.format.separator", options)
+ 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,
+ :scope => @base.class.i18n_scope }
messages.each do |m|
- full_messages << "#{prefix}#{m}"
+ full_messages << I18n.t(:"errors.format", options.merge(:message => m))
end
end
end
diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb
index 1c2347adbf..0be82aa180 100644
--- a/activemodel/lib/active_model/lint.rb
+++ b/activemodel/lib/active_model/lint.rb
@@ -41,6 +41,20 @@ module ActiveModel
assert_boolean model.destroyed?, "destroyed?"
end
+ # naming
+ # ------
+ #
+ # Model.model_name must returns a string with some convenience methods as
+ # :human and :partial_path. Check ActiveModel::Naming for more information.
+ #
+ def test_model_naming
+ assert model.class.respond_to?(:model_name), "The model should respond to model_name"
+ model_name = model.class.model_name
+ assert_kind_of String, model_name
+ assert_kind_of String, model_name.human
+ assert_kind_of String, model_name.partial_path
+ end
+
# errors
# ------
#
diff --git a/activemodel/lib/active_model/locale/en.yml b/activemodel/lib/active_model/locale/en.yml
index 0c2cf9ea33..1cdb897f13 100644
--- a/activemodel/lib/active_model/locale/en.yml
+++ b/activemodel/lib/active_model/locale/en.yml
@@ -1,6 +1,9 @@
en:
activemodel:
errors:
+ # model.errors.full_messages format.
+ format: "{{attribute}} {{message}}"
+
# The values :model, :attribute and :value are always available for interpolation
# The value :count is available when applicable. Can be used for pluralization.
messages:
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
index 675d62b9a6..4cd68a0c89 100644
--- a/activemodel/lib/active_model/naming.rb
+++ b/activemodel/lib/active_model/naming.rb
@@ -2,11 +2,11 @@ require 'active_support/inflector'
module ActiveModel
class Name < String
- attr_reader :singular, :plural, :element, :collection, :partial_path, :human
+ attr_reader :singular, :plural, :element, :collection, :partial_path
alias_method :cache_key, :collection
- def initialize(klass, name)
- super(name)
+ def initialize(klass)
+ super(klass.name)
@klass = klass
@singular = ActiveSupport::Inflector.underscore(self).tr('/', '_').freeze
@plural = ActiveSupport::Inflector.pluralize(@singular).freeze
@@ -15,13 +15,31 @@ module ActiveModel
@collection = ActiveSupport::Inflector.tableize(self).freeze
@partial_path = "#{@collection}/#{@element}".freeze
end
+
+ # Transform the model name into a more humane format, using I18n. By default,
+ # it will underscore then humanize the class name (BlogPost.model_name.human #=> "Blog post").
+ # Specify +options+ with additional translating options.
+ def human(options={})
+ return @human unless @klass.respond_to?(:lookup_ancestors) &&
+ @klass.respond_to?(:i18n_scope)
+
+ defaults = @klass.lookup_ancestors.map do |klass|
+ klass.model_name.underscore.to_sym
+ end
+
+ defaults << options.delete(:default) if options[:default]
+ defaults << @human
+
+ options.reverse_merge! :scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults
+ I18n.translate(defaults.shift, options)
+ end
end
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, name)
+ @_model_name ||= ActiveModel::Name.new(self)
end
end
end
diff --git a/activemodel/lib/active_model/railtie.rb b/activemodel/lib/active_model/railtie.rb
new file mode 100644
index 0000000000..63ffe5db63
--- /dev/null
+++ b/activemodel/lib/active_model/railtie.rb
@@ -0,0 +1,2 @@
+require "active_model"
+require "rails" \ No newline at end of file
diff --git a/activemodel/lib/active_model/translation.rb b/activemodel/lib/active_model/translation.rb
index 42ca463f82..e5ef1e6114 100644
--- a/activemodel/lib/active_model/translation.rb
+++ b/activemodel/lib/active_model/translation.rb
@@ -37,28 +37,8 @@ module ActiveModel
# 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,1])
+ ActiveSupport::Deprecation.warn("human_name has been deprecated, please use model_name.human instead", caller[0,5])
model_name.human(*args)
end
end
-
- class Name < String
- # Transform the model name into a more humane format, using I18n. By default,
- # it will underscore then humanize the class name (BlogPost.human_name #=> "Blog post").
- # Specify +options+ with additional translating options.
- def human(options={})
- return @human unless @klass.respond_to?(:lookup_ancestors) &&
- @klass.respond_to?(:i18n_scope)
-
- defaults = @klass.lookup_ancestors.map do |klass|
- klass.model_name.underscore.to_sym
- end
-
- defaults << options.delete(:default) if options[:default]
- defaults << @human
-
- options.reverse_merge! :scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults
- I18n.translate(defaults.shift, options)
- end
- end
end
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 064ec98f3a..d5460a58bd 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/hash/keys'
+require 'active_model/errors'
module ActiveModel
module Validations
@@ -12,6 +13,29 @@ module ActiveModel
end
module ClassMethods
+ # Validates each attribute against a block.
+ #
+ # class Person < ActiveRecord::Base
+ # validates_each :first_name, :last_name do |record, attr, value|
+ # record.errors.add attr, 'starts with z.' if value[0] == ?z
+ # end
+ # 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>:allow_nil</tt> - Skip validation if attribute is +nil+.
+ # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
+ # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
+ # method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
+ # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a true or false value.
+ def validates_each(*attr_names, &block)
+ options = attr_names.extract_options!.symbolize_keys
+ validates_with BlockValidator, options.merge(:attributes => attr_names.flatten), &block
+ end
+
# Adds a validation method or block to the class. This is useful when
# overriding the +validate+ instance method becomes too unwieldly and
# you're looking for more descriptive declaration of your validations.
@@ -39,39 +63,6 @@ module ActiveModel
# end
#
# This usage applies to +validate_on_create+ and +validate_on_update as well+.
-
- # Validates each attribute against a block.
- #
- # class Person < ActiveRecord::Base
- # validates_each :first_name, :last_name do |record, attr, value|
- # record.errors.add attr, 'starts with z.' if value[0] == ?z
- # end
- # 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>:allow_nil</tt> - Skip validation if attribute is +nil+.
- # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
- # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
- # method, proc or string should return or evaluate to a true or false value.
- def validates_each(*attrs)
- options = attrs.extract_options!.symbolize_keys
- attrs = attrs.flatten
-
- # Declare the validation.
- validate options do |record|
- attrs.each do |attr|
- value = record.send(:read_attribute_for_validation, attr)
- next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
- yield record, attr, value
- end
- end
- end
-
def validate(*args, &block)
options = args.last
if options.is_a?(Hash) && options.key?(:on)
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
index b65c9b933d..bd9463ed27 100644
--- a/activemodel/lib/active_model/validations/acceptance.rb
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -1,5 +1,17 @@
module ActiveModel
module Validations
+ class AcceptanceValidator < EachValidator
+ def initialize(options)
+ super(options.reverse_merge(:allow_nil => true, :accept => "1"))
+ end
+
+ def validate_each(record, attribute, value)
+ unless value == options[:accept]
+ record.errors.add(attribute, :accepted, :default => options[:message])
+ end
+ end
+ end
+
module ClassMethods
# Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
#
@@ -25,8 +37,7 @@ module ActiveModel
# 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_acceptance_of(*attr_names)
- configuration = { :allow_nil => true, :accept => "1" }
- configuration.update(attr_names.extract_options!)
+ options = attr_names.extract_options!
db_cols = begin
column_names
@@ -37,11 +48,7 @@ module ActiveModel
names = attr_names.reject { |name| db_cols.include?(name.to_s) }
attr_accessor(*names)
- validates_each(attr_names,configuration) do |record, attr_name, value|
- unless value == configuration[:accept]
- record.errors.add(attr_name, :accepted, :default => configuration[:message])
- end
- end
+ validates_with AcceptanceValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activemodel/lib/active_model/validations/confirmation.rb b/activemodel/lib/active_model/validations/confirmation.rb
index d414224dd2..b06effdceb 100644
--- a/activemodel/lib/active_model/validations/confirmation.rb
+++ b/activemodel/lib/active_model/validations/confirmation.rb
@@ -1,5 +1,13 @@
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, :default => options[:message])
+ end
+ end
+
module ClassMethods
# Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
#
@@ -30,15 +38,9 @@ module ActiveModel
# 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)
- configuration = attr_names.extract_options!
-
- attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
-
- validates_each(attr_names, configuration) do |record, attr_name, value|
- unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
- record.errors.add(attr_name, :confirmation, :default => configuration[:message])
- end
- end
+ options = attr_names.extract_options!
+ attr_accessor(*(attr_names.map { |n| :"#{n}_confirmation" }))
+ validates_with ConfirmationValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
index 2cfdec97a5..f8759f253b 100644
--- a/activemodel/lib/active_model/validations/exclusion.rb
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -1,5 +1,17 @@
module ActiveModel
module Validations
+ class ExclusionValidator < EachValidator
+ def check_validity!
+ raise ArgumentError, "An object with the method include? is required must be supplied as the " <<
+ ":in option of the configuration hash" unless options[:in].respond_to?(:include?)
+ end
+
+ def validate_each(record, attribute, value)
+ return unless options[:in].include?(value)
+ record.errors.add(attribute, :exclusion, :default => options[:message], :value => value)
+ end
+ end
+
module ClassMethods
# Validates that the value of the specified attribute is not in a particular enumerable object.
#
@@ -21,17 +33,9 @@ module ActiveModel
# 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_exclusion_of(*attr_names)
- configuration = attr_names.extract_options!
-
- enum = configuration[:in] || configuration[:within]
-
- raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
-
- validates_each(attr_names, configuration) do |record, attr_name, value|
- if enum.include?(value)
- record.errors.add(attr_name, :exclusion, :default => configuration[:message], :value => value)
- end
- end
+ options = attr_names.extract_options!
+ options[:in] ||= options.delete(:within)
+ validates_with ExclusionValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
index c670dafc7c..d5427c2b03 100644
--- a/activemodel/lib/active_model/validations/format.rb
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -1,5 +1,15 @@
module ActiveModel
module Validations
+ class FormatValidator < EachValidator
+ def validate_each(record, attribute, value)
+ if options[:with] && value.to_s !~ options[:with]
+ record.errors.add(attribute, :invalid, :default => options[:message], :value => value)
+ elsif options[:without] && value.to_s =~ options[:without]
+ record.errors.add(attribute, :invalid, :default => options[:message], :value => value)
+ end
+ end
+ end
+
module ClassMethods
# Validates whether the value of the specified attribute is of the correct form, going by the regular expression provided.
# You can require that the attribute matches the regular expression:
@@ -33,29 +43,21 @@ module ActiveModel
# 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_format_of(*attr_names)
- configuration = attr_names.extract_options!
+ options = attr_names.extract_options!
- unless configuration.include?(:with) ^ configuration.include?(:without) # ^ == xor, or "exclusive or"
+ unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or"
raise ArgumentError, "Either :with or :without must be supplied (but not both)"
end
- if configuration[:with] && !configuration[:with].is_a?(Regexp)
+ if options[:with] && !options[:with].is_a?(Regexp)
raise ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash"
end
- if configuration[:without] && !configuration[:without].is_a?(Regexp)
+ if options[:without] && !options[:without].is_a?(Regexp)
raise ArgumentError, "A regular expression must be supplied as the :without option of the configuration hash"
end
- if configuration[:with]
- validates_each(attr_names, configuration) do |record, attr_name, value|
- record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value) if value.to_s !~ configuration[:with]
- end
- elsif configuration[:without]
- validates_each(attr_names, configuration) do |record, attr_name, value|
- record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value) if value.to_s =~ configuration[:without]
- end
- end
+ validates_with FormatValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index 0d7dc5cd64..a122e9e737 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -1,5 +1,17 @@
module ActiveModel
module Validations
+ class InclusionValidator < EachValidator
+ def check_validity!
+ raise ArgumentError, "An object with the method include? is required must be supplied as the " <<
+ ":in option of the configuration hash" unless options[:in].respond_to?(:include?)
+ end
+
+ def validate_each(record, attribute, value)
+ return if options[:in].include?(value)
+ record.errors.add(attribute, :inclusion, :default => options[:message], :value => value)
+ end
+ end
+
module ClassMethods
# Validates whether the value of the specified attribute is available in a particular enumerable object.
#
@@ -21,17 +33,9 @@ module ActiveModel
# 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_inclusion_of(*attr_names)
- configuration = attr_names.extract_options!
-
- enum = configuration[:in] || configuration[:within]
-
- raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
-
- validates_each(attr_names, configuration) do |record, attr_name, value|
- unless enum.include?(value)
- record.errors.add(attr_name, :inclusion, :default => configuration[:message], :value => value)
- end
- end
+ options = attr_names.extract_options!
+ options[:in] ||= options.delete(:within)
+ validates_with InclusionValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index 6227239c9b..5db2060fe5 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -1,7 +1,75 @@
module ActiveModel
module Validations
+ class LengthValidator < EachValidator
+ OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
+ MESSAGES = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze
+ CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
+
+ DEFAULT_TOKENIZER = lambda { |value| value.split(//) }
+ attr_reader :type
+
+ def initialize(options)
+ @type = (OPTIONS & options.keys).first
+ super(options.reverse_merge(:tokenizer => DEFAULT_TOKENIZER))
+ end
+
+ def check_validity!
+ ensure_one_range_option!
+ ensure_argument_types!
+ end
+
+ def validate_each(record, attribute, value)
+ checks = options.slice(:minimum, :maximum, :is)
+ value = options[:tokenizer].call(value) if value.kind_of?(String)
+
+ if [:within, :in].include?(type)
+ range = options[type]
+ checks[:minimum], checks[:maximum] = range.begin, range.end
+ checks[:maximum] -= 1 if range.exclude_end?
+ end
+
+ checks.each do |key, check_value|
+ custom_message = options[:message] || options[MESSAGES[key]]
+ validity_check = CHECKS[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
+
+ record.errors.add(attribute, MESSAGES[key], :default => custom_message, :count => check_value) unless valid_value
+ end
+ end
+
+ protected
+
+ def ensure_one_range_option! #:nodoc:
+ range_options = OPTIONS & options.keys
+
+ case range_options.size
+ when 0
+ raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
+ when 1
+ # Valid number of options; do nothing.
+ else
+ raise ArgumentError, 'Too many range options specified. Choose only one.'
+ end
+ end
+
+ def ensure_argument_types! #:nodoc:
+ value = options[type]
+
+ case type
+ when :within, :in
+ raise ArgumentError, ":#{type} must be a Range" unless value.is_a?(Range)
+ when :is, :minimum, :maximum
+ raise ArgumentError, ":#{type} must be a nonnegative Integer" unless value.is_a?(Integer) && value >= 0
+ end
+ end
+ end
+
module ClassMethods
- ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
# Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
#
@@ -38,62 +106,9 @@ module ActiveModel
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
# count words as in above example.)
# Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
- def validates_length_of(*attrs)
- # Merge given options with defaults.
- options = { :tokenizer => lambda {|value| value.split(//)} }
- options.update(attrs.extract_options!.symbolize_keys)
-
- # Ensure that one and only one range option is specified.
- range_options = ALL_RANGE_OPTIONS & options.keys
- case range_options.size
- when 0
- raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
- when 1
- # Valid number of options; do nothing.
- else
- raise ArgumentError, 'Too many range options specified. Choose only one.'
- end
-
- # Get range option and value.
- option = range_options.first
- option_value = options[range_options.first]
- key = {:is => :wrong_length, :minimum => :too_short, :maximum => :too_long}[option]
- custom_message = options[:message] || options[key]
-
- case option
- when :within, :in
- raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
-
- validates_each(attrs, options) do |record, attr, value|
- value = options[:tokenizer].call(value) if value.kind_of?(String)
-
- min, max = option_value.begin, option_value.end
- max = max - 1 if option_value.exclude_end?
-
- if value.nil? || value.size < min
- record.errors.add(attr, :too_short, :default => custom_message || options[:too_short], :count => min)
- elsif value.size > max
- record.errors.add(attr, :too_long, :default => custom_message || options[:too_long], :count => max)
- end
- end
- when :is, :minimum, :maximum
- raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
-
- # Declare different validations per option.
- validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
-
- validates_each(attrs, options) do |record, attr, value|
- value = options[:tokenizer].call(value) if value.kind_of?(String)
-
- valid_value = if option == :maximum
- value.nil? || value.size.send(validity_checks[option], option_value)
- else
- value && value.size.send(validity_checks[option], option_value)
- end
-
- record.errors.add(attr, key, :default => custom_message, :count => option_value) unless valid_value
- end
- end
+ def validates_length_of(*attr_names)
+ options = attr_names.extract_options!
+ validates_with LengthValidator, options.merge(:attributes => attr_names)
end
alias_method :validates_size_of, :validates_length_of
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 32dbcd82d0..f2aab8c5b8 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -1,10 +1,68 @@
module ActiveModel
module Validations
- module ClassMethods
- ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
- :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
- :odd => 'odd?', :even => 'even?' }.freeze
+ class NumericalityValidator < EachValidator
+ CHECKS = { :greater_than => :>, :greater_than_or_equal_to => :>=,
+ :equal_to => :==, :less_than => :<, :less_than_or_equal_to => :<=,
+ :odd => :odd?, :even => :even? }.freeze
+
+ def initialize(options)
+ super(options.reverse_merge(:only_integer => false, :allow_nil => false))
+ end
+
+ def check_validity!
+ options.slice(*CHECKS.keys) do |option, value|
+ next if [:odd, :even].include?(option)
+ raise ArgumentError, ":#{option} must be a number, a symbol or a proc" unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
+ end
+ end
+
+ 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 ||= value
+
+ return if options[:allow_nil] && raw_value.nil?
+
+ unless value = parse_raw_value(raw_value, options)
+ record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => options[:message])
+ return
+ end
+
+ options.slice(*CHECKS.keys).each do |option, option_value|
+ case option
+ when :odd, :even
+ unless value.to_i.send(CHECKS[option])
+ record.errors.add(attr_name, option, :value => value, :default => options[:message])
+ end
+ else
+ option_value = option_value.call(record) if option_value.is_a?(Proc)
+ option_value = record.send(option_value) if option_value.is_a?(Symbol)
+
+ unless value.send(CHECKS[option], option_value)
+ record.errors.add(attr_name, option, :default => options[:message], :value => value, :count => option_value)
+ end
+ end
+ end
+ end
+
+ protected
+
+ def parse_raw_value(raw_value, options)
+ if options[:only_integer]
+ raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\Z/
+ else
+ begin
+ Kernel.Float(raw_value)
+ rescue ArgumentError, TypeError
+ nil
+ end
+ end
+ end
+ end
+
+ module ClassMethods
# Validates whether the value of the specified attribute is numeric by trying to convert it to
# a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
@@ -44,61 +102,9 @@ module ActiveModel
# validates_numericality_of :width, :greater_than => :minimum_weight
# end
#
- #
-
def validates_numericality_of(*attr_names)
- configuration = { :only_integer => false, :allow_nil => false }
- configuration.update(attr_names.extract_options!)
-
- numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
-
- (numericality_options - [ :odd, :even ]).each do |option|
- value = configuration[option]
- raise ArgumentError, ":#{option} must be a number, a symbol or a proc" unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
- end
-
- validates_each(attr_names,configuration) do |record, attr_name, value|
- before_type_cast = "#{attr_name}_before_type_cast"
-
- if record.respond_to?(before_type_cast.to_sym)
- raw_value = record.send("#{attr_name}_before_type_cast") || value
- else
- raw_value = value
- end
-
- next if configuration[:allow_nil] and raw_value.nil?
-
- if configuration[:only_integer]
- unless raw_value.to_s =~ /\A[+-]?\d+\Z/
- record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
- next
- end
- raw_value = raw_value.to_i
- else
- begin
- raw_value = Kernel.Float(raw_value)
- rescue ArgumentError, TypeError
- record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
- next
- end
- end
-
- numericality_options.each do |option|
- case option
- when :odd, :even
- unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
- record.errors.add(attr_name, option, :value => raw_value, :default => configuration[:message])
- end
- else
- configuration[option] = configuration[option].call(record) if configuration[option].is_a? Proc
- configuration[option] = record.method(configuration[option]).call if configuration[option].is_a? Symbol
-
- unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
- record.errors.add(attr_name, option, :default => configuration[:message], :value => raw_value, :count => configuration[option])
- end
- end
- end
- end
+ options = attr_names.extract_options!
+ validates_with NumericalityValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activemodel/lib/active_model/validations/presence.rb b/activemodel/lib/active_model/validations/presence.rb
index 3ff677c137..a4c6f866a7 100644
--- a/activemodel/lib/active_model/validations/presence.rb
+++ b/activemodel/lib/active_model/validations/presence.rb
@@ -2,6 +2,12 @@ require 'active_support/core_ext/object/blank'
module ActiveModel
module Validations
+ class PresenceValidator < EachValidator
+ def validate(record)
+ record.errors.add_on_blank(attributes, options[:message])
+ end
+ end
+
module ClassMethods
# Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
#
@@ -28,13 +34,8 @@ module ActiveModel
# The method, proc or string should return or evaluate to a true or false value.
#
def validates_presence_of(*attr_names)
- configuration = attr_names.extract_options!
-
- # can't use validates_each here, because it cannot cope with nonexistent attributes,
- # while errors.add_on_empty can
- validate configuration do |record|
- record.errors.add_on_blank(attr_names, configuration[:message])
- end
+ options = attr_names.extract_options!
+ validates_with PresenceValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index edc2133ddc..8d521173c6 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -48,14 +48,9 @@ module ActiveModel
# end
# end
#
- def validates_with(*args)
- configuration = args.extract_options!
-
- validate configuration do |record|
- args.each do |klass|
- klass.new(record, configuration.except(:on, :if, :unless)).validate
- end
- end
+ def validates_with(*args, &block)
+ options = args.extract_options!
+ args.each { |klass| validate(klass.new(options, &block), options) }
end
end
end
diff --git a/activemodel/lib/active_model/validations_repair_helper.rb b/activemodel/lib/active_model/validations_repair_helper.rb
deleted file mode 100644
index 40741e6dbe..0000000000
--- a/activemodel/lib/active_model/validations_repair_helper.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-module ActiveModel
- module ValidationsRepairHelper
- extend ActiveSupport::Concern
-
- module ClassMethods
- def repair_validations(*model_classes)
- setup do
- @_stored_callbacks = {}
- model_classes.each do |k|
- @_stored_callbacks[k] = k._validate_callbacks.dup
- end
- end
- teardown do
- model_classes.each do |k|
- k._validate_callbacks = @_stored_callbacks[k]
- k.__update_callbacks(:validate)
- end
- end
- end
- end
-
- def repair_validations(*model_classes, &block)
- @__stored_callbacks = {}
- model_classes.each do |k|
- @__stored_callbacks[k] = k._validate_callbacks.dup
- end
- return block.call
- ensure
- model_classes.each do |k|
- k._validate_callbacks = @__stored_callbacks[k]
- k.__update_callbacks(:validate)
- end
- end
- end
-end
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
index 09de72b757..01695cb73a 100644
--- a/activemodel/lib/active_model/validator.rb
+++ b/activemodel/lib/active_model/validator.rb
@@ -1,5 +1,4 @@
module ActiveModel #:nodoc:
-
# A simple base class that can be used along with ActiveModel::Base.validates_with
#
# class Person < ActiveModel::Base
@@ -52,17 +51,60 @@ module ActiveModel #:nodoc:
# @my_custom_field = options[:field_name] || :first_name
# end
# end
- #
class Validator
- attr_reader :record, :options
+ attr_reader :options
- def initialize(record, options)
- @record = record
+ def initialize(options)
@options = options
end
- def validate
- raise "You must override this method"
+ def validate(record)
+ raise NotImplementedError
+ end
+ end
+
+ # EachValidator is a validator which iterates through the attributes given
+ # in the options hash invoking the validate_each method passing in the
+ # record, attribute and value.
+ #
+ # All ActiveModel validations are built on top of this Validator.
+ class EachValidator < Validator
+ attr_reader :attributes
+
+ def initialize(options)
+ @attributes = Array(options.delete(:attributes))
+ raise ":attributes cannot be blank" if @attributes.empty?
+ super
+ check_validity!
+ end
+
+ def validate(record)
+ attributes.each do |attribute|
+ value = record.send(:read_attribute_for_validation, attribute)
+ next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
+ validate_each(record, attribute, value)
+ end
+ end
+
+ def validate_each(record, attribute, value)
+ raise NotImplementedError
+ end
+
+ def check_validity!
+ end
+ end
+
+ # BlockValidator is a special EachValidator which receives a block on initialization
+ # and call this block for each attribute being validated. +validates_each+ uses this
+ # Validator.
+ class BlockValidator < EachValidator
+ def initialize(options, &block)
+ @block = block
+ super
+ end
+
+ def validate_each(record, attribute, value)
+ @block.call(record, attribute, value)
end
end
end
diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
new file mode 100644
index 0000000000..b996f51d6b
--- /dev/null
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -0,0 +1,70 @@
+require "cases/helper"
+
+class CallbacksTest < ActiveModel::TestCase
+
+ class CallbackValidator
+ def around_create(model)
+ model.callbacks << :before_around_create
+ yield
+ model.callbacks << :after_around_create
+ end
+ end
+
+ class ModelCallbacks
+ attr_reader :callbacks
+ extend ActiveModel::Callbacks
+
+ define_model_callbacks :create
+ define_model_callbacks :initialize, :only => :after
+
+ before_create :before_create
+ around_create CallbackValidator.new
+
+ after_create do |model|
+ model.callbacks << :after_create
+ end
+
+ after_create "@callbacks << :final_callback"
+
+ def initialize(valid=true)
+ @callbacks, @valid = [], valid
+ end
+
+ def before_create
+ @callbacks << :before_create
+ end
+
+ def create
+ _run_create_callbacks do
+ @callbacks << :create
+ @valid
+ end
+ end
+ end
+
+ test "complete callback chain" do
+ model = ModelCallbacks.new
+ model.create
+ assert_equal model.callbacks, [ :before_create, :before_around_create, :create,
+ :after_around_create, :after_create, :final_callback]
+ end
+
+ test "after callbacks are always appended" do
+ model = ModelCallbacks.new
+ model.create
+ assert_equal model.callbacks.last, :final_callback
+ end
+
+ test "after callbacks are not executed if the block returns false" do
+ model = ModelCallbacks.new(false)
+ model.create
+ assert_equal model.callbacks, [ :before_create, :before_around_create,
+ :create, :after_around_create]
+ end
+
+ test "only selects which types of callbacks should be created" do
+ assert !ModelCallbacks.respond_to?(:before_initialize)
+ assert !ModelCallbacks.respond_to?(:around_initialize)
+ assert ModelCallbacks.respond_to?(:after_initialize)
+ end
+end
diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb
index c1a3f6a4a7..30193956ea 100644
--- a/activemodel/test/cases/helper.rb
+++ b/activemodel/test/cases/helper.rb
@@ -1,15 +1,14 @@
-root = File.expand_path('../../../..', __FILE__)
begin
- require "#{root}/vendor/gems/environment"
+ require File.expand_path('../../../../vendor/gems/environment', __FILE__)
rescue LoadError
- $:.unshift("#{root}/activesupport/lib")
end
-lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib")
+lib = File.expand_path('../../../lib', __FILE__)
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'config'
require 'active_model'
+require 'active_model/test_case'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
diff --git a/activemodel/test/cases/lint_test.rb b/activemodel/test/cases/lint_test.rb
index da7d2112dc..63804004ee 100644
--- a/activemodel/test/cases/lint_test.rb
+++ b/activemodel/test/cases/lint_test.rb
@@ -4,6 +4,8 @@ class LintTest < ActiveModel::TestCase
include ActiveModel::Lint::Tests
class CompliantModel
+ extend ActiveModel::Naming
+
def to_model
self
end
diff --git a/activemodel/test/cases/naming_test.rb b/activemodel/test/cases/naming_test.rb
index fe1ea36450..dc39b84ed8 100644
--- a/activemodel/test/cases/naming_test.rb
+++ b/activemodel/test/cases/naming_test.rb
@@ -1,8 +1,9 @@
require 'cases/helper'
+require 'models/track_back'
class NamingTest < ActiveModel::TestCase
def setup
- @model_name = ActiveModel::Name.new(self, 'Post::TrackBack')
+ @model_name = ActiveModel::Name.new(Post::TrackBack)
end
def test_singular
diff --git a/activemodel/test/cases/tests_database.rb b/activemodel/test/cases/tests_database.rb
index 8dd00ea147..79668dd941 100644
--- a/activemodel/test/cases/tests_database.rb
+++ b/activemodel/test/cases/tests_database.rb
@@ -2,6 +2,7 @@ require 'logger'
$:.unshift(File.dirname(__FILE__) + '/../../../activerecord/lib')
require 'active_record'
+require 'active_record/test_case'
require 'active_record/fixtures'
module ActiveModel
diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb
index d171784963..bfc1ca12e6 100644
--- a/activemodel/test/cases/translation_test.rb
+++ b/activemodel/test/cases/translation_test.rb
@@ -1,11 +1,5 @@
require 'cases/helper'
-
-class SuperUser
- extend ActiveModel::Translation
-end
-
-class User < SuperUser
-end
+require 'models/person'
class ActiveModelI18nTests < ActiveModel::TestCase
@@ -14,38 +8,38 @@ class ActiveModelI18nTests < ActiveModel::TestCase
end
def test_translated_model_attributes
- I18n.backend.store_translations 'en', :activemodel => {:attributes => {:super_user => {:name => 'super_user name attribute'} } }
- assert_equal 'super_user name attribute', SuperUser.human_attribute_name('name')
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
+ assert_equal 'person name attribute', Person.human_attribute_name('name')
end
def test_translated_model_attributes_with_symbols
- I18n.backend.store_translations 'en', :activemodel => {:attributes => {:super_user => {:name => 'super_user name attribute'} } }
- assert_equal 'super_user name attribute', SuperUser.human_attribute_name(:name)
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
+ assert_equal 'person name attribute', Person.human_attribute_name(:name)
end
def test_translated_model_attributes_with_ancestor
- I18n.backend.store_translations 'en', :activemodel => {:attributes => {:user => {:name => 'user name attribute'} } }
- assert_equal 'user name attribute', User.human_attribute_name('name')
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:child => {:name => 'child name attribute'} } }
+ assert_equal 'child name attribute', Child.human_attribute_name('name')
end
def test_translated_model_attributes_with_ancestors_fallback
- I18n.backend.store_translations 'en', :activemodel => {:attributes => {:super_user => {:name => 'super_user name attribute'} } }
- assert_equal 'super_user name attribute', User.human_attribute_name('name')
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
+ assert_equal 'person name attribute', Child.human_attribute_name('name')
end
def test_translated_model_names
- I18n.backend.store_translations 'en', :activemodel => {:models => {:super_user => 'super_user model'} }
- assert_equal 'super_user model', SuperUser.model_name.human
+ I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
+ assert_equal 'person model', Person.model_name.human
end
def test_translated_model_names_with_sti
- I18n.backend.store_translations 'en', :activemodel => {:models => {:user => 'user model'} }
- assert_equal 'user model', User.model_name.human
+ I18n.backend.store_translations 'en', :activemodel => {:models => {:child => 'child model'} }
+ assert_equal 'child model', Child.model_name.human
end
def test_translated_model_names_with_ancestors_fallback
- I18n.backend.store_translations 'en', :activemodel => {:models => {:super_user => 'super_user model'} }
- assert_equal 'super_user model', User.model_name.human
+ I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
+ assert_equal 'person model', Child.model_name.human
end
end
diff --git a/activemodel/test/cases/validations/acceptance_validation_test.rb b/activemodel/test/cases/validations/acceptance_validation_test.rb
index 88e5fdb358..11c9c1edfd 100644
--- a/activemodel/test/cases/validations/acceptance_validation_test.rb
+++ b/activemodel/test/cases/validations/acceptance_validation_test.rb
@@ -9,9 +9,10 @@ require 'models/person'
class AcceptanceValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_terms_of_service_agreement_no_acceptance
Topic.validates_acceptance_of(:terms_of_service, :on => :create)
@@ -53,28 +54,18 @@ class AcceptanceValidationTest < ActiveModel::TestCase
assert t.save
end
- def test_validates_acceptance_of_with_custom_error_using_quotes
- repair_validations(Developer) do
- Developer.validates_acceptance_of :salary, :message=> "This string contains 'single' and \"double\" quotes"
- d = Developer.new
- d.salary = "0"
- assert !d.valid?
- assert_equal "This string contains 'single' and \"double\" quotes", d.errors[:salary].last
- end
- end
-
def test_validates_acceptance_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_acceptance_of :karma
+ Person.validates_acceptance_of :karma
- p = Person.new
- p.karma = ""
+ p = Person.new
+ p.karma = ""
- assert p.invalid?
- assert_equal ["must be accepted"], p.errors[:karma]
+ assert p.invalid?
+ assert_equal ["must be accepted"], p.errors[:karma]
- p.karma = "1"
- assert p.valid?
- end
+ p.karma = "1"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
end
diff --git a/activemodel/test/cases/validations/conditional_validation_test.rb b/activemodel/test/cases/validations/conditional_validation_test.rb
index 4c716d5d48..5260162a58 100644
--- a/activemodel/test/cases/validations/conditional_validation_test.rb
+++ b/activemodel/test/cases/validations/conditional_validation_test.rb
@@ -6,9 +6,10 @@ require 'models/topic'
class ConditionalValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_if_validation_using_method_true
# When the method returns true
diff --git a/activemodel/test/cases/validations/confirmation_validation_test.rb b/activemodel/test/cases/validations/confirmation_validation_test.rb
index 1d6f2a6ec5..55554d5054 100644
--- a/activemodel/test/cases/validations/confirmation_validation_test.rb
+++ b/activemodel/test/cases/validations/confirmation_validation_test.rb
@@ -8,9 +8,10 @@ require 'models/person'
class ConfirmationValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_no_title_confirmation
Topic.validates_confirmation_of(:title)
@@ -39,30 +40,19 @@ class ConfirmationValidationTest < ActiveModel::TestCase
assert t.save
end
- def test_validates_confirmation_of_with_custom_error_using_quotes
- repair_validations(Developer) do
- Developer.validates_confirmation_of :name, :message=> "confirm 'single' and \"double\" quotes"
- d = Developer.new
- d.name = "John"
- d.name_confirmation = "Johnny"
- assert !d.valid?
- assert_equal ["confirm 'single' and \"double\" quotes"], d.errors[:name]
- end
- end
-
def test_validates_confirmation_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_confirmation_of :karma
+ Person.validates_confirmation_of :karma
- p = Person.new
- p.karma_confirmation = "None"
- assert p.invalid?
+ p = Person.new
+ p.karma_confirmation = "None"
+ assert p.invalid?
- assert_equal ["doesn't match confirmation"], p.errors[:karma]
+ assert_equal ["doesn't match confirmation"], p.errors[:karma]
- p.karma = "None"
- assert p.valid?
- end
+ p.karma = "None"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
end
diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb
index 584f009e84..7d851f546c 100644
--- a/activemodel/test/cases/validations/exclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/exclusion_validation_test.rb
@@ -7,9 +7,10 @@ require 'models/person'
class ExclusionValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_validates_exclusion_of
Topic.validates_exclusion_of( :title, :in => %w( abe monkey ) )
@@ -30,17 +31,17 @@ class ExclusionValidationTest < ActiveModel::TestCase
end
def test_validates_exclusion_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_exclusion_of :karma, :in => %w( abe monkey )
+ Person.validates_exclusion_of :karma, :in => %w( abe monkey )
- p = Person.new
- p.karma = "abe"
- assert p.invalid?
+ p = Person.new
+ p.karma = "abe"
+ assert p.invalid?
- assert_equal ["is reserved"], p.errors[:karma]
+ assert_equal ["is reserved"], p.errors[:karma]
- p.karma = "Lifo"
- assert p.valid?
- end
+ p.karma = "Lifo"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
end
diff --git a/activemodel/test/cases/validations/format_validation_test.rb b/activemodel/test/cases/validations/format_validation_test.rb
index e19e4bf7b3..e10089208a 100644
--- a/activemodel/test/cases/validations/format_validation_test.rb
+++ b/activemodel/test/cases/validations/format_validation_test.rb
@@ -8,9 +8,10 @@ require 'models/person'
class PresenceValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_validate_format
Topic.validates_format_of(:title, :content, :with => /^Validation\smacros \w+!$/, :message => "is bad data")
@@ -100,28 +101,18 @@ class PresenceValidationTest < ActiveModel::TestCase
assert_raise(ArgumentError) { Topic.validates_format_of(:title, :without => "clearly not a regexp") }
end
- def test_validates_format_of_with_custom_error_using_quotes
- repair_validations(Developer) do
- Developer.validates_format_of :name, :with => /^(A-Z*)$/, :message=> "format 'single' and \"double\" quotes"
- d = Developer.new
- d.name = d.name_confirmation = "John 32"
- assert !d.valid?
- assert_equal ["format 'single' and \"double\" quotes"], d.errors[:name]
- end
- end
-
def test_validates_format_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_format_of :karma, :with => /\A\d+\Z/
+ Person.validates_format_of :karma, :with => /\A\d+\Z/
- p = Person.new
- p.karma = "Pixies"
- assert p.invalid?
+ p = Person.new
+ p.karma = "Pixies"
+ assert p.invalid?
- assert_equal ["is invalid"], p.errors[:karma]
+ assert_equal ["is invalid"], p.errors[:karma]
- p.karma = "1234"
- assert p.valid?
- end
+ p.karma = "1234"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
end
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
index 68b1b27f75..a7656fe219 100644
--- a/activemodel/test/cases/validations/i18n_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -1,6 +1,5 @@
require "cases/helper"
require 'cases/tests_database'
-
require 'models/person'
class I18nValidationTest < ActiveModel::TestCase
@@ -22,20 +21,6 @@ class I18nValidationTest < ActiveModel::TestCase
I18n.backend = @old_backend
end
- def test_percent_s_interpolation_syntax_in_error_messages_was_deprecated
- assert_not_deprecated do
- default = "%s interpolation syntax was deprecated"
- assert_equal default, I18n.t(:does_not_exist, :default => default, :value => 'this')
- end
- end
-
- def test_percent_d_interpolation_syntax_in_error_messages_was_deprecated
- assert_not_deprecated do
- default = "%d interpolation syntaxes are deprecated"
- assert_equal default, I18n.t(:does_not_exist, :default => default, :count => 2)
- end
- end
-
def test_errors_add_on_empty_generates_message
@person.errors.expects(:generate_message).with(:title, :empty, {:default => nil})
@person.errors.add_on_empty :title
@@ -58,10 +43,16 @@ class I18nValidationTest < ActiveModel::TestCase
def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
@person.errors.add('name', 'empty')
- I18n.expects(:translate).with(:"person.name", :default => ['Name'], :scope => [:activemodel, :attributes], :count => 1).returns('Name')
+ I18n.expects(:translate).with(:"person.name", :default => ['Name', 'Name'], :scope => [:activemodel, :attributes], :count => 1).returns('Name')
@person.errors.full_messages
end
+ def test_errors_full_messages_uses_format
+ I18n.backend.store_translations('en', :activemodel => {:errors => {:format => "Field {{attribute}} {{message}}"}})
+ @person.errors.add('name', 'empty')
+ assert_equal ["Field Name empty"], @person.errors.full_messages
+ end
+
# ActiveRecord::Validations
# validates_confirmation_of w/ mocha
def test_validates_confirmation_of_generates_message
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index bc1b0365d2..6b2bcd9c60 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -8,9 +8,10 @@ require 'models/person'
class InclusionValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_validates_inclusion_of
Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
@@ -53,28 +54,18 @@ class InclusionValidationTest < ActiveModel::TestCase
assert_equal ["option uhoh is not in the list"], t.errors[:title]
end
- def test_validates_inclusion_of_with_custom_error_using_quotes
- repair_validations(Developer) do
- Developer.validates_inclusion_of :salary, :in => 1000..80000, :message=> "This string contains 'single' and \"double\" quotes"
- d = Developer.new
- d.salary = "90,000"
- assert !d.valid?
- assert_equal "This string contains 'single' and \"double\" quotes", d.errors[:salary].last
- end
- end
-
def test_validates_inclusion_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_inclusion_of :karma, :in => %w( abe monkey )
+ Person.validates_inclusion_of :karma, :in => %w( abe monkey )
- p = Person.new
- p.karma = "Lifo"
- assert p.invalid?
+ p = Person.new
+ p.karma = "Lifo"
+ assert p.invalid?
- assert_equal ["is not included in the list"], p.errors[:karma]
+ assert_equal ["is not included in the list"], p.errors[:karma]
- p.karma = "monkey"
- assert p.valid?
- end
+ p.karma = "monkey"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
end
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
index 2c97b762f1..f3ef5e648a 100644
--- a/activemodel/test/cases/validations/length_validation_test.rb
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -8,9 +8,10 @@ require 'models/person'
class LengthValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_validates_length_of_with_allow_nil
Topic.validates_length_of( :title, :is => 5, :allow_nil=>true )
@@ -419,48 +420,18 @@ class LengthValidationTest < ActiveModel::TestCase
assert_equal ["Your essay must be at least 5 words."], t.errors[:content]
end
- def test_validates_length_of_with_custom_too_long_using_quotes
- repair_validations(Developer) do
- Developer.validates_length_of :name, :maximum => 4, :too_long=> "This string contains 'single' and \"double\" quotes"
- d = Developer.new
- d.name = "Jeffrey"
- assert !d.valid?
- assert_equal ["This string contains 'single' and \"double\" quotes"], d.errors[:name]
- end
- end
-
- def test_validates_length_of_with_custom_too_short_using_quotes
- repair_validations(Developer) do
- Developer.validates_length_of :name, :minimum => 4, :too_short=> "This string contains 'single' and \"double\" quotes"
- d = Developer.new
- d.name = "Joe"
- assert !d.valid?
- assert_equal ["This string contains 'single' and \"double\" quotes"], d.errors[:name]
- end
- end
-
- def test_validates_length_of_with_custom_message_using_quotes
- repair_validations(Developer) do
- Developer.validates_length_of :name, :minimum => 4, :message=> "This string contains 'single' and \"double\" quotes"
- d = Developer.new
- d.name = "Joe"
- assert !d.valid?
- assert_equal ["This string contains 'single' and \"double\" quotes"], d.errors[:name]
- end
- end
-
def test_validates_length_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_length_of :karma, :minimum => 5
+ Person.validates_length_of :karma, :minimum => 5
- p = Person.new
- p.karma = "Pix"
- assert p.invalid?
+ p = Person.new
+ p.karma = "Pix"
+ assert p.invalid?
- assert_equal ["is too short (minimum is 5 characters)"], p.errors[:karma]
+ assert_equal ["is too short (minimum is 5 characters)"], p.errors[:karma]
- p.karma = "The Smiths"
- assert p.valid?
- end
+ p.karma = "The Smiths"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
end
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
index d3201966dc..75cd654f98 100644
--- a/activemodel/test/cases/validations/numericality_validation_test.rb
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -8,9 +8,10 @@ require 'models/person'
class NumericalityValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
NIL = [nil]
BLANK = ["", " ", " \t \r \n"]
@@ -138,37 +139,19 @@ class NumericalityValidationTest < ActiveModel::TestCase
assert_equal ["greater than 4"], topic.errors[:approved]
end
- def test_numericality_with_getter_method
- repair_validations(Developer) do
- Developer.validates_numericality_of( :salary )
- developer = Developer.new("name" => "michael", "salary" => nil)
- developer.instance_eval("def salary; read_attribute('salary') ? read_attribute('salary') : 100000; end")
- assert developer.valid?
- end
- end
-
- def test_numericality_with_allow_nil_and_getter_method
- repair_validations(Developer) do
- Developer.validates_numericality_of( :salary, :allow_nil => true)
- developer = Developer.new("name" => "michael", "salary" => nil)
- developer.instance_eval("def salary; read_attribute('salary') ? read_attribute('salary') : 100000; end")
- assert developer.valid?
- end
- end
-
def test_validates_numericality_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_numericality_of :karma, :allow_nil => false
+ Person.validates_numericality_of :karma, :allow_nil => false
- p = Person.new
- p.karma = "Pix"
- assert p.invalid?
+ p = Person.new
+ p.karma = "Pix"
+ assert p.invalid?
- assert_equal ["is not a number"], p.errors[:karma]
+ assert_equal ["is not a number"], p.errors[:karma]
- p.karma = "1234"
- assert p.valid?
- end
+ p.karma = "1234"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
private
diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb
index 90b0951a77..8b9795a90c 100644
--- a/activemodel/test/cases/validations/presence_validation_test.rb
+++ b/activemodel/test/cases/validations/presence_validation_test.rb
@@ -9,9 +9,6 @@ require 'models/custom_reader'
class PresenceValidationTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
-
- repair_validations(Topic)
def test_validate_presences
Topic.validates_presence_of(:title, :content)
@@ -30,43 +27,44 @@ class PresenceValidationTest < ActiveModel::TestCase
t.content = "like stuff"
assert t.save
+ ensure
+ Topic.reset_callbacks(:validate)
end
- # def test_validates_presence_of_with_custom_message_using_quotes
- # repair_validations(Developer) do
- # Developer.validates_presence_of :non_existent, :message=> "This string contains 'single' and \"double\" quotes"
- # d = Developer.new
- # d.name = "Joe"
- # assert !d.valid?
- # assert_equal ["This string contains 'single' and \"double\" quotes"], d.errors[:non_existent]
- # end
- # end
+ def test_validates_acceptance_of_with_custom_error_using_quotes
+ Person.validates_presence_of :karma, :message=> "This string contains 'single' and \"double\" quotes"
+ p = Person.new
+ assert !p.valid?
+ assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
+ ensure
+ Person.reset_callbacks(:validate)
+ end
def test_validates_presence_of_for_ruby_class
- repair_validations(Person) do
- Person.validates_presence_of :karma
+ Person.validates_presence_of :karma
- p = Person.new
- assert p.invalid?
+ p = Person.new
+ assert p.invalid?
- assert_equal ["can't be blank"], p.errors[:karma]
+ assert_equal ["can't be blank"], p.errors[:karma]
- p.karma = "Cold"
- assert p.valid?
- end
+ p.karma = "Cold"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
end
def test_validates_presence_of_for_ruby_class_with_custom_reader
- repair_validations(Person) do
- CustomReader.validates_presence_of :karma
+ CustomReader.validates_presence_of :karma
- p = CustomReader.new
- assert p.invalid?
+ p = CustomReader.new
+ assert p.invalid?
- assert_equal ["can't be blank"], p.errors[:karma]
+ assert_equal ["can't be blank"], p.errors[:karma]
- p[:karma] = "Cold"
- assert p.valid?
- end
+ p[:karma] = "Cold"
+ assert p.valid?
+ ensure
+ CustomReader.reset_callbacks(:validate)
end
end
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index fae87a6188..7540ccb580 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -6,38 +6,51 @@ require 'models/topic'
class ValidatesWithTest < ActiveRecord::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
ERROR_MESSAGE = "Validation error from validator"
OTHER_ERROR_MESSAGE = "Validation error from other validator"
class ValidatorThatAddsErrors < ActiveModel::Validator
- def validate()
+ def validate(record)
record.errors[:base] << ERROR_MESSAGE
end
end
class OtherValidatorThatAddsErrors < ActiveModel::Validator
- def validate()
+ def validate(record)
record.errors[:base] << OTHER_ERROR_MESSAGE
end
end
class ValidatorThatDoesNotAddErrors < ActiveModel::Validator
- def validate()
+ def validate(record)
end
end
class ValidatorThatValidatesOptions < ActiveModel::Validator
- def validate()
+ def validate(record)
if options[:field] == :first_name
record.errors[:base] << ERROR_MESSAGE
end
end
end
+ class ValidatorPerEachAttribute < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ record.errors[attribute] << "Value is #{value}"
+ end
+ end
+
+ class ValidatorCheckValidity < ActiveModel::EachValidator
+ def check_validity!
+ raise "boom!"
+ end
+ end
+
test "vaidation with class that adds errors" do
Topic.validates_with(ValidatorThatAddsErrors)
topic = Topic.new
@@ -98,11 +111,11 @@ class ValidatesWithTest < ActiveRecord::TestCase
assert topic.errors[:base].include?(ERROR_MESSAGE)
end
- test "passes all non-standard configuration options to the validator class" do
+ test "passes all configuration options to the validator class" do
topic = Topic.new
validator = mock()
- validator.expects(:new).with(topic, {:foo => :bar}).returns(validator)
- validator.expects(:validate)
+ validator.expects(:new).with(:foo => :bar, :if => "1 == 1").returns(validator)
+ validator.expects(:validate).with(topic)
Topic.validates_with(validator, :if => "1 == 1", :foo => :bar)
assert topic.valid?
@@ -115,4 +128,39 @@ class ValidatesWithTest < ActiveRecord::TestCase
assert topic.errors[:base].include?(ERROR_MESSAGE)
end
+ test "validates_with each validator" do
+ Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content])
+ topic = Topic.new :title => "Title", :content => "Content"
+ assert !topic.valid?
+ assert_equal ["Value is Title"], topic.errors[:title]
+ assert_equal ["Value is Content"], topic.errors[:content]
+ end
+
+ test "each validator checks validity" do
+ assert_raise RuntimeError do
+ Topic.validates_with(ValidatorCheckValidity, :attributes => [:title])
+ end
+ end
+
+ test "each validator expects attributes to be given" do
+ assert_raise RuntimeError do
+ Topic.validates_with(ValidatorPerEachAttribute)
+ end
+ end
+
+ test "each validator skip nil values if :allow_nil is set to true" do
+ Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content], :allow_nil => true)
+ topic = Topic.new :content => ""
+ assert !topic.valid?
+ assert topic.errors[:title].empty?
+ assert_equal ["Value is "], topic.errors[:content]
+ end
+
+ test "each validator skip blank values if :allow_blank is set to true" do
+ Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content], :allow_blank => true)
+ topic = Topic.new :content => ""
+ assert topic.valid?
+ assert topic.errors[:title].empty?
+ assert topic.errors[:content].empty?
+ end
end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index 78565177d8..38a2a716a7 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -9,11 +9,12 @@ require 'models/custom_reader'
class ValidationsTest < ActiveModel::TestCase
include ActiveModel::TestsDatabase
- include ActiveModel::ValidationsRepairHelper
# Most of the tests mess with the validations of Topic, so lets repair it all the time.
# Other classes we mess with will be dealt with in the specific tests
- repair_validations(Topic)
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
def test_single_field_validation
r = Reply.new
@@ -70,6 +71,12 @@ class ValidationsTest < ActiveModel::TestCase
assert_equal 2, r.errors.count
end
+ def test_errors_on_nested_attributes_expands_name
+ t = Topic.new
+ t.errors["replies.name"] << "can't be blank"
+ assert_equal ["Replies name can't be blank"], t.errors.full_messages
+ end
+
def test_errors_on_base
r = Reply.new
r.content = "Mismatch"
diff --git a/activemodel/test/models/person.rb b/activemodel/test/models/person.rb
index d98420f900..c83d768379 100644
--- a/activemodel/test/models/person.rb
+++ b/activemodel/test/models/person.rb
@@ -1,5 +1,9 @@
class Person
include ActiveModel::Validations
+ extend ActiveModel::Translation
- attr_accessor :title, :karma
+ attr_accessor :title, :karma, :salary
+end
+
+class Child < Person
end
diff --git a/activemodel/test/models/track_back.rb b/activemodel/test/models/track_back.rb
new file mode 100644
index 0000000000..d137e4ff8f
--- /dev/null
+++ b/activemodel/test/models/track_back.rb
@@ -0,0 +1,4 @@
+class Post
+ class TrackBack
+ end
+end \ No newline at end of file
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index d8bfb1916d..0cfd8cdc87 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -1,5 +1,113 @@
*Edge*
+* Add Relation#except. [Pratik Naik]
+
+ one_red_item = Item.where(:colour => 'red').limit(1)
+ all_items = one_red_item.except(:where, :limit)
+
+* Add Relation#delete_all. [Pratik Naik]
+
+ Item.where(:colour => 'red').delete_all
+
+* Add Model.having and Relation#having. [Pratik Naik]
+
+ Developer.group("salary").having("sum(salary) > 10000").select("salary")
+
+* Add Relation#count. [Pratik Naik]
+
+ legends = People.where("age > 100")
+ legends.count
+ legends.count(:age, :distinct => true)
+ legends.select('id').count
+
+* Add Model.readonly and association_collection#readonly finder method. [Pratik Naik]
+
+ Post.readonly.to_a # Load all posts in readonly mode
+ @user.items.readonly(false).to_a # Load all the user items in writable mode
+
+* Add .lock finder method [Pratik Naik]
+
+ User.lock.where(:name => 'lifo').to_a
+
+ old_items = Item.where("age > 100")
+ old_items.lock.each {|i| .. }
+
+* Add Model.from and association_collection#from finder methods [Pratik Naik]
+
+ user = User.scoped
+ user.select('*').from('users, items')
+
+* Add relation.destroy_all [Pratik Naik]
+
+ old_items = Item.where("age > 100")
+ old_items.destroy_all
+
+* Add relation.exists? [Pratik Naik]
+
+ red_items = Item.where(:colours => 'red')
+ red_items.exists?
+ red_items.exists?(1)
+
+* Add find(ids) to relations. [Pratik Naik]
+
+ old_users = User.order("age DESC")
+ old_users.find(1)
+ old_users.find(1, 2, 3)
+
+* Add new finder methods to association collection. [Pratik Naik]
+
+ class User < ActiveRecord::Base
+ has_many :items
+ end
+
+ user = User.first
+ user.items.where(:items => {:colour => 'red'})
+ user.items.select('items.id')
+
+* Add relation.reload to force reloading the records. [Pratik Naik]
+
+ topics = Topic.scoped
+ topics.to_a # force load
+ topics.first # returns a cached record
+ topics.reload
+ topics.first # Fetches a new record from the database
+
+* Rename Model.conditions and relation.conditions to .where. [Pratik Naik]
+
+ Before :
+ User.conditions(:name => 'lifo')
+ User.select('id').conditions(["age > ?", 21])
+
+ Now :
+ User.where(:name => 'lifo')
+ User.select('id').where(["age > ?", 21])
+
+* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. [Pratik Naik]
+
+ Examples :
+
+ posts = Post.select('id).order('name') # Returns a lazy relation
+ posts.each {|p| puts p.id } # Fires "select id from posts order by name"
+
+* Model.scoped now returns a relation if invoked without any arguments. [Pratik Naik]
+
+ Example :
+
+ posts = Post.scoped
+ posts.size # Fires "select count(*) from posts" and returns the count
+ posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
+
+* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 [Murray Steele]
+
+ # post.comments sets each comment's post without needing to :include
+ class Post < ActiveRecord::Base
+ has_many :comments, :inverse_of => :post
+ end
+
+* MySQL: add_ and change_column support positioning. #3286 [Ben Marini]
+
+* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 [Mike Breen, Gabe da Silveira]
+
* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git [Pratik Naik]
* PostgreSQL: XML datatype support. #1874 [Leonardo Borges]
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index 8195e78826..728dec8925 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -21,89 +21,118 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
-$:.unshift(activesupport_path) if File.directory?(activesupport_path)
-activemodel_path = "#{File.dirname(__FILE__)}/../../activemodel/lib"
-$:.unshift(activemodel_path) if File.directory?(activemodel_path)
+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'
require 'arel'
module ActiveRecord
- # TODO: Review explicit loads to see if they will automatically be handled by the initializer.
- def self.load_all!
- [Base, DynamicFinderMatch, ConnectionAdapters::AbstractAdapter]
- end
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :VERSION
+
+ autoload :ActiveRecordError, 'active_record/base'
+ autoload :ConnectionNotEstablished, 'active_record/base'
- autoload :VERSION, 'active_record/version'
-
- autoload :ActiveRecordError, 'active_record/base'
- autoload :ConnectionNotEstablished, 'active_record/base'
-
- autoload :Aggregations, 'active_record/aggregations'
- autoload :AssociationPreload, 'active_record/association_preload'
- autoload :Associations, 'active_record/associations'
- autoload :AttributeMethods, 'active_record/attribute_methods'
- autoload :Attributes, 'active_record/attributes'
- autoload :AutosaveAssociation, 'active_record/autosave_association'
- autoload :Relation, 'active_record/relation'
- autoload :Base, 'active_record/base'
- autoload :Batches, 'active_record/batches'
- autoload :Calculations, 'active_record/calculations'
- autoload :Callbacks, 'active_record/callbacks'
- autoload :DynamicFinderMatch, 'active_record/dynamic_finder_match'
- autoload :DynamicScopeMatch, 'active_record/dynamic_scope_match'
- autoload :Migration, 'active_record/migration'
- autoload :Migrator, 'active_record/migration'
- autoload :NamedScope, 'active_record/named_scope'
- autoload :NestedAttributes, 'active_record/nested_attributes'
- autoload :Observer, 'active_record/observer'
- autoload :QueryCache, 'active_record/query_cache'
- autoload :Reflection, 'active_record/reflection'
- autoload :Schema, 'active_record/schema'
- autoload :SchemaDumper, 'active_record/schema_dumper'
- autoload :Serialization, 'active_record/serialization'
- autoload :SessionStore, 'active_record/session_store'
- autoload :StateMachine, 'active_record/state_machine'
- autoload :TestCase, 'active_record/test_case'
- autoload :Timestamp, 'active_record/timestamp'
- autoload :Transactions, 'active_record/transactions'
- autoload :Types, 'active_record/types'
- autoload :Validations, 'active_record/validations'
+ autoload :Aggregations
+ autoload :AssociationPreload
+ autoload :Associations
+ autoload :AttributeMethods
+ autoload :Attributes
+ autoload :AutosaveAssociation
+
+ autoload :Relation
+
+ autoload_under 'relation' do
+ autoload :QueryMethods
+ autoload :FinderMethods
+ autoload :CalculationMethods
+ autoload :PredicateBuilder
+ autoload :SpawnMethods
+ end
+
+ autoload :Base
+ autoload :Batches
+ autoload :Calculations
+ autoload :Callbacks
+ autoload :DynamicFinderMatch
+ autoload :DynamicScopeMatch
+ autoload :Migration
+ autoload :Migrator, 'active_record/migration'
+ autoload :NamedScope
+ autoload :NestedAttributes
+ autoload :Observer
+ autoload :QueryCache
+ autoload :Reflection
+ autoload :Schema
+ autoload :SchemaDumper
+ autoload :Serialization
+ autoload :SessionStore
+ autoload :StateMachine
+ autoload :Timestamp
+ autoload :Transactions
+ autoload :Types
+ autoload :Validations
+ end
module AttributeMethods
- autoload :BeforeTypeCast, 'active_record/attribute_methods/before_type_cast'
- autoload :Dirty, 'active_record/attribute_methods/dirty'
- autoload :PrimaryKey, 'active_record/attribute_methods/primary_key'
- autoload :Query, 'active_record/attribute_methods/query'
- autoload :Read, 'active_record/attribute_methods/read'
- autoload :TimeZoneConversion, 'active_record/attribute_methods/time_zone_conversion'
- autoload :Write, 'active_record/attribute_methods/write'
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :BeforeTypeCast
+ autoload :Dirty
+ autoload :PrimaryKey
+ autoload :Query
+ autoload :Read
+ autoload :TimeZoneConversion
+ autoload :Write
+ end
end
module Attributes
- autoload :Aliasing, 'active_record/attributes/aliasing'
- autoload :Store, 'active_record/attributes/store'
- autoload :Typecasting, 'active_record/attributes/typecasting'
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Aliasing
+ autoload :Store
+ autoload :Typecasting
+ end
end
module Type
- autoload :Number, 'active_record/types/number'
- autoload :Object, 'active_record/types/object'
- autoload :Serialize, 'active_record/types/serialize'
- autoload :TimeWithZone, 'active_record/types/time_with_zone'
- autoload :Unknown, 'active_record/types/unknown'
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Number, 'active_record/types/number'
+ autoload :Object, 'active_record/types/object'
+ autoload :Serialize, 'active_record/types/serialize'
+ autoload :TimeWithZone, 'active_record/types/time_with_zone'
+ autoload :Unknown, 'active_record/types/unknown'
+ end
end
module Locking
- autoload :Optimistic, 'active_record/locking/optimistic'
- autoload :Pessimistic, 'active_record/locking/pessimistic'
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Optimistic
+ autoload :Pessimistic
+ end
end
module ConnectionAdapters
- autoload :AbstractAdapter, 'active_record/connection_adapters/abstract_adapter'
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :AbstractAdapter
+ end
end
end
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index d90dcf090e..149a11eb47 100755
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -1,9 +1,10 @@
require 'active_support/core_ext/module/delegation'
+require 'active_support/core_ext/enumerable'
module ActiveRecord
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
- def initialize(reflection)
- super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{reflection.class_name})")
+ def initialize(reflection, associated_class = nil)
+ super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})")
end
end
@@ -60,6 +61,12 @@ module ActiveRecord
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]}).")
+ end
+ end
+
class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc:
def initialize(reflection)
super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.")
@@ -1316,7 +1323,7 @@ module ActiveRecord
if association.nil? || force_reload
association = association_proxy_class.new(self, reflection)
- retval = association.reload
+ 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
@@ -1361,7 +1368,7 @@ module ActiveRecord
association_instance_set(reflection.name, association)
end
- association.reload if force_reload
+ reflection.klass.uncached { association.reload } if force_reload
association
end
@@ -1373,9 +1380,9 @@ module ActiveRecord
if reflection.through_reflection && reflection.source_reflection.belongs_to?
through = reflection.through_reflection
primary_key = reflection.source_reflection.primary_key_name
- send(through.name).all(:select => "DISTINCT #{through.quoted_table_name}.#{primary_key}").map!(&:"#{primary_key}")
+ send(through.name).select("DISTINCT #{through.quoted_table_name}.#{primary_key}").map!(&:"#{primary_key}")
else
- send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map!(&:id)
+ send(reflection.name).select("#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map!(&:id)
end
end
end
@@ -1394,8 +1401,8 @@ module ActiveRecord
end
define_method("#{reflection.name.to_s.singularize}_ids=") do |new_value|
- ids = (new_value || []).reject { |nid| nid.blank? }
- send("#{reflection.name}=", reflection.klass.find(ids))
+ ids = (new_value || []).reject { |nid| nid.blank? }.map(&:to_i)
+ send("#{reflection.name}=", reflection.klass.find(ids).index_by(&:id).values_at(*ids))
end
end
end
@@ -1456,12 +1463,10 @@ module ActiveRecord
after_destroy(method_name)
end
- def find_with_associations(options = {}, join_dependency = nil)
- catch :invalid_query do
- join_dependency ||= JoinDependency.new(self, merge_includes(scope(:find, :include), options[:include]), options[:joins])
- rows = select_all_rows(options, join_dependency)
- return join_dependency.instantiate(rows)
- end
+ def find_with_associations(options, join_dependency)
+ rows = select_all_rows(options, join_dependency)
+ join_dependency.instantiate(rows)
+ rescue ThrowResult
[]
end
@@ -1480,7 +1485,7 @@ module ActiveRecord
dependent_conditions = []
dependent_conditions << "#{reflection.primary_key_name} = \#{record.#{reflection.name}.send(:owner_quoted_id)}"
dependent_conditions << "#{reflection.options[:as]}_type = '#{base_class.name}'" if reflection.options[:as]
- dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.quoted_table_name) if reflection.options[:conditions]
+ dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.table_name) if reflection.options[:conditions]
dependent_conditions << extra_conditions if extra_conditions
dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ")
dependent_conditions = dependent_conditions.gsub('@', '\@')
@@ -1672,7 +1677,6 @@ module ActiveRecord
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)
@@ -1682,6 +1686,9 @@ module ActiveRecord
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
@@ -1696,7 +1703,7 @@ module ActiveRecord
def construct_finder_arel_with_included_associations(options, join_dependency)
scope = scope(:find)
- relation = arel_table((scope && scope[:from]) || options[:from])
+ relation = active_relation
for association in join_dependency.join_associations
relation = association.join_relation(relation)
@@ -1704,11 +1711,13 @@ module ActiveRecord
relation = relation.joins(construct_join(options[:joins], scope)).
select(column_aliases(join_dependency)).
- group(construct_group(options[:group], options[:having], scope)).
+ group(options[:group] || (scope && scope[:group])).
+ having(options[:having] || (scope && scope[:having])).
order(construct_order(options[:order], scope)).
- conditions(construct_conditions(options[:conditions], scope))
+ where(construct_conditions(options[:conditions], scope)).
+ from((scope && scope[:from]) || options[:from])
- relation = relation.conditions(construct_arel_limited_ids_condition(options, join_dependency)) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
+ relation = relation.where(construct_arel_limited_ids_condition(options, join_dependency)) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
relation = relation.limit(construct_limit(options[:limit], scope)) if using_limitable_reflections?(join_dependency.reflections)
relation
@@ -1720,7 +1729,7 @@ module ActiveRecord
def construct_arel_limited_ids_condition(options, join_dependency)
if (ids_array = select_limited_ids_array(options, join_dependency)).empty?
- throw :invalid_query
+ raise ThrowResult
else
Arel::Predicates::In.new(
Arel::SqlLiteral.new("#{connection.quote_table_name table_name}.#{primary_key}"),
@@ -1739,101 +1748,25 @@ module ActiveRecord
def construct_finder_sql_for_association_limiting(options, join_dependency)
scope = scope(:find)
- relation = arel_table(options[:from])
+ relation = active_relation
for association in join_dependency.join_associations
relation = association.join_relation(relation)
end
relation = relation.joins(construct_join(options[:joins], scope)).
- conditions(construct_conditions(options[:conditions], scope)).
- group(construct_group(options[:group], options[:having], scope)).
+ where(construct_conditions(options[:conditions], scope)).
+ group(options[:group] || (scope && scope[:group])).
+ having(options[:having] || (scope && scope[:having])).
order(construct_order(options[:order], scope)).
limit(construct_limit(options[:limit], scope)).
offset(construct_limit(options[:offset], scope)).
+ from(options[:from]).
select(connection.distinct("#{connection.quote_table_name table_name}.#{primary_key}", construct_order(options[:order], scope(:find)).join(",")))
relation.to_sql
end
- def tables_in_string(string)
- return [] if string.blank?
- string.scan(/([a-zA-Z_][\.\w]+).?\./).flatten
- end
-
- def tables_in_hash(hash)
- return [] if hash.blank?
- tables = hash.map do |key, value|
- if value.is_a?(Hash)
- key.to_s
- else
- tables_in_string(key) if key.is_a?(String)
- end
- end
- tables.flatten.compact
- end
-
- def conditions_tables(options)
- # look in both sets of conditions
- conditions = [scope(:find, :conditions), options[:conditions]].inject([]) do |all, cond|
- case cond
- when nil then all
- when Array then all << tables_in_string(cond.first)
- when Hash then all << tables_in_hash(cond)
- else all << tables_in_string(cond)
- end
- end
- conditions.flatten
- end
-
- def order_tables(options)
- order = [options[:order], scope(:find, :order) ].join(", ")
- return [] unless order && order.is_a?(String)
- tables_in_string(order)
- end
-
- def selects_tables(options)
- select = options[:select]
- return [] unless select && select.is_a?(String)
- tables_in_string(select)
- end
-
- def joined_tables(options)
- scope = scope(:find)
- joins = options[:joins]
- merged_joins = scope && scope[:joins] && joins ? merge_joins(scope[:joins], joins) : (joins || scope && scope[:joins])
- [table_name] + case merged_joins
- when Symbol, Hash, Array
- if array_of_strings?(merged_joins)
- tables_in_string(merged_joins.join(' '))
- else
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_joins, nil)
- join_dependency.join_associations.collect {|join_association| [join_association.aliased_join_table_name, join_association.aliased_table_name]}.flatten.compact
- end
- else
- tables_in_string(merged_joins)
- end
- end
-
- # Checks if the conditions reference a table other than the current model table
- def include_eager_conditions?(options, tables = nil, joined_tables = nil)
- ((tables || conditions_tables(options)) - (joined_tables || joined_tables(options))).any?
- end
-
- # Checks if the query order references a table other than the current model's table.
- def include_eager_order?(options, tables = nil, joined_tables = nil)
- ((tables || order_tables(options)) - (joined_tables || joined_tables(options))).any?
- end
-
- def include_eager_select?(options, joined_tables = nil)
- (selects_tables(options) - (joined_tables || joined_tables(options))).any?
- end
-
- def references_eager_loaded_tables?(options)
- joined_tables = joined_tables(options)
- include_eager_order?(options, nil, joined_tables) || include_eager_conditions?(options, nil, joined_tables) || include_eager_select?(options, joined_tables)
- end
-
def using_limitable_reflections?(reflections)
reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero?
end
diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb
index 25e329c0c1..358db6df1d 100644
--- a/activerecord/lib/active_record/associations/association_collection.rb
+++ b/activerecord/lib/active_record/associations/association_collection.rb
@@ -20,7 +20,22 @@ module ActiveRecord
super
construct_sql
end
-
+
+ delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped
+
+ def select(select = nil, &block)
+ if block_given?
+ load_target
+ @target.select(&block)
+ else
+ scoped.select(select)
+ end
+ end
+
+ def scoped
+ with_scope(construct_scope) { @reflection.klass.scoped }
+ end
+
def find(*args)
options = args.extract_options!
@@ -37,27 +52,21 @@ module ActiveRecord
load_target.select { |r| ids.include?(r.id) }
end
else
- conditions = "#{@finder_sql}"
- if sanitized_conditions = sanitize_sql(options[:conditions])
- conditions << " AND (#{sanitized_conditions})"
- end
-
- options[:conditions] = conditions
+ 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)
- if options[:order] && @reflection.options[:order]
- options[:order] = "#{options[:order]}, #{@reflection.options[:order]}"
- elsif @reflection.options[:order]
- options[:order] = @reflection.options[:order]
+ case args.first
+ when :first, :last, :all
+ relation.send(args.first)
+ else
+ relation.find(*args)
+ end
end
-
- # Build options specific to association
- construct_find_options!(options)
-
- merge_options_from_reflection!(options)
-
- # Pass through args exactly as we received them.
- args << options
- @reflection.klass.find(*args)
end
end
@@ -168,7 +177,7 @@ module ActiveRecord
if @reflection.options[:counter_sql]
@reflection.klass.count_by_sql(@counter_sql)
else
- column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args)
+ column_name, options = @reflection.klass.scoped.send(:construct_count_options_from_args, *args)
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}" if column_name == :all
@@ -383,7 +392,7 @@ module ActiveRecord
loaded if target
target
end
-
+
def method_missing(method, *args)
if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
if block_given?
@@ -476,7 +485,14 @@ module ActiveRecord
def callback(method, record)
callbacks_for(method).each do |callback|
- ActiveSupport::DeprecatedCallbacks::Callback.new(method, callback, record).call(@owner, record)
+ case callback
+ when Symbol
+ @owner.send(callback, record)
+ when Proc
+ callback.call(@owner, record)
+ else
+ callback.send(method, @owner, record)
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb
index 7d8f4670fa..022dd2ae9b 100644
--- a/activerecord/lib/active_record/associations/association_proxy.rb
+++ b/activerecord/lib/active_record/associations/association_proxy.rb
@@ -161,7 +161,7 @@ module ActiveRecord
end
# Forwards the call to the reflection class.
- def sanitize_sql(sql, table_name = @reflection.klass.quoted_table_name)
+ def sanitize_sql(sql, table_name = @reflection.klass.table_name)
@reflection.klass.send(:sanitize_sql, sql, table_name)
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 67e18d692d..f6edd6383c 100644
--- a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
@@ -13,6 +13,7 @@ module ActiveRecord
@updated = true
end
+ set_inverse_instance(record, @owner)
loaded
record
end
@@ -22,21 +23,44 @@ module ActiveRecord
end
private
- def find_target
- return nil if association_class.nil?
- if @reflection.options[:conditions]
- association_class.find(
- @owner[@reflection.primary_key_name],
- :select => @reflection.options[:select],
- :conditions => conditions,
- :include => @reflection.options[:include]
- )
+ # 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
- association_class.find(@owner[@reflection.primary_key_name], :select => @reflection.options[:select], :include => @reflection.options[:include])
+ false
+ end
+ end
+
+ def set_inverse_instance(record, instance)
+ return if record.nil? || !we_can_set_the_inverse_on_this?(record)
+ inverse_relationship = @reflection.polymorphic_inverse_of(record.class)
+ unless inverse_relationship.nil?
+ record.send(:"set_#{inverse_relationship.name}_target", instance)
end
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
+ end
+
def foreign_key_present
!@owner[@reflection.primary_key_name].nil?
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 c646fe488b..bd05d1014c 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,11 +1,6 @@
module ActiveRecord
module Associations
class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
- def initialize(owner, reflection)
- super
- @primary_key_list = {}
- end
-
def create(attributes = {})
create_record(attributes) { |record| insert_record(record) }
end
@@ -23,9 +18,7 @@ module ActiveRecord
end
def has_primary_key?
- return @has_primary_key unless @has_primary_key.nil?
- @has_primary_key = (@owner.connection.supports_primary_key? &&
- @owner.connection.primary_key(@reflection.options[:join_table]))
+ @has_primary_key ||= @owner.connection.supports_primary_key? && @owner.connection.primary_key(@reflection.options[:join_table])
end
protected
@@ -40,11 +33,6 @@ module ActiveRecord
end
def insert_record(record, force = true, validate = true)
- if has_primary_key?
- raise ActiveRecord::ConfigurationError,
- "Primary key is not allowed in a has_and_belongs_to_many join table (#{@reflection.options[:join_table]})."
- end
-
if record.new_record?
if force
record.save!
@@ -56,7 +44,7 @@ module ActiveRecord
if @reflection.options[:insert_sql]
@owner.connection.insert(interpolate_sql(@reflection.options[:insert_sql], record))
else
- relation = arel_table(@reflection.options[:join_table])
+ relation = Arel::Table.new(@reflection.options[:join_table])
attributes = columns.inject({}) do |attrs, column|
case column.name.to_s
when @reflection.primary_key_name.to_s
@@ -82,8 +70,8 @@ module ActiveRecord
if sql = @reflection.options[:delete_sql]
records.each { |record| @owner.connection.delete(interpolate_sql(sql, record)) }
else
- relation = arel_table(@reflection.options[:join_table])
- relation.conditions(relation[@reflection.primary_key_name].eq(@owner.id).
+ 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
end
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index cd31b0e211..d3336cf2d2 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -69,8 +69,8 @@ module ActiveRecord
when :delete_all
@reflection.klass.delete(records.map { |record| record.id })
else
- relation = arel_table(@reflection.table_name)
- relation.conditions(relation[@reflection.primary_key_name].eq(@owner.id).
+ 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)
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index b85a40b2e5..ea769fd48b 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -57,6 +57,7 @@ module ActiveRecord
@target = (AssociationProxy === obj ? obj.target : obj)
end
+ set_inverse_instance(obj, @owner)
@loaded = true
unless @owner.new_record? or obj.nil? or dont_save
@@ -120,10 +121,9 @@ module ActiveRecord
else
record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
self.target = record
+ set_inverse_instance(record, @owner)
end
- set_inverse_instance(record, @owner)
-
record
end
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 8f37fcd515..98ab64537e 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -155,6 +155,13 @@ module ActiveRecord
# Adds a validate and save callback for the association as specified by
# the +reflection+.
+ #
+ # For performance reasons, we don't check whether to validate at runtime,
+ # but instead only define the method and callback when needed. However,
+ # this can change, for instance, when using nested attributes. Since we
+ # don't want the callbacks to get defined multiple times, there are
+ # guards that check if the save or validation methods have already been
+ # defined before actually defining them.
def add_autosave_association_callbacks(reflection)
save_method = "autosave_associated_records_for_#{reflection.name}"
validation_method = "validate_associated_records_for_#{reflection.name}"
@@ -162,28 +169,33 @@ module ActiveRecord
case reflection.macro
when :has_many, :has_and_belongs_to_many
- before_save :before_save_collection_association
+ unless method_defined?(save_method)
+ before_save :before_save_collection_association
- define_method(save_method) { 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
+ define_method(save_method) { 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
+ end
- if force_validation || (reflection.macro == :has_many && reflection.options[:validate] != false)
+ if !method_defined?(validation_method) &&
+ (force_validation || (reflection.macro == :has_many && reflection.options[:validate] != false))
define_method(validation_method) { validate_collection_association(reflection) }
validate validation_method
end
else
- case reflection.macro
- when :has_one
- define_method(save_method) { save_has_one_association(reflection) }
- after_save save_method
- when :belongs_to
- define_method(save_method) { save_belongs_to_association(reflection) }
- before_save save_method
+ unless method_defined?(save_method)
+ case reflection.macro
+ when :has_one
+ define_method(save_method) { save_has_one_association(reflection) }
+ after_save save_method
+ when :belongs_to
+ define_method(save_method) { save_belongs_to_association(reflection) }
+ before_save save_method
+ end
end
- if force_validation
+ if !method_defined?(validation_method) && force_validation
define_method(validation_method) { validate_single_association(reflection) }
validate validation_method
end
@@ -221,9 +233,9 @@ module ActiveRecord
if new_record
association
elsif association.loaded?
- autosave ? association : association.select { |record| record.new_record? }
+ autosave ? association : association.find_all { |record| record.new_record? }
else
- autosave ? association.target : association.target.select { |record| record.new_record? }
+ autosave ? association.target : association.target.find_all { |record| record.new_record? }
end
end
@@ -255,7 +267,7 @@ module ActiveRecord
unless valid = association.valid?
if reflection.options[:autosave]
association.errors.each do |attribute, message|
- attribute = "#{reflection.name}_#{attribute}"
+ attribute = "#{reflection.name}.#{attribute}"
errors[attribute] << message if errors[attribute].empty?
end
else
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 056f29f029..ec7725d256 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -1,4 +1,3 @@
-require 'benchmark'
require 'yaml'
require 'set'
require 'active_support/benchmarkable'
@@ -13,6 +12,7 @@ require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/string/behavior'
require 'active_support/core_ext/object/metaclass'
+require 'active_support/core_ext/module/delegation'
module ActiveRecord #:nodoc:
# Generic Active Record exception class.
@@ -68,6 +68,10 @@ module ActiveRecord #:nodoc:
class StatementInvalid < ActiveRecordError
end
+ # Raised when SQL statement is invalid and the application gets a blank result.
+ class ThrowResult < ActiveRecordError
+ end
+
# Parent class for all specific exceptions which wrap database driver exceptions
# provides access to the original exception also.
class WrappedDatabaseException < StatementInvalid
@@ -639,17 +643,20 @@ module ActiveRecord #:nodoc:
# end
def find(*args)
options = args.extract_options!
- validate_find_options(options)
set_readonly_option!(options)
+ relation = construct_finder_arel(options)
+
case args.first
- when :first then find_initial(options)
- when :last then find_last(options)
- when :all then find_every(options)
- else find_from_ids(args, options)
+ when :first, :last, :all
+ relation.send(args.first)
+ else
+ relation.find(*args)
end
end
+ delegate :select, :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped
+
# A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
# same arguments to this method as you can to <tt>find(:first)</tt>.
def first(*args)
@@ -662,26 +669,10 @@ module ActiveRecord #:nodoc:
find(:last, *args)
end
- # Returns an ActiveRecord::Relation object. You can pass in all the same arguments to this method as you can
- # to find(:all).
+ # 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)
- options = args.extract_options!
-
- if options.empty? && !scoped?(:find)
- relation = arel_table
- else
- relation = construct_finder_arel(options)
- include_associations = merge_includes(scope(:find, :include), options[:include])
-
- if include_associations.any?
- if references_eager_loaded_tables?(options)
- relation.eager_load(include_associations)
- else
- relation.preload(include_associations)
- end
- end
- end
- relation
+ find(:all, *args)
end
# Executes a custom SQL query against your database and returns all the results. The results will
@@ -735,10 +726,13 @@ module ActiveRecord #:nodoc:
# Person.exists?(:name => "David")
# Person.exists?(['name LIKE ?', "%#{query}%"])
# Person.exists?
- def exists?(id_or_conditions = {})
- find_initial(
- :select => "#{quoted_table_name}.#{primary_key}",
- :conditions => expand_id_conditions(id_or_conditions)) ? true : false
+ def exists?(id_or_conditions = nil)
+ case id_or_conditions
+ when Array, Hash
+ where(id_or_conditions).exists?
+ else
+ scoped.exists?(id_or_conditions)
+ end
end
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
@@ -821,8 +815,8 @@ module ActiveRecord #:nodoc:
#
# # Delete multiple rows
# Todo.delete([2,3,4])
- def delete(id)
- delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
+ def delete(id_or_array)
+ active_relation.where(construct_conditions(nil, scope(:find))).delete(id_or_array)
end
# Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
@@ -879,10 +873,10 @@ module ActiveRecord #:nodoc:
def update_all(updates, conditions = nil, options = {})
scope = scope(:find)
- relation = arel_table
+ relation = active_relation
if conditions = construct_conditions(conditions, scope)
- relation = relation.conditions(Arel::SqlLiteral.new(conditions))
+ relation = relation.where(Arel::SqlLiteral.new(conditions))
end
relation = if options.has_key?(:limit) || (scope && scope[:limit])
@@ -923,7 +917,7 @@ module ActiveRecord #:nodoc:
# Person.destroy_all("last_login < '2004-04-04'")
# Person.destroy_all(:status => "inactive")
def destroy_all(conditions = nil)
- find(:all, :conditions => conditions).each { |object| object.destroy }
+ where(conditions).destroy_all
end
# Deletes the records matching +conditions+ without instantiating the records first, and hence not
@@ -944,11 +938,7 @@ module ActiveRecord #:nodoc:
# 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)
- if conditions
- arel_table.conditions(Arel::SqlLiteral.new(construct_conditions(conditions, scope(:find)))).delete
- else
- arel_table.delete
- end
+ active_relation.where(construct_conditions(conditions, scope(:find))).delete_all
end
# Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
@@ -967,6 +957,29 @@ module ActiveRecord #:nodoc:
connection.select_value(sql, "#{name} Count").to_i
end
+ # Resets one or more counter caches to their correct value using an SQL
+ # count query. This is useful when adding new counter caches, or if the
+ # counter has been corrupted or modified directly by SQL.
+ #
+ # ==== Parameters
+ #
+ # * +id+ - The id of the object you wish to reset a counter on.
+ # * +counters+ - One or more counter names to reset
+ #
+ # ==== Examples
+ #
+ # # For Post with id #1 records reset the comments_count
+ # Post.reset_counters(1, :comments)
+ def reset_counters(id, *counters)
+ object = find(id)
+ counters.each do |association|
+ child_class = reflect_on_association(association).klass
+ counter_name = child_class.reflect_on_association(self.name.downcase.to_sym).counter_cache_column
+
+ connection.update("UPDATE #{quoted_table_name} SET #{connection.quote_column_name(counter_name)} = #{object.send(association).count} WHERE #{connection.quote_column_name(primary_key)} = #{quote_value(object.id)}", "#{name} UPDATE")
+ end
+ end
+
# A generic "counter updater" implementation, intended primarily to be
# used by increment_counter and decrement_counter, but which may also
# be useful on its own. It simply does a direct SQL update for the record
@@ -1378,7 +1391,8 @@ module ActiveRecord #:nodoc:
# end
def reset_column_information
undefine_attribute_methods
- @arel_table = @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
+ @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
+ @active_relation = @active_relation_engine = nil
end
def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
@@ -1491,130 +1505,25 @@ module ActiveRecord #:nodoc:
"(#{segments.join(') AND (')})" unless segments.empty?
end
-
- def arel_table(table = nil)
- table = table_name if table.blank?
- if @arel_table.nil? || @arel_table.name != table
- @arel_table = Relation.new(self, Arel::Table.new(table))
- end
- @arel_table
+ def active_relation
+ @active_relation ||= Relation.new(self, active_relation_table)
end
- private
- def find_initial(options)
- options.update(:limit => 1)
- find_every(options).first
- end
-
- def find_last(options)
- order = options[:order]
-
- if order
- order = reverse_sql_order(order)
- elsif !scoped?(:find, :order)
- order = "#{table_name}.#{primary_key} DESC"
- end
-
- if scoped?(:find, :order)
- scope = scope(:find)
- original_scoped_order = scope[:order]
- scope[:order] = reverse_sql_order(original_scoped_order)
- end
-
- begin
- find_initial(options.merge({ :order => order }))
- ensure
- scope[:order] = original_scoped_order if original_scoped_order
- end
- end
-
- def reverse_sql_order(order_query)
- order_query.to_s.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(',')
- end
-
- def find_every(options)
- include_associations = merge_includes(scope(:find, :include), options[:include])
-
- if include_associations.any? && references_eager_loaded_tables?(options)
- records = find_with_associations(options)
- else
- records = find_by_sql(construct_finder_sql(options))
- if include_associations.any?
- preload_associations(records, include_associations)
- end
- end
-
- records.each { |record| record.readonly! } if options[:readonly]
-
- records
- end
-
- def find_from_ids(ids, options)
- expects_array = ids.first.kind_of?(Array)
- return ids.first if expects_array && ids.first.empty?
-
- ids = ids.flatten.compact.uniq
-
- case ids.size
- when 0
- raise RecordNotFound, "Couldn't find #{name} without an ID"
- when 1
- result = find_one(ids.first, options)
- expects_array ? [ result ] : result
- else
- find_some(ids, options)
- end
- end
-
- def find_one(id, options)
- conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
- options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} = #{quote_value(id,columns_hash[primary_key])}#{conditions}"
-
- # Use find_every(options).first since the primary key condition
- # already ensures we have a single record. Using find_initial adds
- # a superfluous :limit => 1.
- if result = find_every(options).first
- result
- else
- raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}"
- end
- end
-
- def find_some(ids, options)
- conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
- ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',')
- options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}"
-
- result = find_every(options)
-
- # Determine expected size from limit and offset, not just ids.size.
- expected_size =
- if options[:limit] && ids.size > options[:limit]
- options[:limit]
- else
- ids.size
- end
-
- # 11 ids with limit 3, offset 9 should give 2 results.
- if options[:offset] && (ids.size - options[:offset] < expected_size)
- expected_size = ids.size - options[:offset]
- end
+ def active_relation_table(table_name_alias = nil)
+ Arel::Table.new(table_name, :as => table_name_alias, :engine => active_relation_engine)
+ end
- if result.size == expected_size
- result
+ def active_relation_engine
+ @active_relation_engine ||= begin
+ if self == ActiveRecord::Base
+ Arel::Table.engine
else
- raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
+ connection_handler.connection_pools[name] ? Arel::Sql::Engine.new(self) : superclass.active_relation_engine
end
end
+ end
+ private
# 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.
@@ -1665,25 +1574,28 @@ module ActiveRecord #:nodoc:
end
def construct_finder_arel(options = {}, scope = scope(:find))
- # TODO add lock to Arel
- relation = arel_table(options[:from]).
+ validate_find_options(options)
+
+ relation = active_relation.
joins(construct_join(options[:joins], scope)).
- conditions(construct_conditions(options[:conditions], scope)).
+ where(construct_conditions(options[:conditions], scope)).
select(options[:select] || (scope && scope[:select]) || default_select(options[:joins] || (scope && scope[:joins]))).
- group(construct_group(options[:group], options[:having], scope)).
+ group(options[:group] || (scope && scope[:group])).
+ having(options[:having] || (scope && scope[:having])).
order(construct_order(options[:order], scope)).
limit(construct_limit(options[:limit], scope)).
- offset(construct_offset(options[:offset], scope))
+ offset(construct_offset(options[:offset], scope)).
+ from(options[:from]).
+ includes( merge_includes(scope && scope[:include], options[:include]))
+
+ lock = (scope && scope[:lock]) || options[:lock]
+ relation = relation.lock if lock.present?
relation = relation.readonly if options[:readonly]
relation
end
- def construct_finder_sql(options, scope = scope(:find))
- construct_finder_arel(options, scope).to_sql
- end
-
def construct_join(joins, scope)
merged_joins = scope && scope[:joins] && joins ? merge_joins(scope[:joins], joins) : (joins || scope && scope[:joins])
case merged_joins
@@ -1700,20 +1612,9 @@ module ActiveRecord #:nodoc:
end
end
- def construct_group(group, having, scope)
- sql = ''
- if group
- sql << group.to_s
- sql << " HAVING #{sanitize_sql_for_conditions(having)}" if having
- elsif scope && (scoped_group = scope[:group])
- sql << scoped_group.to_s
- sql << " HAVING #{sanitize_sql_for_conditions(scope[:having])}" if scope[:having]
- end
- sql
- end
-
def construct_order(order, scope)
orders = []
+
scoped_order = scope[:order] if scope
if order
orders << order
@@ -1721,7 +1622,8 @@ module ActiveRecord #:nodoc:
elsif scoped_order
orders << scoped_order
end
- orders
+
+ orders.reject {|o| o.blank?}
end
def construct_limit(limit, scope)
@@ -1743,7 +1645,7 @@ module ActiveRecord #:nodoc:
# Merges includes so that the result is a valid +include+
def merge_includes(first, second)
- (safe_to_array(first) + safe_to_array(second)).uniq
+ (Array.wrap(first) + Array.wrap(second)).uniq
end
def merge_joins(*joins)
@@ -1755,13 +1657,13 @@ module ActiveRecord #:nodoc:
end
joins.flatten.map{|j| j.strip}.uniq
else
- joins.collect{|j| safe_to_array(j)}.flatten.uniq
+ joins.collect{|j| Array.wrap(j)}.flatten.uniq
end
end
def build_association_joins(joins)
join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, joins, nil)
- relation = arel_table.relation
+ relation = active_relation.relation
join_dependency.join_associations.map { |association|
if (association_relation = association.relation).is_a?(Array)
[Arel::InnerJoin.new(relation, association_relation.first, association.association_join.first).joins(relation),
@@ -1772,38 +1674,18 @@ module ActiveRecord #:nodoc:
}.join(" ")
end
- # Object#to_a is deprecated, though it does have the desired behavior
- def safe_to_array(o)
- case o
- when NilClass
- []
- when Array
- o
- else
- [o]
- end
- end
-
def array_of_strings?(o)
o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
end
- # The optional scope argument is for the current <tt>:find</tt> scope.
- # The <tt>:lock</tt> option has precedence over a scoped <tt>:lock</tt>.
- def add_lock!(sql, options, scope = :auto)
- scope = scope(:find) if :auto == scope
- options = options.reverse_merge(:lock => scope[:lock]) if scope
- connection.add_lock!(sql, options)
- end
+ def type_condition(table_alias = nil)
+ table = Arel::Table.new(table_name, :engine => active_relation_engine, :as => table_alias)
- def type_condition(table_alias=nil)
- quoted_table_alias = self.connection.quote_table_name(table_alias || table_name)
- quoted_inheritance_column = connection.quote_column_name(inheritance_column)
- type_condition = subclasses.inject("#{quoted_table_alias}.#{quoted_inheritance_column} = '#{sti_name}' " ) do |condition, subclass|
- condition << "OR #{quoted_table_alias}.#{quoted_inheritance_column} = '#{subclass.sti_name}' "
- end
+ sti_column = table[inheritance_column]
+ condition = sti_column.eq(sti_name)
+ subclasses.each{|subclass| condition = condition.or(sti_column.eq(subclass.sti_name)) }
- " (#{type_condition}) "
+ condition.to_sql
end
# Guesses the table name, but does not decorate it with prefix and suffix information.
@@ -1814,9 +1696,8 @@ module ActiveRecord #:nodoc:
end
# Enables dynamic finders like <tt>find_by_user_name(user_name)</tt> and <tt>find_by_user_name_and_password(user_name, password)</tt>
- # that are turned into <tt>find(:first, :conditions => ["user_name = ?", user_name])</tt> and
- # <tt>find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt> respectively. Also works for
- # <tt>find(:all)</tt> by using <tt>find_all_by_amount(50)</tt> that is turned into <tt>find(:all, :conditions => ["amount = ?", 50])</tt>.
+ # that are turned into <tt>where(:user_name => user_name).first</tt> and <tt>where(:user_name => user_name, :password => :password).first</tt>
+ # respectively. Also works for <tt>all</tt> by using <tt>find_all_by_amount(50)</tt> that is turned into <tt>where(:amount => 50).all</tt>.
#
# 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>.
@@ -1832,103 +1713,11 @@ module ActiveRecord #:nodoc:
attribute_names = match.attribute_names
super unless all_attributes_exists?(attribute_names)
if match.finder?
- finder = match.finder
- bang = match.bang?
- # def self.find_by_login_and_activated(*args)
- # options = args.extract_options!
- # attributes = construct_attributes_from_arguments(
- # [:login,:activated],
- # args
- # )
- # finder_options = { :conditions => attributes }
- # validate_find_options(options)
- # set_readonly_option!(options)
- #
- # if options[:conditions]
- # with_scope(:find => finder_options) do
- # find(:first, options)
- # end
- # else
- # find(:first, options.merge(finder_options))
- # end
- # end
- self.class_eval %{
- def self.#{method_id}(*args)
- options = args.extract_options!
- attributes = construct_attributes_from_arguments(
- [:#{attribute_names.join(',:')}],
- args
- )
- finder_options = { :conditions => attributes }
- validate_find_options(options)
- set_readonly_option!(options)
-
- #{'result = ' if bang}if options[:conditions]
- with_scope(:find => finder_options) do
- find(:#{finder}, options)
- end
- else
- find(:#{finder}, options.merge(finder_options))
- end
- #{'result || raise(RecordNotFound, "Couldn\'t find #{name} with #{attributes.to_a.collect { |pair| pair.join(\' = \') }.join(\', \')}")' if bang}
- end
- }, __FILE__, __LINE__
- send(method_id, *arguments)
+ options = arguments.extract_options!
+ relation = options.any? ? construct_finder_arel(options) : scoped
+ relation.send :find_by_attributes, match, attribute_names, *arguments
elsif match.instantiator?
- instantiator = match.instantiator
- # def self.find_or_create_by_user_id(*args)
- # guard_protected_attributes = false
- #
- # if args[0].is_a?(Hash)
- # guard_protected_attributes = true
- # attributes = args[0].with_indifferent_access
- # find_attributes = attributes.slice(*[:user_id])
- # else
- # find_attributes = attributes = construct_attributes_from_arguments([:user_id], args)
- # end
- #
- # options = { :conditions => find_attributes }
- # set_readonly_option!(options)
- #
- # record = find(:first, options)
- #
- # if record.nil?
- # record = self.new { |r| r.send(:attributes=, attributes, guard_protected_attributes) }
- # yield(record) if block_given?
- # record.save
- # record
- # else
- # record
- # end
- # end
- self.class_eval %{
- def self.#{method_id}(*args)
- guard_protected_attributes = false
-
- if args[0].is_a?(Hash)
- guard_protected_attributes = true
- attributes = args[0].with_indifferent_access
- find_attributes = attributes.slice(*[:#{attribute_names.join(',:')}])
- else
- find_attributes = attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args)
- end
-
- options = { :conditions => find_attributes }
- set_readonly_option!(options)
-
- record = find(:first, options)
-
- if record.nil?
- record = self.new { |r| r.send(:attributes=, attributes, guard_protected_attributes) }
- #{'yield(record) if block_given?'}
- #{'record.save' if instantiator == :create}
- record
- else
- record
- end
- end
- }, __FILE__, __LINE__
- send(method_id, *arguments, &block)
+ scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block
end
elsif match = DynamicScopeMatch.match(method_id)
attribute_names = match.attribute_names
@@ -1990,14 +1779,6 @@ module ActiveRecord #:nodoc:
end
end
- # Interpret Array and Hash as conditions and anything else as an id.
- def expand_id_conditions(id_or_conditions)
- case id_or_conditions
- when Array, Hash then id_or_conditions
- else sanitize_sql(primary_key => id_or_conditions)
- end
- end
-
protected
# Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
# method_name may be <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
@@ -2184,7 +1965,7 @@ module ActiveRecord #:nodoc:
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
# { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
- def sanitize_sql_for_conditions(condition, table_name = quoted_table_name)
+ def sanitize_sql_for_conditions(condition, table_name = self.table_name)
return nil if condition.blank?
case condition
@@ -2255,30 +2036,12 @@ module ActiveRecord #:nodoc:
# And for value objects on a composed_of relationship:
# { :address => Address.new("123 abc st.", "chicago") }
# # => "address_street='123 abc st.' and address_city='chicago'"
- def sanitize_sql_hash_for_conditions(attrs, default_table_name = quoted_table_name)
+ def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
attrs = expand_hash_conditions_for_aggregates(attrs)
- conditions = attrs.map do |attr, value|
- table_name = default_table_name
-
- unless value.is_a?(Hash)
- attr = attr.to_s
-
- # Extract table name from qualified attribute names.
- if attr.include?('.')
- attr_table_name, attr = attr.split('.', 2)
- attr_table_name = connection.quote_table_name(attr_table_name)
- else
- attr_table_name = table_name
- end
-
- attribute_condition("#{attr_table_name}.#{connection.quote_column_name(attr)}", value)
- else
- sanitize_sql_hash_for_conditions(value, connection.quote_table_name(attr.to_s))
- end
- end.join(' AND ')
-
- replace_bind_variables(conditions, expand_range_bind_variables(attrs.values))
+ table = Arel::Table.new(default_table_name, active_relation_engine)
+ builder = PredicateBuilder.new(active_relation_engine)
+ builder.build_from_hash(attrs, table).map(&:to_sql).join(' AND ')
end
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
@@ -2543,7 +2306,7 @@ module ActiveRecord #:nodoc:
# be made (since they can't be persisted).
def destroy
unless new_record?
- self.class.arel_table.conditions(self.class.arel_table[self.class.primary_key].eq(id)).delete
+ self.class.active_relation.where(self.class.active_relation[self.class.primary_key].eq(id)).delete_all
end
@destroyed = true
@@ -2830,7 +2593,7 @@ module ActiveRecord #:nodoc:
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.arel_table.conditions(self.class.arel_table[self.class.primary_key].eq(id)).update(attributes_with_values)
+ self.class.active_relation.where(self.class.active_relation[self.class.primary_key].eq(id)).update(attributes_with_values)
end
# Creates a record with values matching those of the instance attributes
@@ -2843,9 +2606,9 @@ module ActiveRecord #:nodoc:
attributes_values = arel_attributes_values
new_id = if attributes_values.empty?
- self.class.arel_table.insert connection.empty_insert_statement_value
+ self.class.active_relation.insert connection.empty_insert_statement_value
else
- self.class.arel_table.insert attributes_values
+ self.class.active_relation.insert attributes_values
end
self.id ||= new_id
@@ -2940,7 +2703,7 @@ module ActiveRecord #:nodoc:
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
+ attrs[self.class.active_relation[name]] = value
end
end
end
diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb
index 40242333e5..20d287faeb 100644
--- a/activerecord/lib/active_record/calculations.rb
+++ b/activerecord/lib/active_record/calculations.rb
@@ -44,7 +44,26 @@ module ActiveRecord
#
# 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(*args)
- calculate(:count, *construct_count_options_from_args(*args))
+ case args.size
+ when 0
+ construct_calculation_arel.count
+ when 1
+ if args[0].is_a?(Hash)
+ options = args[0]
+ distinct = options.has_key?(:distinct) ? options.delete(:distinct) : false
+ construct_calculation_arel(options).count(options[:select], :distinct => distinct)
+ else
+ construct_calculation_arel.count(args[0])
+ end
+ when 2
+ column_name, options = args
+ distinct = options.has_key?(:distinct) ? options.delete(:distinct) : false
+ construct_calculation_arel(options).count(column_name, :distinct => distinct)
+ else
+ raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
+ end
+ rescue ThrowResult
+ 0
end
# Calculates the average value on a given column. The value is returned as
@@ -122,168 +141,63 @@ module ActiveRecord
# Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors
# Person.sum("2 * age")
def calculate(operation, column_name, options = {})
- validate_calculation_options(operation, options)
- operation = operation.to_s.downcase
-
- scope = scope(:find)
+ construct_calculation_arel(options).calculate(operation, column_name, options.slice(:distinct))
+ rescue ThrowResult
+ 0
+ end
- merged_includes = merge_includes(scope ? scope[:include] : [], options[:include])
+ private
+ def validate_calculation_options(options = {})
+ options.assert_valid_keys(CALCULATIONS_OPTIONS)
+ end
- if operation == "count"
- if merged_includes.any?
- distinct = true
- column_name = options[:select] || primary_key
- end
+ def construct_calculation_arel(options = {})
+ validate_calculation_options(options)
+ options = options.except(:distinct)
- distinct = nil if column_name.to_s =~ /\s*DISTINCT\s+/i
- distinct ||= options[:distinct]
- else
- distinct = nil
- end
+ scope = scope(:find)
+ includes = merge_includes(scope ? scope[:include] : [], options[:include])
- catch :invalid_query do
- relation = if merged_includes.any?
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, construct_join(options[:joins], scope))
- construct_finder_arel_with_included_associations(options, join_dependency)
+ if includes.any?
+ join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, includes, construct_join(options[:joins], scope))
+ construct_calculation_arel_with_included_associations(options, join_dependency)
else
- relation = arel_table(options[:from]).
+ active_relation.
joins(construct_join(options[:joins], scope)).
- conditions(construct_conditions(options[:conditions], scope)).
+ from((scope && scope[:from]) || options[:from]).
+ where(construct_conditions(options[:conditions], scope)).
order(options[:order]).
limit(options[:limit]).
- offset(options[:offset])
- end
- if options[:group]
- return execute_grouped_calculation(operation, column_name, options, relation)
- else
- return execute_simple_calculation(operation, column_name, options.merge(:distinct => distinct), relation)
+ offset(options[:offset]).
+ group(options[:group]).
+ having(options[:having]).
+ select(options[:select] || (scope && scope[:select]) || default_select(options[:joins] || (scope && scope[:joins])))
end
end
- 0
- end
-
- def execute_simple_calculation(operation, column_name, options, relation) #:nodoc:
- column = if column_names.include?(column_name.to_s)
- Arel::Attribute.new(arel_table(options[:from] || table_name),
- options[:select] || column_name)
- else
- Arel::SqlLiteral.new(options[:select] ||
- (column_name == :all ? "*" : column_name.to_s))
- end
-
- relation = relation.select(operation == 'count' ? column.count(options[:distinct]) : column.send(operation))
-
- type_cast_calculated_value(connection.select_value(relation.to_sql), column_for(column_name), operation)
- end
- def execute_grouped_calculation(operation, column_name, options, relation) #:nodoc:
- group_attr = options[:group].to_s
- association = 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 construct_calculation_arel_with_included_associations(options, join_dependency)
+ scope = scope(:find)
- options[:group] = connection.adapter_name == 'FrontBase' ? group_alias : group_field
+ relation = active_relation
- aggregate_alias = column_alias_for(operation, column_name)
-
- options[:select] = (operation == 'count' && column_name == :all) ?
- "COUNT(*) AS count_all" :
- Arel::Attribute.new(arel_table, column_name).send(operation).as(aggregate_alias).to_sql
-
- options[:select] << ", #{group_field} AS #{group_alias}"
-
- relation = relation.select(options[:select]).group(construct_group(options[:group], options[:having], nil))
-
- calculated_data = connection.select_all(relation.to_sql)
-
- if association
- key_ids = calculated_data.collect { |row| row[group_alias] }
- key_records = association.klass.base_class.find(key_ids)
- key_records = key_records.inject({}) { |hsh, r| hsh.merge(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
- end
-
- protected
- def construct_count_options_from_args(*args)
- options = {}
- column_name = :all
-
- # We need to handle
- # count()
- # count(:column_name=:all)
- # count(options={})
- # count(column_name=:all, options={})
- # selects specified by scopes
- case args.size
- when 0
- column_name = scope(:find)[:select] if scope(:find)
- when 1
- if args[0].is_a?(Hash)
- column_name = scope(:find)[:select] if scope(:find)
- options = args[0]
- else
- column_name = args[0]
- end
- when 2
- column_name, options = args
- else
- raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
+ for association in join_dependency.join_associations
+ relation = association.join_relation(relation)
end
- [column_name || :all, options]
- end
-
- private
- def validate_calculation_options(operation, options = {})
- options.assert_valid_keys(CALCULATIONS_OPTIONS)
- end
+ relation = relation.joins(construct_join(options[:joins], scope)).
+ select(column_aliases(join_dependency)).
+ group(options[:group]).
+ having(options[:having]).
+ order(options[:order]).
+ where(construct_conditions(options[:conditions], scope)).
+ from((scope && scope[:from]) || options[:from])
- # Converts the given keys to the value that the database adapter returns as
- # a usable column name:
- #
- # column_alias_for("users.id") # => "users_id"
- # column_alias_for("sum(id)") # => "sum_id"
- # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
- # column_alias_for("count(*)") # => "count_all"
- # column_alias_for("count", "id") # => "count_id"
- def column_alias_for(*keys)
- table_name = keys.join(' ')
- table_name.downcase!
- table_name.gsub!(/\*/, 'all')
- table_name.gsub!(/\W+/, ' ')
- table_name.strip!
- table_name.gsub!(/ +/, '_')
+ relation = relation.where(construct_arel_limited_ids_condition(options, join_dependency)) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
+ relation = relation.limit(construct_limit(options[:limit], scope)) if using_limitable_reflections?(join_dependency.reflections)
- connection.table_alias_for(table_name)
+ relation
end
- def column_for(field)
- field_name = field.to_s.split('.').last
- columns.detect { |c| c.name.to_s == field_name }
- end
-
- def type_cast_calculated_value(value, column, operation = nil)
- case operation
- when 'count' then value.to_i
- when 'sum' then type_cast_using_column(value || '0', column)
- when 'average' then value && (value.is_a?(Fixnum) ? value.to_f : value).to_d
- else type_cast_using_column(value, column)
- end
- end
-
- def type_cast_using_column(value, column)
- column ? column.type_cast(value) : value
- end
end
end
end
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index b25893a1c3..e2a8f03c8f 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -1,5 +1,3 @@
-require 'observer'
-
module ActiveRecord
# Callbacks are hooks into the lifecycle 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
@@ -210,7 +208,6 @@ module ActiveRecord
# instead of quietly returning +false+.
module Callbacks
extend ActiveSupport::Concern
- include ActiveSupport::Callbacks
CALLBACKS = [
:after_initialize, :after_find, :before_validation, :after_validation,
@@ -224,60 +221,14 @@ module ActiveRecord
alias_method_chain method, :callbacks
end
- define_callbacks :initialize, :find, :save, :create, :update, :destroy,
- :validation, :terminator => "result == false", :scope => [:kind, :name]
+ extend ActiveModel::Callbacks
+
+ define_model_callbacks :initialize, :find, :only => :after
+ define_model_callbacks :save, :create, :update, :destroy
+ define_model_callbacks :validation, :only => [:before, :after]
end
module ClassMethods
- def after_initialize(*args, &block)
- options = args.extract_options!
- options[:prepend] = true
- set_callback(:initialize, :after, *(args << options), &block)
- end
-
- def after_find(*args, &block)
- options = args.extract_options!
- options[:prepend] = true
- set_callback(:find, :after, *(args << options), &block)
- end
-
- [:save, :create, :update, :destroy].each do |callback|
- module_eval <<-CALLBACKS, __FILE__, __LINE__
- def before_#{callback}(*args, &block)
- set_callback(:#{callback}, :before, *args, &block)
- end
-
- def around_#{callback}(*args, &block)
- set_callback(:#{callback}, :around, *args, &block)
- end
-
- def after_#{callback}(*args, &block)
- options = args.extract_options!
- options[:prepend] = true
- options[:if] = Array(options[:if]) << "!halted && value != false"
- set_callback(:#{callback}, :after, *(args << options), &block)
- end
- CALLBACKS
- end
-
- def before_validation(*args, &block)
- options = args.extract_options!
- if options[:on]
- options[:if] = Array(options[:if])
- options[:if] << "@_on_validate == :#{options[:on]}"
- end
- set_callback(:validation, :before, *(args << options), &block)
- end
-
- def after_validation(*args, &block)
- options = args.extract_options!
- options[:if] = Array(options[:if])
- options[:if] << "!halted"
- options[:if] << "@_on_validate == :#{options[:on]}" if options[:on]
- options[:prepend] = true
- set_callback(:validation, :after, *(args << options), &block)
- end
-
def method_added(meth)
super
if CALLBACKS.include?(meth.to_sym)
@@ -323,7 +274,7 @@ module ActiveRecord
def deprecated_callback_method(symbol) #:nodoc:
if respond_to?(symbol)
- ActiveSupport::Deprecation.warn("Base##{symbol} has been deprecated, please use Base.#{symbol} :method instead")
+ ActiveSupport::Deprecation.warn("Overwriting #{symbol} in your models has been deprecated, please use Base##{symbol} :method_name instead")
send(symbol)
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index be89873632..027d736484 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -181,18 +181,6 @@ module ActiveRecord
# done if the transaction block raises an exception or returns false.
def rollback_db_transaction() end
- # Appends a locking clause to an SQL statement.
- # This method *modifies* the +sql+ parameter.
- # # SELECT * FROM suppliers FOR UPDATE
- # add_lock! 'SELECT * FROM suppliers', :lock => true
- # add_lock! 'SELECT * FROM suppliers', :lock => ' FOR UPDATE'
- def add_lock!(sql, options)
- case lock = options[:lock]
- when true; sql << ' FOR UPDATE'
- when String; sql << " #{lock}"
- end
- end
-
def default_sequence_name(table, column)
nil
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 8fae26b790..d09aa3c4d2 100755
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -1,6 +1,7 @@
require 'date'
require 'bigdecimal'
require 'bigdecimal/util'
+require 'active_support/core_ext/benchmark'
# TODO: Autoload these files
require 'active_record/connection_adapters/abstract/schema_definitions'
@@ -191,7 +192,6 @@ module ActiveRecord
end
def log_info(sql, name, ms)
- @runtime += ms
if @logger && @logger.debug?
name = '%s (%.1fms)' % [name || 'SQL', ms]
@logger.debug(format_log_entry(name, sql.squeeze(' ')))
@@ -199,8 +199,12 @@ module ActiveRecord
end
protected
- def log(sql, name, &block)
- ActiveSupport::Notifications.instrument(:sql, :sql => sql, :name => name, &block)
+ def log(sql, name)
+ result = nil
+ ActiveSupport::Notifications.instrument(:sql, :sql => sql, :name => name) do
+ @runtime += Benchmark.ms { result = yield }
+ end
+ result
rescue Exception => e
# Log message and raise exception.
# Set last_verification to 0, so that connection gets verified
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index ad36ff22e3..fa28bc64df 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -470,6 +470,13 @@ module ActiveRecord
execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
end
+ def add_column(table_name, column_name, type, options = {})
+ add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(add_column_sql, options)
+ add_column_position!(add_column_sql, options)
+ execute(add_column_sql)
+ end
+
def change_column_default(table_name, column_name, default) #:nodoc:
column = column_for(table_name, column_name)
change_column table_name, column_name, column.sql_type, :default => default
@@ -498,6 +505,7 @@ module ActiveRecord
change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
add_column_options!(change_column_sql, options)
+ add_column_position!(change_column_sql, options)
execute(change_column_sql)
end
@@ -529,6 +537,13 @@ module ActiveRecord
end
end
+ def add_column_position!(sql, options)
+ if options[:first]
+ sql << " FIRST"
+ elsif options[:after]
+ sql << " AFTER #{quote_column_name(options[:after])}"
+ end
+ end
# SHOW VARIABLES LIKE 'name'
def show_variable(name)
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
index c9c2892ba4..78b897add6 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -183,12 +183,6 @@ module ActiveRecord
catch_schema_changes { @connection.rollback }
end
- # SELECT ... FOR UPDATE is redundant since the table is locked.
- def add_lock!(sql, options) #:nodoc:
- sql
- end
-
-
# SCHEMA STATEMENTS ========================================
def tables(name = nil) #:nodoc:
diff --git a/activerecord/lib/active_record/locale/en.yml b/activerecord/lib/active_record/locale/en.yml
index 092f5f0023..e33d389f8c 100644
--- a/activerecord/lib/active_record/locale/en.yml
+++ b/activerecord/lib/active_record/locale/en.yml
@@ -1,6 +1,9 @@
en:
activerecord:
errors:
+ # model.errors.full_messages format.
+ format: "{{attribute}} {{message}}"
+
# The values :model, :attribute and :value are always available for interpolation
# The value :count is available when applicable. Can be used for pluralization.
messages:
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index c8cd79a2b0..f9e538c586 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -23,16 +23,6 @@ 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:
- #
- # p1 = Person.find(1)
- # p2 = Person.find(1)
- #
- # p1.first_name = "Michael"
- # p1.save
- #
- # p2.destroy # Raises a ActiveRecord::StaleObjectError
- #
# You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
# or otherwise apply the business logic needed to resolve the conflict.
#
@@ -49,7 +39,6 @@ module ActiveRecord
self.lock_optimistically = true
alias_method_chain :update, :lock
- alias_method_chain :destroy, :lock
alias_method_chain :attributes_from_column_definition, :lock
class << self
@@ -89,11 +78,11 @@ module ActiveRecord
attribute_names.uniq!
begin
- arel_table = self.class.arel_table(self.class.table_name)
+ relation = self.class.active_relation
- affected_rows = arel_table.where(
- arel_table[self.class.primary_key].eq(quoted_id).and(
- arel_table[self.class.locking_column].eq(quote_value(previous_value))
+ affected_rows = relation.where(
+ relation[self.class.primary_key].eq(quoted_id).and(
+ relation[self.class.locking_column].eq(quote_value(previous_value))
)
).update(arel_attributes_values(false, false, attribute_names))
@@ -111,29 +100,6 @@ module ActiveRecord
end
end
- def destroy_with_lock #:nodoc:
- return destroy_without_lock unless locking_enabled?
-
- unless new_record?
- lock_col = self.class.locking_column
- previous_value = send(lock_col).to_i
-
- arel_table = self.class.arel_table(self.class.table_name)
-
- affected_rows = arel_table.where(
- arel_table[self.class.primary_key].eq(quoted_id).and(
- arel_table[self.class.locking_column].eq(quote_value(previous_value))
- )
- ).delete
-
- unless affected_rows == 1
- raise ActiveRecord::StaleObjectError, "Attempted to delete a stale object"
- end
- end
-
- freeze
- end
-
module ClassMethods
DEFAULT_LOCKING_COLUMN = 'lock_version'
diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb
index bbe2d1f205..f63b249241 100644
--- a/activerecord/lib/active_record/named_scope.rb
+++ b/activerecord/lib/active_record/named_scope.rb
@@ -6,18 +6,34 @@ module ActiveRecord
module NamedScope
extend ActiveSupport::Concern
- # All subclasses of ActiveRecord::Base have one named scope:
- # * <tt>scoped</tt> - which allows for the creation of anonymous \scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt>
- #
- # These anonymous \scopes tend to be useful when procedurally generating complex queries, where passing
- # intermediate values (scopes) around as first-class objects is convenient.
- #
- # You can define a scope that applies to all finders using ActiveRecord::Base.default_scope.
- included do
- named_scope :scoped, lambda { |scope| scope }
- end
-
module ClassMethods
+ # Returns a relation if invoked without any arguments.
+ #
+ # posts = Post.scoped
+ # posts.size # Fires "select count(*) from posts" and returns the count
+ # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
+ #
+ # Returns an anonymous named scope if any options are supplied.
+ #
+ # shirts = Shirt.scoped(:conditions => {:color => 'red'})
+ # shirts = shirts.scoped(:include => :washing_instructions)
+ #
+ # Anonymous \scopes tend to be useful when procedurally generating complex queries, where passing
+ # intermediate values (scopes) around as first-class objects is convenient.
+ #
+ # You can define a scope that applies to all finders using ActiveRecord::Base.default_scope.
+ def scoped(options = {}, &block)
+ if options.present?
+ Scope.new(self, options, &block)
+ else
+ unless scoped?(:find)
+ finder_needs_type_condition? ? active_relation.where(type_condition) : active_relation.spawn
+ else
+ construct_finder_arel
+ end
+ end
+ end
+
def scopes
read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
end
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index f61a4a6c73..dbdeba6c24 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -212,6 +212,11 @@ module ActiveRecord
# nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
# exception is raised. If omitted, any number associations can be processed.
# Note that the :limit option is only applicable to one-to-many associations.
+ # [:update_only]
+ # Allows you to specify that an existing record may only be updated.
+ # A new record may only be created when there is no existing record.
+ # This option only works for one-to-one associations and is ignored for
+ # collection associations. This option is off by default.
#
# Examples:
# # creates avatar_attributes=
@@ -221,9 +226,9 @@ module ActiveRecord
# # creates avatar_attributes= and posts_attributes=
# accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
def accepts_nested_attributes_for(*attr_names)
- options = { :allow_destroy => false }
+ options = { :allow_destroy => false, :update_only => false }
options.update(attr_names.extract_options!)
- options.assert_valid_keys(:allow_destroy, :reject_if, :limit)
+ options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
attr_names.each do |association_name|
if reflection = reflect_on_association(association_name)
@@ -235,7 +240,7 @@ module ActiveRecord
end
reflection.options[:autosave] = true
-
+ add_autosave_association_callbacks(reflection)
self.nested_attributes_options[association_name.to_sym] = options
if options[:reject_if] == :all_blank
@@ -243,15 +248,13 @@ module ActiveRecord
end
# def pirate_attributes=(attributes)
- # assign_nested_attributes_for_one_to_one_association(:pirate, attributes, false)
+ # assign_nested_attributes_for_one_to_one_association(:pirate, attributes)
# end
class_eval %{
def #{association_name}_attributes=(attributes)
assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
end
}, __FILE__, __LINE__
-
- add_autosave_association_callbacks(reflection)
else
raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
end
@@ -286,28 +289,29 @@ module ActiveRecord
# Assigns the given attributes to the association.
#
- # If the given attributes include an <tt>:id</tt> that matches the existing
- # record’s id, then the existing record will be modified. Otherwise a new
- # record will be built.
+ # If update_only is false and the given attributes include an <tt>:id</tt>
+ # that matches the existing record’s id, then the existing record will be
+ # modified. If update_only is true, a new record is only created when no
+ # object exists. Otherwise a new record will be built.
#
- # If the given attributes include a matching <tt>:id</tt> attribute _and_ a
- # <tt>:_destroy</tt> key set to a truthy value, then the existing record
- # will be marked for destruction.
+ # If the given attributes include a matching <tt>:id</tt> attribute, or
+ # update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
+ # then the existing record will be marked for destruction.
def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
options = self.nested_attributes_options[association_name]
attributes = attributes.with_indifferent_access
+ check_existing_record = (options[:update_only] || !attributes['id'].blank?)
- if attributes['id'].blank?
- unless reject_new_record?(association_name, attributes)
- method = "build_#{association_name}"
- if respond_to?(method)
- send(method, attributes.except(*UNASSIGNABLE_KEYS))
- else
- raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
- end
+ if check_existing_record && (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])
+ elsif !reject_new_record?(association_name, attributes)
+ method = "build_#{association_name}"
+ if respond_to?(method)
+ send(method, attributes.except(*UNASSIGNABLE_KEYS))
+ else
+ raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
end
- elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s
- assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
end
end
diff --git a/activerecord/lib/active_record/notifications.rb b/activerecord/lib/active_record/notifications.rb
deleted file mode 100644
index 562a5b91f4..0000000000
--- a/activerecord/lib/active_record/notifications.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-require 'active_support/notifications'
-
-ActiveSupport::Notifications.subscribe("sql") do |name, before, after, result, instrumenter_id, payload|
- ActiveRecord::Base.connection.log_info(payload[:sql], name, after - before)
-end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
new file mode 100644
index 0000000000..657ee738c0
--- /dev/null
+++ b/activerecord/lib/active_record/railtie.rb
@@ -0,0 +1,71 @@
+# For now, action_controller must always be present with
+# rails, so let's make sure that it gets required before
+# here. This is needed for correctly setting up the middleware.
+# In the future, this might become an optional require.
+require "active_record"
+require "action_controller/railtie"
+require "rails"
+
+module ActiveRecord
+ class Railtie < Rails::Railtie
+ plugin_name :active_record
+
+ rake_tasks do
+ load "active_record/railties/databases.rake"
+ end
+
+ initializer "active_record.set_configs" do |app|
+ app.config.active_record.each do |k,v|
+ ActiveRecord::Base.send "#{k}=", v
+ end
+ end
+
+ # This sets the database configuration from Configuration#database_configuration
+ # and then establishes the connection.
+ initializer "active_record.initialize_database" do |app|
+ ActiveRecord::Base.configurations = app.config.database_configuration
+ ActiveRecord::Base.establish_connection
+ end
+
+ initializer "active_record.initialize_timezone" do
+ ActiveRecord::Base.time_zone_aware_attributes = true
+ ActiveRecord::Base.default_timezone = :utc
+ end
+
+ # Expose database runtime to controller for logging.
+ initializer "active_record.log_runtime" do |app|
+ require "active_record/railties/controller_runtime"
+ ActionController::Base.send :include, ActiveRecord::Railties::ControllerRuntime
+ end
+
+ # Setup database middleware after initializers have run
+ initializer "active_record.initialize_database_middleware" do |app|
+ middleware = app.config.middleware
+ if middleware.include?(ActiveRecord::SessionStore)
+ middleware.insert_before ActiveRecord::SessionStore, ActiveRecord::ConnectionAdapters::ConnectionManagement
+ middleware.insert_before ActiveRecord::SessionStore, ActiveRecord::QueryCache
+ else
+ middleware.use ActiveRecord::ConnectionAdapters::ConnectionManagement
+ middleware.use ActiveRecord::QueryCache
+ end
+ end
+
+ initializer "active_record.load_observers" do
+ ActiveRecord::Base.instantiate_observers
+ end
+
+ # TODO: ActiveRecord::Base.logger should delegate to its own config.logger
+ initializer "active_record.logger" do
+ ActiveRecord::Base.logger ||= ::Rails.logger
+ end
+
+ initializer "active_record.notifications" do
+ require 'active_support/notifications'
+
+ ActiveSupport::Notifications.subscribe("sql") do |name, before, after, instrumenter_id, payload|
+ ActiveRecord::Base.connection.log_info(payload[:sql], payload[:name], (after - before) * 1000)
+ end
+ end
+
+ end
+end
diff --git a/activerecord/lib/active_record/railties/controller_runtime.rb b/activerecord/lib/active_record/railties/controller_runtime.rb
new file mode 100644
index 0000000000..535e967ec3
--- /dev/null
+++ b/activerecord/lib/active_record/railties/controller_runtime.rb
@@ -0,0 +1,31 @@
+require 'active_support/core_ext/module/attr_internal'
+
+module ActiveRecord
+ module Railties
+ module ControllerRuntime
+ extend ActiveSupport::Concern
+
+ attr_internal :db_runtime
+
+ def cleanup_view_runtime
+ if ActiveRecord::Base.connected?
+ db_rt_before_render = ActiveRecord::Base.connection.reset_runtime
+ runtime = super
+ db_rt_after_render = ActiveRecord::Base.connection.reset_runtime
+ self.db_runtime = db_rt_before_render + db_rt_after_render
+ runtime - db_rt_after_render
+ else
+ super
+ end
+ end
+
+ module ClassMethods
+ def log_process_action(controller)
+ super
+ db_runtime = controller.send :db_runtime
+ logger.info(" ActiveRecord runtime: %.1fms" % db_runtime.to_f) if db_runtime
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/tasks/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index a35a6c156b..a35a6c156b 100644
--- a/railties/lib/rails/tasks/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index db5d2b25ed..b751c9ad68 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -214,8 +214,10 @@ module ActiveRecord
end
def check_validity_of_inverse!
- if has_inverse? && inverse_of.nil?
- raise InverseOfAssociationNotFoundError.new(self)
+ unless options[:polymorphic]
+ if has_inverse? && inverse_of.nil?
+ raise InverseOfAssociationNotFoundError.new(self)
+ end
end
end
@@ -237,8 +239,16 @@ module ActiveRecord
def inverse_of
if has_inverse?
@inverse_of ||= klass.reflect_on_association(options[:inverse_of])
- else
- nil
+ end
+ end
+
+ def polymorphic_inverse_of(associated_class)
+ if has_inverse?
+ if inverse_relationship = associated_class.reflect_on_association(options[:inverse_of])
+ inverse_relationship
+ else
+ raise InverseOfAssociationNotFoundError.new(self, associated_class)
+ end
end
end
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 5f0eec754f..6b9925d4e7 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -1,127 +1,195 @@
module ActiveRecord
class Relation
- delegate :to_sql, :to => :relation
- delegate :length, :collect, :find, :map, :each, :to => :to_a
+ include QueryMethods, FinderMethods, CalculationMethods, SpawnMethods
+
+ delegate :length, :collect, :map, :each, :all?, :to => :to_a
+
attr_reader :relation, :klass
+ attr_writer :readonly, :table
+ attr_accessor :preload_associations, :eager_load_associations, :includes_associations
def initialize(klass, relation)
@klass, @relation = klass, relation
- @readonly = false
- @associations_to_preload = []
+ @preload_associations = []
@eager_load_associations = []
+ @includes_associations = []
+ @loaded, @readonly = false
end
- def preload(association)
- @associations_to_preload += association
- self
+ def new(*args, &block)
+ with_create_scope { @klass.new(*args, &block) }
end
- def eager_load(association)
- @eager_load_associations += association
- self
+ def create(*args, &block)
+ with_create_scope { @klass.create(*args, &block) }
end
- def readonly
- @readonly = true
- self
+ def create!(*args, &block)
+ with_create_scope { @klass.create!(*args, &block) }
+ end
+
+ def respond_to?(method, include_private = false)
+ return true if @relation.respond_to?(method, include_private) || Array.method_defined?(method)
+
+ 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
+ super
+ end
end
def to_a
- records = if @eager_load_associations.any?
- catch :invalid_query do
- return @klass.send(:find_with_associations, {
+ return @records if loaded?
+
+ find_with_associations = @eager_load_associations.any? || references_eager_loaded_tables?
+
+ @records = if find_with_associations
+ begin
+ @klass.send(:find_with_associations, {
:select => @relation.send(:select_clauses).join(', '),
:joins => @relation.joins(relation),
:group => @relation.send(:group_clauses).join(', '),
- :order => @relation.send(:order_clauses).join(', '),
- :conditions => @relation.send(:where_clauses).join("\n\tAND "),
+ :order => order_clause,
+ :conditions => where_clause,
:limit => @relation.taken,
- :offset => @relation.skipped
+ :offset => @relation.skipped,
+ :from => (@relation.send(:from_clauses) if @relation.send(:sources).present?)
},
- ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations, nil))
+ ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations + @includes_associations, nil))
+ rescue ThrowResult
+ []
end
- []
else
@klass.find_by_sql(@relation.to_sql)
end
- @klass.send(:preload_associations, records, @associations_to_preload) unless @associations_to_preload.empty?
- records.each { |record| record.readonly! } if @readonly
+ preload = @preload_associations
+ preload += @includes_associations unless find_with_associations
+ preload.each {|associations| @klass.send(:preload_associations, @records, associations) }
+
+ @records.each { |record| record.readonly! } if @readonly
- records
+ @loaded = true
+ @records
end
- def first
- @relation = @relation.take(1)
- to_a.first
+ alias all to_a
+
+ def size
+ loaded? ? @records.length : count
end
- def select(selects)
- selects.blank? ? self : Relation.new(@klass, @relation.project(selects))
+ def empty?
+ loaded? ? @records.empty? : count.zero?
end
- def group(groups)
- groups.blank? ? self : Relation.new(@klass, @relation.group(groups))
+ def any?
+ if block_given?
+ to_a.any? { |*block_args| yield(*block_args) }
+ else
+ !empty?
+ end
end
- def order(orders)
- orders.blank? ? self : Relation.new(@klass, @relation.order(orders))
+ def many?
+ if block_given?
+ to_a.many? { |*block_args| yield(*block_args) }
+ else
+ @relation.send(:taken).present? ? to_a.many? : size > 1
+ end
end
- def limit(limits)
- limits.blank? ? self : Relation.new(@klass, @relation.take(limits))
+ def destroy_all
+ to_a.each {|object| object.destroy}
+ reset
end
- def offset(offsets)
- offsets.blank? ? self : Relation.new(@klass, @relation.skip(offsets))
+ def delete_all
+ @relation.delete.tap { reset }
end
- def on(join)
- join.blank? ? self : Relation.new(@klass, @relation.on(join))
+ def delete(id_or_array)
+ where(@klass.primary_key => id_or_array).delete_all
end
- def joins(join, join_type = nil)
- if join.blank?
- self
- else
- join = case join
- when String
- @relation.join(join)
- when Hash, Array, Symbol
- if @klass.send(:array_of_strings?, join)
- @relation.join(join.join(' '))
- else
- @relation.join(@klass.send(:build_association_joins, join))
- end
- else
- @relation.join(join, join_type)
- end
- Relation.new(@klass, join)
- end
+ def loaded?
+ @loaded
+ end
+
+ def reload
+ @loaded = false
+ reset
+ end
+
+ def reset
+ @first = @last = @create_scope = @to_sql = @order_clause = nil
+ @records = []
+ self
+ end
+
+ def table
+ @table ||= Arel::Table.new(@klass.table_name, :engine => @klass.active_relation_engine)
end
- def conditions(conditions)
- if conditions.blank?
- self
+ def primary_key
+ @primary_key ||= table[@klass.primary_key]
+ end
+
+ def to_sql
+ @to_sql ||= @relation.to_sql
+ end
+
+ protected
+
+ def method_missing(method, *args, &block)
+ if @relation.respond_to?(method)
+ @relation.send(method, *args, &block)
+ elsif Array.method_defined?(method)
+ to_a.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
- conditions = @klass.send(:merge_conditions, conditions) if [String, Hash, Array].include?(conditions.class)
- Relation.new(@klass, @relation.where(conditions))
+ super
end
end
- def respond_to?(method)
- @relation.respond_to?(method) || Array.method_defined?(method) || super
+ def with_create_scope
+ @klass.send(:with_scope, :create => create_scope) { yield }
end
- private
- def method_missing(method, *args, &block)
- if @relation.respond_to?(method)
- @relation.send(method, *args, &block)
- elsif Array.method_defined?(method)
- to_a.send(method, *args, &block)
- else
- super
- end
+ def create_scope
+ @create_scope ||= wheres.inject({}) do |hash, where|
+ hash[where.operand1.name] = where.operand2.value if where.is_a?(Arel::Predicates::Equality)
+ hash
end
+ end
+
+ def where_clause(join_string = " AND ")
+ @relation.send(:where_clauses).join(join_string)
+ end
+
+ def order_clause
+ @order_clause ||= @relation.send(:order_clauses).join(', ')
+ end
+
+ def references_eager_loaded_tables?
+ joined_tables = (tables_in_string(@relation.joins(relation)) + [table.name, table.table_alias]).compact.uniq
+ (tables_in_string(to_sql) - joined_tables).any?
+ end
+
+ def tables_in_string(string)
+ return [] if string.blank?
+ string.scan(/([a-zA-Z_][\.\w]+).?\./).flatten.uniq
+ end
+
end
end
diff --git a/activerecord/lib/active_record/relation/calculation_methods.rb b/activerecord/lib/active_record/relation/calculation_methods.rb
new file mode 100644
index 0000000000..5246c7bc5d
--- /dev/null
+++ b/activerecord/lib/active_record/relation/calculation_methods.rb
@@ -0,0 +1,177 @@
+module ActiveRecord
+ module CalculationMethods
+
+ def count(*args)
+ calculate(:count, *construct_count_options_from_args(*args))
+ end
+
+ def average(column_name)
+ calculate(:average, column_name)
+ end
+
+ def minimum(column_name)
+ calculate(:minimum, column_name)
+ end
+
+ def maximum(column_name)
+ calculate(:maximum, column_name)
+ end
+
+ def sum(column_name)
+ calculate(:sum, column_name)
+ end
+
+ def calculate(operation, column_name, options = {})
+ operation = operation.to_s.downcase
+
+ if operation == "count"
+ joins = @relation.joins(relation)
+ if joins.present? && joins =~ /LEFT OUTER/i
+ distinct = true
+ column_name = @klass.primary_key if column_name == :all
+ end
+
+ distinct = nil if column_name.to_s =~ /\s*DISTINCT\s+/i
+ distinct ||= options[:distinct]
+ else
+ distinct = nil
+ end
+
+ distinct = options[:distinct] || distinct
+ column_name = :all if column_name.blank? && operation == "count"
+
+ if @relation.send(:groupings).any?
+ return execute_grouped_calculation(operation, column_name)
+ else
+ return execute_simple_calculation(operation, column_name, distinct)
+ end
+ rescue ThrowResult
+ 0
+ end
+
+ private
+
+ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
+ column = if @klass.column_names.include?(column_name.to_s)
+ Arel::Attribute.new(@klass.active_relation, column_name)
+ else
+ Arel::SqlLiteral.new(column_name == :all ? "*" : column_name.to_s)
+ end
+
+ relation = 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)
+ end
+
+ def execute_grouped_calculation(operation, column_name) #:nodoc:
+ group_attr = @relation.send(:groupings).first.value
+ 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)
+
+ group = @klass.connection.adapter_name == 'FrontBase' ? group_alias : group_field
+
+ aggregate_alias = column_alias_for(operation, column_name)
+
+ select_statement = if operation == 'count' && column_name == :all
+ "COUNT(*) AS count_all"
+ else
+ Arel::Attribute.new(@klass.active_relation, column_name).send(operation).as(aggregate_alias).to_sql
+ end
+
+ select_statement << ", #{group_field} AS #{group_alias}"
+
+ relation = select(select_statement).group(group)
+
+ calculated_data = @klass.connection.select_all(relation.to_sql)
+
+ if association
+ key_ids = calculated_data.collect { |row| row[group_alias] }
+ key_records = association.klass.base_class.find(key_ids)
+ key_records = key_records.inject({}) { |hsh, r| hsh.merge(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
+ end
+
+ def construct_count_options_from_args(*args)
+ options = {}
+ column_name = :all
+
+ # Handles count(), count(:column), count(:distinct => true), count(:column, :distinct => true)
+ # TODO : relation.projections only works when .select() was last in the chain. Fix it!
+ case args.size
+ when 0
+ select = get_projection_name_from_chained_relations
+ column_name = select if select !~ /(,|\*)/
+ when 1
+ if args[0].is_a?(Hash)
+ select = get_projection_name_from_chained_relations
+ column_name = select if select !~ /(,|\*)/
+ options = args[0]
+ else
+ column_name = args[0]
+ end
+ when 2
+ column_name, options = args
+ else
+ raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
+ end
+
+ [column_name || :all, options]
+ end
+
+ # Converts the given keys to the value that the database adapter returns as
+ # a usable column name:
+ #
+ # column_alias_for("users.id") # => "users_id"
+ # column_alias_for("sum(id)") # => "sum_id"
+ # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
+ # column_alias_for("count(*)") # => "count_all"
+ # column_alias_for("count", "id") # => "count_id"
+ def column_alias_for(*keys)
+ table_name = keys.join(' ')
+ table_name.downcase!
+ table_name.gsub!(/\*/, 'all')
+ table_name.gsub!(/\W+/, ' ')
+ table_name.strip!
+ table_name.gsub!(/ +/, '_')
+
+ @klass.connection.table_alias_for(table_name)
+ end
+
+ def column_for(field)
+ field_name = field.to_s.split('.').last
+ @klass.columns.detect { |c| c.name.to_s == field_name }
+ end
+
+ def type_cast_calculated_value(value, column, operation = nil)
+ case operation
+ when 'count' then value.to_i
+ when 'sum' then type_cast_using_column(value || '0', column)
+ when 'average' then value && (value.is_a?(Fixnum) ? value.to_f : value).to_d
+ else type_cast_using_column(value, column)
+ end
+ end
+
+ def type_cast_using_column(value, column)
+ column ? column.type_cast(value) : value
+ end
+
+ def get_projection_name_from_chained_relations(relation = @relation)
+ if relation.respond_to?(:projections) && relation.projections.present?
+ relation.send(:select_clauses).join(', ')
+ elsif relation.respond_to?(:relation)
+ get_projection_name_from_chained_relations(relation.relation)
+ end
+ end
+
+ end
+end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
new file mode 100644
index 0000000000..c3e5f27838
--- /dev/null
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -0,0 +1,120 @@
+module ActiveRecord
+ module FinderMethods
+
+ def find(*ids, &block)
+ return to_a.find(&block) if block_given?
+
+ expects_array = ids.first.kind_of?(Array)
+ return ids.first if expects_array && ids.first.empty?
+
+ ids = ids.flatten.compact.uniq
+
+ case ids.size
+ when 0
+ raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
+ when 1
+ result = find_one(ids.first)
+ expects_array ? [ result ] : result
+ else
+ find_some(ids)
+ end
+ end
+
+ def exists?(id = nil)
+ relation = select(primary_key).limit(1)
+ relation = relation.where(primary_key.eq(id)) if id
+ relation.first ? true : false
+ end
+
+ def first
+ if loaded?
+ @records.first
+ else
+ @first ||= limit(1).to_a[0]
+ end
+ end
+
+ def last
+ if loaded?
+ @records.last
+ else
+ @last ||= reverse_order.limit(1).to_a[0]
+ end
+ end
+
+ protected
+
+ def find_by_attributes(match, attributes, *args)
+ conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h}
+ result = where(conditions).send(match.finder)
+
+ if match.bang? && result.blank?
+ raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"
+ else
+ result
+ end
+ end
+
+ def find_or_instantiator_by_attributes(match, attributes, *args)
+ guard_protected_attributes = false
+
+ if args[0].is_a?(Hash)
+ guard_protected_attributes = true
+ attributes_for_create = args[0].with_indifferent_access
+ conditions = attributes_for_create.slice(*attributes).symbolize_keys
+ else
+ attributes_for_create = conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h}
+ end
+
+ record = where(conditions).first
+
+ unless record
+ record = @klass.new { |r| r.send(:attributes=, attributes_for_create, guard_protected_attributes) }
+ yield(record) if block_given?
+ record.save if match.instantiator == :create
+ end
+
+ record
+ end
+
+ def find_one(id)
+ record = where(primary_key.eq(id)).first
+
+ unless record
+ conditions = where_clause(', ')
+ conditions = " [WHERE #{conditions}]" if conditions.present?
+ raise RecordNotFound, "Couldn't find #{@klass.name} with ID=#{id}#{conditions}"
+ end
+
+ record
+ end
+
+ def find_some(ids)
+ result = where(primary_key.in(ids)).all
+
+ expected_size =
+ if @relation.taken && ids.size > @relation.taken
+ @relation.taken
+ else
+ ids.size
+ end
+
+ # 11 ids with limit 3, offset 9 should give 2 results.
+ if @relation.skipped && (ids.size - @relation.skipped < expected_size)
+ expected_size = ids.size - @relation.skipped
+ end
+
+ if result.size == expected_size
+ result
+ else
+ conditions = where_clause(', ')
+ conditions = " [WHERE #{conditions}]" if conditions.present?
+
+ error = "Couldn't find all #{@klass.name.pluralize} with IDs "
+ error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
+ raise RecordNotFound, error
+ end
+ end
+
+ end
+end
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
new file mode 100644
index 0000000000..6b7d941350
--- /dev/null
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -0,0 +1,45 @@
+module ActiveRecord
+ class PredicateBuilder
+
+ def initialize(engine)
+ @engine = engine
+ end
+
+ def build_from_hash(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)
+ else
+ column = column.to_s
+
+ if column.include?('.')
+ table_name, column = column.split('.', 2)
+ table = Arel::Table.new(table_name, :engine => @engine)
+ end
+
+ attribute = table[column] || Arel::Attribute.new(table, column.to_sym)
+
+ case value
+ when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope
+ attribute.in(value)
+ when Range
+ # TODO : Arel should handle ranges with excluded end.
+ if value.exclude_end?
+ [attribute.gteq(value.begin), attribute.lt(value.end)]
+ else
+ attribute.in(value)
+ end
+ else
+ attribute.eq(value)
+ end
+ end
+ end
+
+ 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
new file mode 100644
index 0000000000..525a9cb365
--- /dev/null
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -0,0 +1,141 @@
+module ActiveRecord
+ module QueryMethods
+
+ def preload(*associations)
+ spawn.tap {|r| r.preload_associations += Array.wrap(associations) }
+ end
+
+ def includes(*associations)
+ spawn.tap {|r| r.includes_associations += Array.wrap(associations) }
+ end
+
+ def eager_load(*associations)
+ spawn.tap {|r| r.eager_load_associations += Array.wrap(associations) }
+ end
+
+ def readonly(status = true)
+ spawn.tap {|r| r.readonly = status }
+ end
+
+ def select(selects)
+ if selects.present?
+ relation = spawn(@relation.project(selects))
+ relation.readonly = @relation.joins(relation).present? ? false : @readonly
+ relation
+ else
+ spawn
+ end
+ end
+
+ def from(from)
+ from.present? ? spawn(@relation.from(from)) : spawn
+ end
+
+ def having(*args)
+ return spawn if args.blank?
+
+ if [String, Hash, Array].include?(args.first.class)
+ havings = @klass.send(:merge_conditions, args.size > 1 ? Array.wrap(args) : args.first)
+ else
+ havings = args.first
+ end
+
+ spawn(@relation.having(havings))
+ end
+
+ def group(groups)
+ groups.present? ? spawn(@relation.group(groups)) : spawn
+ end
+
+ def order(orders)
+ orders.present? ? spawn(@relation.order(orders)) : spawn
+ end
+
+ def lock(locks = true)
+ case locks
+ when String
+ spawn(@relation.lock(locks))
+ when TrueClass, NilClass
+ spawn(@relation.lock)
+ else
+ spawn
+ end
+ end
+
+ def reverse_order
+ relation = spawn
+ relation.instance_variable_set(:@orders, nil)
+
+ order_clause = @relation.send(:order_clauses).join(', ')
+ if order_clause.present?
+ relation.order(reverse_sql_order(order_clause))
+ else
+ relation.order("#{@klass.table_name}.#{@klass.primary_key} DESC")
+ end
+ end
+
+ def limit(limits)
+ limits.present? ? spawn(@relation.take(limits)) : spawn
+ end
+
+ def offset(offsets)
+ offsets.present? ? spawn(@relation.skip(offsets)) : spawn
+ end
+
+ def on(join)
+ spawn(@relation.on(join))
+ end
+
+ def joins(join, join_type = nil)
+ return spawn if join.blank?
+
+ join_relation = case join
+ when String
+ @relation.join(join)
+ when Hash, Array, Symbol
+ if @klass.send(:array_of_strings?, join)
+ @relation.join(join.join(' '))
+ else
+ @relation.join(@klass.send(:build_association_joins, join))
+ end
+ else
+ @relation.join(join, join_type)
+ end
+
+ spawn(join_relation).tap { |r| r.readonly = true }
+ end
+
+ def where(*args)
+ return spawn if args.blank?
+
+ builder = PredicateBuilder.new(Arel::Sql::Engine.new(@klass))
+
+ conditions = if [String, Array].include?(args.first.class)
+ merged = @klass.send(:merge_conditions, args.size > 1 ? Array.wrap(args) : args.first)
+ Arel::SqlLiteral.new(merged) if merged
+ elsif args.first.is_a?(Hash)
+ attributes = @klass.send(:expand_hash_conditions_for_aggregates, args.first)
+ builder.build_from_hash(attributes, table)
+ else
+ args.first
+ end
+
+ conditions.is_a?(String) ? spawn(@relation.where(conditions)) : spawn(@relation.where(*conditions))
+ end
+
+ private
+
+ def reverse_sql_order(order_query)
+ order_query.to_s.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(',')
+ end
+
+ end
+end
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
new file mode 100644
index 0000000000..a637e97155
--- /dev/null
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -0,0 +1,75 @@
+module ActiveRecord
+ module SpawnMethods
+ def spawn(relation = @relation)
+ relation = Relation.new(@klass, relation)
+ relation.readonly = @readonly
+ relation.preload_associations = @preload_associations
+ relation.eager_load_associations = @eager_load_associations
+ relation.includes_associations = @includes_associations
+ relation.table = table
+ relation
+ end
+
+ def merge(r)
+ raise ArgumentError, "Cannot merge a #{r.klass.name} relation with #{@klass.name} relation" if r.klass != @klass
+
+ merged_relation = spawn(table).eager_load(r.eager_load_associations).preload(r.preload_associations).includes(r.includes_associations)
+ merged_relation.readonly = r.readonly
+
+ [self.relation, r.relation].each do |arel|
+ merged_relation = merged_relation.
+ joins(arel.joins(arel)).
+ group(arel.groupings).
+ limit(arel.taken).
+ offset(arel.skipped).
+ select(arel.send(:select_clauses)).
+ from(arel.sources).
+ having(arel.havings).
+ lock(arel.locked)
+ end
+
+ relation_order = r.send(:order_clause)
+ merged_order = relation_order.present? ? relation_order : order_clause
+ merged_relation = merged_relation.order(merged_order)
+
+ merged_wheres = @relation.wheres
+
+ r.wheres.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 }
+ end
+
+ merged_wheres << w
+ end
+
+ merged_relation.where(*merged_wheres)
+ end
+
+ alias :& :merge
+
+ def except(*skips)
+ result = Relation.new(@klass, table)
+ result.table = table
+
+ [:eager_load, :preload, :includes].each do |load_method|
+ result = result.send(load_method, send(:"#{load_method}_associations"))
+ end
+
+ result.readonly = self.readonly unless skips.include?(:readonly)
+
+ result = result.joins(@relation.joins(@relation)) unless skips.include?(:joins)
+ result = result.group(@relation.groupings) unless skips.include?(:group)
+ result = result.limit(@relation.taken) unless skips.include?(:limit)
+ result = result.offset(@relation.skipped) unless skips.include?(:offset)
+ result = result.select(@relation.send(:select_clauses)) unless skips.include?(:select)
+ result = result.from(@relation.sources) unless skips.include?(:from)
+ result = result.order(order_clause) unless skips.include?(:order)
+ result = result.where(*@relation.wheres) unless skips.include?(:where)
+ result = result.having(*@relation.havings) unless skips.include?(:having)
+ result = result.lock(@relation.locked) unless skips.include?(:lock)
+
+ result
+ end
+
+ end
+end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index e8a2a72735..12c1f23763 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -17,8 +17,6 @@ module ActiveRecord
module Validations
extend ActiveSupport::Concern
-
- include ActiveSupport::DeprecatedCallbacks
include ActiveModel::Validations
included do
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
index 92f47d770f..66b78682ad 100644
--- a/activerecord/lib/active_record/validations/associated.rb
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -1,5 +1,12 @@
module ActiveRecord
module Validations
+ class AssociatedValidator < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ return if (value.is_a?(Array) ? value : [value]).collect{ |r| r.nil? || r.valid? }.all?
+ record.errors.add(attribute, :invalid, :default => options[:message], :value => value)
+ end
+ end
+
module ClassMethods
# Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
#
@@ -33,13 +40,8 @@ module ActiveRecord
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_associated(*attr_names)
- configuration = attr_names.extract_options!
-
- validates_each(attr_names, configuration) do |record, attr_name, value|
- unless (value.is_a?(Array) ? value : [value]).collect { |r| r.nil? || r.valid? }.all?
- record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
- end
- end
+ options = attr_names.extract_options!
+ validates_with AssociatedValidator, options.merge(:attributes => attr_names)
end
end
end
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 711086dc2c..7efd312357 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -1,5 +1,78 @@
module ActiveRecord
module Validations
+ class UniquenessValidator < ActiveModel::EachValidator
+ def initialize(options)
+ @klass = options.delete(:klass)
+ super(options.reverse_merge(:case_sensitive => true))
+ end
+
+ def validate_each(record, attribute, value)
+ finder_class = find_finder_class_for(record)
+ table = finder_class.active_relation
+
+ table_name = record.class.quoted_table_name
+ sql, params = mount_sql_and_params(finder_class, table_name, attribute, value)
+
+ relation = table.where(sql, *params)
+
+ Array(options[:scope]).each do |scope_item|
+ scope_value = record.send(scope_item)
+ relation = relation.where(scope_item => scope_value)
+ end
+
+ unless record.new_record?
+ # TODO : This should be in Arel
+ relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
+ end
+
+ if relation.exists?
+ record.errors.add(attribute, :taken, :default => options[:message], :value => value)
+ end
+ end
+
+ protected
+
+ # The check for an existing value should be run from a class that
+ # isn't abstract. This means working down from the current class
+ # (self), to the first non-abstract class. Since classes don't know
+ # their subclasses, we have to build the hierarchy between self and
+ # the record's class.
+ def find_finder_class_for(record) #:nodoc:
+ class_hierarchy = [record.class]
+
+ while class_hierarchy.first != @klass
+ class_hierarchy.insert(0, class_hierarchy.first.superclass)
+ end
+
+ class_hierarchy.detect { |klass| !klass.abstract_class? }
+ end
+
+ def mount_sql_and_params(klass, table_name, attribute, value) #:nodoc:
+ column = klass.columns_hash[attribute.to_s]
+
+ operator = if value.nil?
+ "IS ?"
+ elsif column.text?
+ value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s
+ "#{klass.connection.case_sensitive_equality_operator} ?"
+ else
+ "= ?"
+ end
+
+ sql_attribute = "#{table_name}.#{klass.connection.quote_column_name(attribute)}"
+
+ if value.nil? || (options[:case_sensitive] || !column.text?)
+ sql = "#{sql_attribute} #{operator}"
+ params = [value]
+ else
+ sql = "LOWER(#{sql_attribute}) #{operator}"
+ params = [value.mb_chars.downcase]
+ end
+
+ [sql, params]
+ end
+ end
+
module ClassMethods
# Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
# can be named "davidhh".
@@ -69,6 +142,7 @@ module ActiveRecord
#
# This could even happen if you use transactions with the 'serializable'
# isolation level. There are several ways to get around this problem:
+ #
# - By locking the database table before validating, and unlocking it after
# saving. However, table locking is very expensive, and thus not
# recommended.
@@ -94,65 +168,10 @@ module ActiveRecord
# 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.
+ #
def validates_uniqueness_of(*attr_names)
- configuration = { :case_sensitive => true }
- configuration.update(attr_names.extract_options!)
-
- validates_each(attr_names,configuration) do |record, attr_name, value|
- # The check for an existing value should be run from a class that
- # isn't abstract. This means working down from the current class
- # (self), to the first non-abstract class. Since classes don't know
- # their subclasses, we have to build the hierarchy between self and
- # the record's class.
- class_hierarchy = [record.class]
- while class_hierarchy.first != self
- class_hierarchy.insert(0, class_hierarchy.first.superclass)
- end
-
- # Now we can work our way down the tree to the first non-abstract
- # class (which has a database table to query from).
- finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
-
- column = finder_class.columns_hash[attr_name.to_s]
-
- if value.nil?
- comparison_operator = "IS ?"
- elsif column.text?
- comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
- value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s
- else
- comparison_operator = "= ?"
- end
-
- sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
-
- if value.nil? || (configuration[:case_sensitive] || !column.text?)
- condition_sql = "#{sql_attribute} #{comparison_operator}"
- condition_params = [value]
- else
- condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}"
- condition_params = [value.mb_chars.downcase]
- end
-
- if scope = configuration[:scope]
- Array(scope).map do |scope_item|
- scope_value = record.send(scope_item)
- condition_sql << " AND " << attribute_condition("#{record.class.quoted_table_name}.#{scope_item}", scope_value)
- condition_params << scope_value
- end
- end
-
- unless record.new_record?
- condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
- condition_params << record.send(:id)
- end
-
- finder_class.with_exclusive_scope do
- if finder_class.exists?([condition_sql, *condition_params])
- record.errors.add(attr_name, :taken, :default => configuration[:message], :value => value)
- end
- end
- end
+ options = attr_names.extract_options!
+ validates_with UniquenessValidator, options.merge(:attributes => attr_names, :klass => self)
end
end
end
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index d5a4d9007b..ffa6d45948 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -61,14 +61,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_with_two_tables_in_from_without_getting_double_quoted
- posts = Post.find(:all,
- :select => "posts.*",
- :from => "authors, posts",
- :include => :comments,
- :conditions => "posts.author_id = authors.id",
- :order => "posts.id"
- )
-
+ posts = Post.select("posts.*").from("authors, posts").eager_load(:comments).where("posts.author_id = authors.id").order("posts.id").to_a
assert_equal 2, posts.first.comments.size
end
@@ -469,7 +462,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_and_limit_and_scoped_conditions_on_the_eagers
posts = nil
- Post.with_scope(:find => {
+ Post.send(:with_scope, :find => {
:include => :comments,
:conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'"
}) do
@@ -477,7 +470,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_equal 2, posts.size
end
- Post.with_scope(:find => {
+ Post.send(:with_scope, :find => {
:include => [ :comments, :author ],
:conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')"
}) do
@@ -487,7 +480,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_has_many_and_limit_and_scoped_and_explicit_conditions_on_the_eagers
- Post.with_scope(:find => { :conditions => "1=1" }) do
+ Post.send(:with_scope, :find => { :conditions => "1=1" }) do
posts = authors(:david).posts.find(:all,
:include => :comments,
:conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'",
@@ -506,7 +499,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_scoped_order_using_association_limiting_without_explicit_scope
posts_with_explicit_order = Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :order => 'posts.id DESC', :limit => 2)
- posts_with_scoped_order = Post.with_scope(:find => {:order => 'posts.id DESC'}) do
+ posts_with_scoped_order = Post.send(:with_scope, :find => {:order => 'posts.id DESC'}) do
Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :limit => 2)
end
assert_equal posts_with_explicit_order, posts_with_scoped_order
diff --git a/activerecord/test/cases/associations/habtm_join_table_test.rb b/activerecord/test/cases/associations/habtm_join_table_test.rb
index bf3e04c3eb..745f169ad7 100644
--- a/activerecord/test/cases/associations/habtm_join_table_test.rb
+++ b/activerecord/test/cases/associations/habtm_join_table_test.rb
@@ -36,21 +36,9 @@ class HabtmJoinTableTest < ActiveRecord::TestCase
uses_transaction :test_should_raise_exception_when_join_table_has_a_primary_key
def test_should_raise_exception_when_join_table_has_a_primary_key
if ActiveRecord::Base.connection.supports_primary_key?
- assert_raise ActiveRecord::ConfigurationError do
- jaime = MyReader.create(:name=>"Jaime")
- jaime.my_books << MyBook.create(:name=>'Great Expectations')
+ assert_raise ActiveRecord::HasAndBelongsToManyAssociationWithPrimaryKeyError do
+ MyReader.has_and_belongs_to_many :my_books
end
end
end
-
- uses_transaction :test_should_cache_result_of_primary_key_check
- def test_should_cache_result_of_primary_key_check
- if ActiveRecord::Base.connection.supports_primary_key?
- ActiveRecord::Base.connection.stubs(:primary_key).with('my_books_my_readers').returns(false).once
- weaz = MyReader.create(:name=>'Weaz')
-
- weaz.my_books << MyBook.create(:name=>'Great Expectations')
- weaz.my_books << MyBook.create(:name=>'Greater Expectations')
- end
- end
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 86d14c9c81..ce7eedbb54 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -1179,4 +1179,3 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal firm.name, client.firm_name
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 5f13b66d11..608d5a3608 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -137,6 +137,28 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert !posts(:welcome).reload.people(true).include?(people(:michael))
end
+ def test_replace_order_is_preserved
+ posts(:welcome).people.clear
+ posts(:welcome).people = [people(:david), people(:michael)]
+ assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order('id').map(&:person_id)
+
+ # Test the inverse order in case the first success was a coincidence
+ posts(:welcome).people.clear
+ posts(:welcome).people = [people(:michael), people(:david)]
+ assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order('id').map(&:person_id)
+ end
+
+ def test_replace_by_id_order_is_preserved
+ posts(:welcome).people.clear
+ posts(:welcome).person_ids = [people(:david).id, people(:michael).id]
+ assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order('id').map(&:person_id)
+
+ # Test the inverse order in case the first success was a coincidence
+ posts(:welcome).people.clear
+ posts(:welcome).person_ids = [people(:michael).id, people(:david).id]
+ assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order('id').map(&:person_id)
+ end
+
def test_associate_with_create
assert_queries(1) { posts(:thinking) }
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index 289c89d1e2..d359ad48c5 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -327,10 +327,4 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert !account.new_record?
assert_equal 500, account.credit_limit
end
-
- def test_create!_respects_hash_condition
- account = companies(:first_firm).create_account_limit_500_with_hash_conditions!
- assert !account.new_record?
- assert_equal 500, account.credit_limit
- 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 5f08c40005..18a1cd3cd0 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -9,84 +9,84 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
fixtures :authors, :posts, :comments, :categories, :categories_posts, :categorizations
def test_construct_finder_sql_creates_inner_joins
- sql = Author.send(:construct_finder_sql, :joins => :posts)
+ sql = Author.joins(:posts).to_sql
assert_match /INNER JOIN .?posts.? ON .?posts.?.author_id = authors.id/, sql
end
def test_construct_finder_sql_cascades_inner_joins
- sql = Author.send(:construct_finder_sql, :joins => {:posts => :comments})
+ sql = Author.joins(:posts => :comments).to_sql
assert_match /INNER JOIN .?posts.? ON .?posts.?.author_id = authors.id/, sql
assert_match /INNER JOIN .?comments.? ON .?comments.?.post_id = posts.id/, sql
end
def test_construct_finder_sql_inner_joins_through_associations
- sql = Author.send(:construct_finder_sql, :joins => :categorized_posts)
+ sql = Author.joins(:categorized_posts).to_sql
assert_match /INNER JOIN .?categorizations.?.*INNER JOIN .?posts.?/, sql
end
def test_construct_finder_sql_applies_association_conditions
- sql = Author.send(:construct_finder_sql, :joins => :categories_like_general, :conditions => "TERMINATING_MARKER")
+ sql = Author.joins(:categories_like_general).where("TERMINATING_MARKER").to_sql
assert_match /INNER JOIN .?categories.? ON.*AND.*.?General.?(.|\n)*TERMINATING_MARKER/, sql
end
def test_construct_finder_sql_applies_aliases_tables_on_association_conditions
- result = Author.find(:all, :joins => [:thinking_posts, :welcome_posts])
+ result = Author.joins(:thinking_posts, :welcome_posts).to_a
assert_equal authors(:david), result.first
end
def test_construct_finder_sql_unpacks_nested_joins
- sql = Author.send(:construct_finder_sql, :joins => {:posts => [[:comments]]})
+ sql = Author.joins(:posts => [[:comments]]).to_sql
assert_no_match /inner join.*inner join.*inner join/i, sql, "only two join clauses should be present"
assert_match /INNER JOIN .?posts.? ON .?posts.?.author_id = authors.id/, sql
assert_match /INNER JOIN .?comments.? ON .?comments.?.post_id = .?posts.?.id/, sql
end
def test_construct_finder_sql_ignores_empty_joins_hash
- sql = Author.send(:construct_finder_sql, :joins => {})
+ sql = Author.joins({}).to_sql
assert_no_match /JOIN/i, sql
end
def test_construct_finder_sql_ignores_empty_joins_array
- sql = Author.send(:construct_finder_sql, :joins => [])
+ sql = Author.joins([]).to_sql
assert_no_match /JOIN/i, sql
end
def test_find_with_implicit_inner_joins_honors_readonly_without_select
- authors = Author.find(:all, :joins => :posts)
+ authors = Author.joins(:posts).to_a
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| a.readonly? }, "expected all authors to be readonly"
end
def test_find_with_implicit_inner_joins_honors_readonly_with_select
- authors = Author.find(:all, :select => 'authors.*', :joins => :posts)
+ authors = Author.joins(:posts).select('authors.*').to_a
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
end
def test_find_with_implicit_inner_joins_honors_readonly_false
- authors = Author.find(:all, :joins => :posts, :readonly => false)
+ authors = Author.joins(:posts).readonly(false).to_a
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
end
def test_find_with_implicit_inner_joins_does_not_set_associations
- authors = Author.find(:all, :select => 'authors.*', :joins => :posts)
+ authors = Author.joins(:posts).select('authors.*')
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| !a.send(:instance_variable_names).include?("@posts")}, "expected no authors to have the @posts association loaded"
end
def test_count_honors_implicit_inner_joins
- real_count = Author.find(:all).sum{|a| a.posts.count }
+ real_count = Author.scoped.to_a.sum{|a| a.posts.count }
assert_equal real_count, Author.count(:joins => :posts), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins
- real_count = Author.find(:all).sum{|a| a.posts.count }
+ real_count = Author.scoped.to_a.sum{|a| a.posts.count }
assert_equal real_count, Author.calculate(:count, 'authors.id', :joins => :posts), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
- real_count = Author.find(:all).select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
+ real_count = Author.scoped.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
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
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index 47f83db112..1d7604f52b 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -85,7 +85,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
fixtures :men, :faces
def test_parent_instance_should_be_shared_with_child_on_find
- m = Man.find(:first)
+ m = men(:gordon)
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -96,7 +96,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
- m = Man.find(:first, :include => :face)
+ m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :face)
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -104,7 +104,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
f.man.name = 'Mungo'
assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
- m = Man.find(:first, :include => :face, :order => 'faces.id')
+ m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :face, :order => 'faces.id')
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -114,7 +114,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_newly_built_child
- m = Man.find(:first)
+ m = men(:gordon)
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 = Man.find(:first)
+ m = men(:gordon)
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"
@@ -135,6 +135,86 @@ class InverseHasOneTests < ActiveRecord::TestCase
assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
end
+ def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method
+ m = Man.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)
+ assert_not_nil f.man
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_replaced_via_accessor_child
+ m = Man.find(:first)
+ f = Face.new(:description => 'haunted')
+ m.face = f
+ assert_not_nil f.man
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+
+ def test_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
@@ -144,7 +224,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
fixtures :men, :interests
def test_parent_instance_should_be_shared_with_every_child_on_find
- m = Man.find(:first)
+ m = men(:gordon)
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -156,7 +236,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_eager_loaded_children
- m = Man.find(:first, :include => :interests)
+ m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :interests)
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -166,7 +246,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
- m = Man.find(:first, :include => :interests, :order => 'interests.id')
+ m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :interests, :order => 'interests.id')
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -175,11 +255,10 @@ class InverseHasManyTests < ActiveRecord::TestCase
i.man.name = 'Mungo'
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
-
end
def test_parent_instance_should_be_shared_with_newly_built_child
- m = Man.find(:first)
+ 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"
@@ -189,8 +268,20 @@ 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
+ 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'}
+ assert_not_nil i.topic, "Child attributes supplied to build via blocks should be populated"
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_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"
@@ -200,8 +291,31 @@ class InverseHasManyTests < ActiveRecord::TestCase
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_poked_in_child
+ 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')
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_block_style_created_child
+ m = Man.find(:first)
+ i = m.interests.create {|ii| ii.topic = 'Industrial Revolution Re-enactment'}
+ assert_not_nil i.topic, "Child attributes supplied to create via blocks should be populated"
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_poked_in_child
+ m = men(:gordon)
i = Interest.create(:topic => 'Industrial Revolution Re-enactment')
m.interests << i
assert_not_nil i.man
@@ -212,6 +326,30 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
end
+ def test_parent_instance_should_be_shared_with_replaced_via_accessor_children
+ m = Man.find(:first)
+ i = Interest.new(:topic => 'Industrial Revolution Re-enactment')
+ m.interests = [i]
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_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
@@ -221,7 +359,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
fixtures :men, :faces, :interests
def test_child_instance_should_be_shared_with_parent_on_find
- f = Face.find(:first)
+ f = faces(:trusting)
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -231,7 +369,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
- f = Face.find(:first, :include => :man)
+ f = Face.find(:first, :include => :man, :conditions => {:description => 'trusting'})
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -239,8 +377,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
m.face.description = 'pleasing'
assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
-
- f = Face.find(:first, :include => :man, :order => 'men.id')
+ f = Face.find(:first, :include => :man, :order => 'men.id', :conditions => {:description => 'trusting'})
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -250,7 +387,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
end
def test_child_instance_should_be_shared_with_newly_built_parent
- f = Face.find(:first)
+ f = faces(:trusting)
m = f.build_man(:name => 'Charles')
assert_not_nil m.face
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
@@ -261,7 +398,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
end
def test_child_instance_should_be_shared_with_newly_created_parent
- f = Face.find(:first)
+ f = faces(:trusting)
m = f.create_man(:name => 'Charles')
assert_not_nil m.face
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
@@ -272,7 +409,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
end
def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
- i = Interest.find(:first)
+ i = interests(:trainspotting)
m = i.man
assert_not_nil m.interests
iz = m.interests.detect {|iz| iz.id == i.id}
@@ -284,11 +421,128 @@ class InverseBelongsToTests < ActiveRecord::TestCase
assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to parent-owned instance"
end
+ def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
+ f = Face.find(:first)
+ m = Man.new(:name => 'Charles')
+ f.man = m
+ assert_not_nil m.face
+ assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
+ m.face.description = 'pleasing'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
+ end
+
+ def test_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
end
+class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
+ fixtures :men, :faces, :interests
+
+ def test_child_instance_should_be_shared_with_parent_on_find
+ f = Face.find(:first, :conditions => {:description => 'confused'})
+ m = f.polymorphic_man
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
+ m.polymorphic_face.description = 'pleasing'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
+ end
+
+ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
+ f = Face.find(:first, :conditions => {:description => 'confused'}, :include => :man)
+ m = f.polymorphic_man
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
+ m.polymorphic_face.description = 'pleasing'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
+
+ f = Face.find(:first, :conditions => {:description => 'confused'}, :include => :man, :order => 'men.id')
+ m = f.polymorphic_man
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
+ m.polymorphic_face.description = 'pleasing'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
+ end
+
+ def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
+ face = faces(:confused)
+ old_man = face.polymorphic_man
+ new_man = Man.new
+
+ assert_not_nil face.polymorphic_man
+ face.polymorphic_man = new_man
+
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
+ face.description = 'Bongo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to parent instance"
+ new_man.polymorphic_face.description = 'Mungo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
+ end
+
+ def test_child_instance_should_be_shared_with_replaced_via_method_parent
+ face = faces(:confused)
+ old_man = face.polymorphic_man
+ new_man = Man.new
+
+ assert_not_nil face.polymorphic_man
+ face.polymorphic_man.replace(new_man)
+
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
+ face.description = 'Bongo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to parent instance"
+ new_man.polymorphic_face.description = 'Mungo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
+ end
+
+ def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
+ i = interests(:llama_wrangling)
+ m = i.polymorphic_man
+ assert_not_nil m.polymorphic_interests
+ iz = m.polymorphic_interests.detect {|iz| iz.id == i.id}
+ assert_not_nil iz
+ assert_equal i.topic, iz.topic, "Interest topics should be the same before changes to child"
+ i.topic = 'Eating cheese with a spoon'
+ assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to child"
+ iz.topic = 'Cow tipping'
+ assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to parent-owned instance"
+ end
+
+ def test_trying_to_access_inverses_that_dont_exist_shouldnt_raise_an_error
+ # Ideally this would, if only for symmetry's sake with other association types
+ assert_nothing_raised(ActiveRecord::InverseOfAssociationNotFoundError) { Face.find(:first).horrible_polymorphic_man }
+ end
+
+ def test_trying_to_set_polymorphic_inverses_that_dont_exist_at_all_should_raise_an_error
+ # fails because no class has the correct inverse_of for horrible_polymorphic_man
+ assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.find(:first).horrible_polymorphic_man = Man.first }
+ end
+
+ def test_trying_to_set_polymorphic_inverses_that_dont_exist_on_the_instance_being_set_should_raise_an_error
+ # passes because Man does have the correct inverse_of
+ assert_nothing_raised(ActiveRecord::InverseOfAssociationNotFoundError) { Face.find(:first).polymorphic_man = Man.first }
+ # fails because Interest does have the correct inverse_of
+ assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.find(:first).polymorphic_man = Interest.first }
+ end
+end
+
# NOTE - these tests might not be meaningful, ripped as they were from the parental_control plugin
# which would guess the inverse rather than look for an explicit configuration option.
class InverseMultipleHasManyInversesForSameModel < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index e429c1d157..9bc34bd750 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -64,6 +64,16 @@ 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_force_reload_is_uncached
+ firm = Firm.create!("name" => "A New Firm, Inc")
+ client = Client.create!("name" => "TheClient.com", :firm => firm)
+ ActiveRecord::Base.cache do
+ firm.clients.each {}
+ assert_queries(0) { assert_not_nil firm.clients.each {} }
+ assert_queries(1) { assert_not_nil firm.clients(true).each {} }
+ end
+ end
end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 9164701601..cf763d730a 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -31,11 +31,40 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
assert base.valid_keys_for_has_and_belongs_to_many_association.include?(:autosave)
end
+ def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
+ assert_no_difference_when_adding_callbacks_twice_for Pirate, :ship
+ end
+
+ def test_should_not_add_the_same_callbacks_multiple_times_for_belongs_to
+ assert_no_difference_when_adding_callbacks_twice_for Ship, :pirate
+ end
+
+ def test_should_not_add_the_same_callbacks_multiple_times_for_has_many
+ assert_no_difference_when_adding_callbacks_twice_for Pirate, :birds
+ end
+
+ def test_should_not_add_the_same_callbacks_multiple_times_for_has_and_belongs_to_many
+ assert_no_difference_when_adding_callbacks_twice_for Pirate, :parrots
+ end
+
private
def base
ActiveRecord::Base
end
+
+ def assert_no_difference_when_adding_callbacks_twice_for(model, association_name)
+ reflection = model.reflect_on_association(association_name)
+ assert_no_difference "callbacks_for_model(#{model.name}).length" do
+ model.send(:add_autosave_association_callbacks, reflection)
+ end
+ end
+
+ def callbacks_for_model(model)
+ model.instance_variables.grep(/_callbacks$/).map do |ivar|
+ model.instance_variable_get(ivar)
+ end.flatten
+ end
end
class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
@@ -757,14 +786,14 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_automatically_validate_the_associated_model
@pirate.ship.name = ''
assert @pirate.invalid?
- assert @pirate.errors[:ship_name].any?
+ assert @pirate.errors[:"ship.name"].any?
end
def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
@pirate.ship.name = nil
@pirate.catchphrase = nil
assert @pirate.invalid?
- assert @pirate.errors[:ship_name].any?
+ assert @pirate.errors[:"ship.name"].any?
assert @pirate.errors[:catchphrase].any?
end
@@ -857,7 +886,7 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_automatically_validate_the_associated_model
@ship.pirate.catchphrase = ''
assert @ship.invalid?
- assert @ship.errors[:pirate_catchphrase].any?
+ assert @ship.errors[:"pirate.catchphrase"].any?
end
def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_is_not_valid
@@ -865,7 +894,7 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
@ship.pirate.catchphrase = nil
assert @ship.invalid?
assert @ship.errors[:name].any?
- assert @ship.errors[:pirate_catchphrase].any?
+ assert @ship.errors[:"pirate.catchphrase"].any?
end
def test_should_still_allow_to_bypass_validations_on_the_associated_model
@@ -932,7 +961,7 @@ module AutosaveAssociationOnACollectionAssociationTests
@pirate.send(@association_name).each { |child| child.name = '' }
assert !@pirate.valid?
- assert_equal ["can't be blank"], @pirate.errors["#{@association_name}_name"]
+ assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
assert @pirate.errors[@association_name].empty?
end
@@ -940,8 +969,25 @@ module AutosaveAssociationOnACollectionAssociationTests
@pirate.send(@association_name).build(:name => '')
assert !@pirate.valid?
- assert_equal ["can't be blank"], @pirate.errors["#{@association_name}_name"]
+ assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
+ assert @pirate.errors[@association_name].empty?
+ end
+
+ def test_should_default_invalid_error_from_i18n
+ I18n.backend.store_translations(:en, :activerecord => { :errors => { :models =>
+ { @association_name.to_s.singularize.to_sym => { :blank => "cannot be blank" } }
+ }})
+
+ @pirate.send(@association_name).build(:name => '')
+
+ assert !@pirate.valid?
+ assert_equal ["cannot be blank"], @pirate.errors["#{@association_name}.name"]
+ assert_equal ["#{@association_name.to_s.titleize} name cannot be blank"], @pirate.errors.full_messages
assert @pirate.errors[@association_name].empty?
+ ensure
+ I18n.backend.store_translations(:en, :activerecord => { :errors => { :models =>
+ { @association_name.to_s.singularize.to_sym => nil }
+ }})
end
def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
@@ -949,7 +995,7 @@ module AutosaveAssociationOnACollectionAssociationTests
@pirate.catchphrase = nil
assert !@pirate.valid?
- assert_equal ["can't be blank"], @pirate.errors["#{@association_name}_name"]
+ assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
assert @pirate.errors[:catchphrase].any?
end
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 5c2911eca1..730d9d8df7 100755
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -201,7 +201,7 @@ class BasicsTest < ActiveRecord::TestCase
topic = Topic.new(:title => "New Topic")
assert topic.save!
- reply = Reply.new
+ reply = WrongReply.new
assert_raise(ActiveRecord::RecordInvalid) { reply.save! }
end
@@ -680,6 +680,16 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal -2, Topic.find(2).replies_count
end
+ def test_reset_counters
+ assert_equal 1, Topic.find(1).replies_count
+
+ Topic.increment_counter("replies_count", 1)
+ assert_equal 2, Topic.find(1).replies_count
+
+ Topic.reset_counters(1, :replies)
+ assert_equal 1, Topic.find(1).replies_count
+ end
+
def test_update_counter
category = categories(:general)
assert_nil category.categorizations_count
@@ -949,6 +959,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_update_attributes!
+ Reply.validates_presence_of(:title)
reply = Reply.find(2)
assert_equal "The Second Topic of the day", reply.title
assert_equal "Have a nice day", reply.content
@@ -964,6 +975,8 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "Have a nice day", reply.content
assert_raise(ActiveRecord::RecordInvalid) { reply.update_attributes!(:title => nil, :content => "Have a nice evening") }
+ ensure
+ Reply.reset_callbacks(:validate)
end
def test_mass_assignment_should_raise_exception_if_accessible_and_protected_attribute_writers_are_both_used
@@ -1815,7 +1828,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_scoped_find_conditions
- scoped_developers = Developer.with_scope(:find => { :conditions => 'salary > 90000' }) do
+ scoped_developers = Developer.send(:with_scope, :find => { :conditions => 'salary > 90000' }) do
Developer.find(:all, :conditions => 'id < 5')
end
assert !scoped_developers.include?(developers(:david)) # David's salary is less than 90,000
@@ -1823,7 +1836,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_scoped_find_limit_offset
- scoped_developers = Developer.with_scope(:find => { :limit => 3, :offset => 2 }) do
+ scoped_developers = Developer.send(:with_scope, :find => { :limit => 3, :offset => 2 }) do
Developer.find(:all, :order => 'id')
end
assert !scoped_developers.include?(developers(:david))
@@ -1837,17 +1850,17 @@ class BasicsTest < ActiveRecord::TestCase
def test_scoped_find_order
# Test order in scope
- scoped_developers = Developer.with_scope(:find => { :limit => 1, :order => 'salary DESC' }) do
+ scoped_developers = Developer.send(:with_scope, :find => { :limit => 1, :order => 'salary DESC' }) do
Developer.find(:all)
end
assert_equal 'Jamis', scoped_developers.first.name
assert scoped_developers.include?(developers(:jamis))
# Test scope without order and order in find
- scoped_developers = Developer.with_scope(:find => { :limit => 1 }) do
+ 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
- scoped_developers = Developer.with_scope(:find => { :limit => 3, :order => 'id DESC' }) do
+ 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))
@@ -1859,7 +1872,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_scoped_find_limit_offset_including_has_many_association
- topics = Topic.with_scope(:find => {:limit => 1, :offset => 1, :include => :replies}) do
+ topics = Topic.send(:with_scope, :find => {:limit => 1, :offset => 1, :include => :replies}) do
Topic.find(:all, :order => "topics.id")
end
assert_equal 1, topics.size
@@ -1867,7 +1880,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_scoped_find_order_including_has_many_association
- developers = Developer.with_scope(:find => { :order => 'developers.salary DESC', :include => :projects }) do
+ developers = Developer.send(:with_scope, :find => { :order => 'developers.salary DESC', :include => :projects }) do
Developer.find(:all)
end
assert developers.size >= 2
@@ -1877,7 +1890,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_scoped_find_with_group_and_having
- developers = Developer.with_scope(:find => { :group => 'developers.salary', :having => "SUM(salary) > 10000", :select => "SUM(salary) as salary" }) do
+ developers = Developer.send(:with_scope, :find => { :group => 'developers.salary', :having => "SUM(salary) > 10000", :select => "SUM(salary) as salary" }) do
Developer.find(:all)
end
assert_equal 3, developers.size
@@ -1892,8 +1905,14 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal Developer.find(:first, :order => 'id desc'), Developer.last
end
+ def test_all
+ developers = Developer.all
+ assert_kind_of Array, developers
+ assert_equal Developer.find(:all), developers
+ end
+
def test_all_with_conditions
- assert_equal Developer.find(:all, :order => 'id desc'), Developer.all.order('id desc').to_a
+ assert_equal Developer.find(:all, :order => 'id desc'), Developer.order('id desc').all
end
def test_find_ordered_last
@@ -1917,7 +1936,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_find_scoped_ordered_last
- last_developer = Developer.with_scope(:find => { :order => 'developers.salary ASC' }) do
+ last_developer = Developer.send(:with_scope, :find => { :order => 'developers.salary ASC' }) do
Developer.find(:last)
end
assert_equal last_developer, Developer.find(:all, :order => 'developers.salary ASC').last
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index 5009a90846..e417d8a803 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -5,7 +5,7 @@ class EachTest < ActiveRecord::TestCase
fixtures :posts
def setup
- @posts = Post.all(:order => "id asc")
+ @posts = Post.order("id asc")
@total = Post.count
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 004f4d0ea6..bd2d471fc7 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -29,8 +29,8 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
- assert_equal 0, NumericData.send(:type_cast_calculated_value, 0, nil, 'avg')
- assert_equal 53.0, NumericData.send(:type_cast_calculated_value, 53, nil, 'avg')
+ assert_equal 0, NumericData.scoped.send(:type_cast_calculated_value, 0, nil, 'avg')
+ assert_equal 53.0, NumericData.scoped.send(:type_cast_calculated_value, 53, nil, 'avg')
end
def test_should_get_maximum_of_field
@@ -42,7 +42,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_get_maximum_of_field_with_scoped_include
- Account.with_scope :find => { :include => :firm, :conditions => "companies.name != 'Summit'" } do
+ Account.send :with_scope, :find => { :include => :firm, :conditions => "companies.name != 'Summit'" } do
assert_equal 50, Account.maximum(:credit_limit)
end
end
@@ -248,17 +248,15 @@ class CalculationsTest < ActiveRecord::TestCase
def test_should_reject_invalid_options
assert_nothing_raised do
- [:count, :sum].each do |func|
- # empty options are valid
- Company.send(:validate_calculation_options, func)
- # these options are valid for all calculations
- [:select, :conditions, :joins, :order, :group, :having, :distinct].each do |opt|
- Company.send(:validate_calculation_options, func, opt => true)
- end
+ # empty options are valid
+ Company.send(:validate_calculation_options)
+ # these options are valid for all calculations
+ [:select, :conditions, :joins, :order, :group, :having, :distinct].each do |opt|
+ Company.send(:validate_calculation_options, opt => true)
end
# :include is only valid on :count
- Company.send(:validate_calculation_options, :count, :include => true)
+ Company.send(:validate_calculation_options, :include => true)
end
assert_raise(ArgumentError) { Company.send(:validate_calculation_options, :sum, :foo => :bar) }
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
index f456d273fe..4961d12a44 100644
--- a/activerecord/test/cases/dirty_test.rb
+++ b/activerecord/test/cases/dirty_test.rb
@@ -301,7 +301,7 @@ class DirtyTest < ActiveRecord::TestCase
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"})
- topic = Topic.first(:select => 'id, author_name')
+ topic = Topic.select('id, author_name').first
topic.update_attribute :author_name, 'John'
topic = Topic.first
assert_not_nil topic.content
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 3de07797d4..d2451f24c1 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -120,7 +120,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_exists_with_scoped_include
- Developer.with_scope(:find => { :include => :projects, :order => "projects.name" }) do
+ Developer.send(:with_scope, :find => { :include => :projects, :order => "projects.name" }) do
assert Developer.exists?
end
end
@@ -233,11 +233,11 @@ class FinderTest < ActiveRecord::TestCase
end
def test_first
- assert_equal topics(:second).title, Topic.first(:conditions => "title = 'The Second Topic of the day'").title
+ assert_equal topics(:second).title, Topic.where("title = 'The Second Topic of the day'").first.title
end
def test_first_failing
- assert_nil Topic.first(:conditions => "title = 'The Second Topic of the day!'")
+ assert_nil Topic.where("title = 'The Second Topic of the day!'").first
end
def test_unexisting_record_exception_handling
@@ -291,7 +291,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_hash_conditions_on_joined_table
- firms = Firm.all :joins => :account, :conditions => {:accounts => { :credit_limit => 50 }}
+ firms = Firm.joins(:account).where(:accounts => { :credit_limit => 50 })
assert_equal 1, firms.size
assert_equal companies(:first_firm), firms.first
end
@@ -571,21 +571,6 @@ class FinderTest < ActiveRecord::TestCase
assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
end
- def test_dynamic_finders_should_go_through_the_find_class_method
- Topic.expects(:find).with(:first, :conditions => { :title => 'The First Topic!' })
- Topic.find_by_title("The First Topic!")
-
- Topic.expects(:find).with(:last, :conditions => { :title => 'The Last Topic!' })
- Topic.find_last_by_title("The Last Topic!")
-
- Topic.expects(:find).with(:all, :conditions => { :title => 'A Topic.' })
- Topic.find_all_by_title("A Topic.")
-
- Topic.expects(:find).with(:first, :conditions => { :title => 'Does not exist yet for sure!' }).times(2)
- Topic.find_or_initialize_by_title('Does not exist yet for sure!')
- Topic.find_or_create_by_title('Does not exist yet for sure!')
- end
-
def test_find_by_one_attribute
assert_equal topics(:first), Topic.find_by_title("The First Topic")
assert_nil Topic.find_by_title("The First Topic!")
@@ -596,21 +581,6 @@ class FinderTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::RecordNotFound) { Topic.find_by_title!("The First Topic!") }
end
- def test_find_by_one_attribute_caches_dynamic_finder
- # ensure this test can run independently of order
- class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
- assert !Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
- t = Topic.find_by_title("The First Topic")
- assert Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
- end
-
- def test_dynamic_finder_returns_same_results_after_caching
- # ensure this test can run independently of order
- class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.public_method_defined?(:find_by_title)
- t = Topic.find_by_title("The First Topic")
- assert_equal t, Topic.find_by_title("The First Topic") # find_by_title has been cached
- end
-
def test_find_by_one_attribute_with_order_option
assert_equal accounts(:signals37), Account.find_by_credit_limit(50, :order => 'id')
assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :order => 'id DESC')
@@ -654,14 +624,6 @@ class FinderTest < ActiveRecord::TestCase
assert_equal customers(:david), found_customer
end
- def test_dynamic_finder_on_one_attribute_with_conditions_caches_method
- # ensure this test can run independently of order
- class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
- assert !Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
- a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
- assert Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
- end
-
def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
# ensure this test can run independently of order
class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
@@ -694,14 +656,6 @@ class FinderTest < ActiveRecord::TestCase
assert_nil Topic.find_last_by_title("A title with no matches")
end
- def test_find_last_by_one_attribute_caches_dynamic_finder
- # ensure this test can run independently of order
- class << Topic; self; end.send(:remove_method, :find_last_by_title) if Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
- assert !Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
- t = Topic.find_last_by_title(Topic.last.title)
- assert Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
- end
-
def test_find_last_by_invalid_method_syntax
assert_raise(NoMethodError) { Topic.fail_to_find_last_by_title("The First Topic") }
assert_raise(NoMethodError) { Topic.find_last_by_title?("The First Topic") }
@@ -926,13 +880,6 @@ class FinderTest < ActiveRecord::TestCase
assert !c.new_record?
end
- def test_dynamic_find_or_initialize_from_one_attribute_caches_method
- class << Company; self; end.send(:remove_method, :find_or_initialize_by_name) if Company.public_methods.any? { |m| m.to_s == 'find_or_initialize_by_name' }
- assert !Company.public_methods.any? { |m| m.to_s == 'find_or_initialize_by_name' }
- sig38 = Company.find_or_initialize_by_name("38signals")
- assert Company.public_methods.any? { |m| m.to_s == 'find_or_initialize_by_name' }
- 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
@@ -1075,8 +1022,8 @@ class FinderTest < ActiveRecord::TestCase
def test_finder_with_scoped_from
all_topics = Topic.find(:all)
- Topic.with_scope(:find => { :from => 'fake_topics' }) do
- assert_equal all_topics, Topic.all(:from => 'topics').to_a
+ Topic.send(:with_scope, :find => { :from => 'fake_topics' }) do
+ assert_equal all_topics, Topic.from('topics').to_a
end
end
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index 25613da912..479970b2fa 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -1,11 +1,9 @@
-root = File.expand_path('../../../..', __FILE__)
begin
- require "#{root}/vendor/gems/environment"
+ require File.expand_path('../../../../vendor/gems/environment', __FILE__)
rescue LoadError
- $:.unshift("#{root}/activesupport/lib")
end
-lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib")
+lib = File.expand_path('../../../lib', __FILE__)
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'config'
@@ -49,11 +47,6 @@ ActiveRecord::Base.connection.class.class_eval do
alias_method_chain :execute, :query_record
end
-# Make with_scope public for tests
-class << ActiveRecord::Base
- public :with_scope, :with_exclusive_scope
-end
-
unless ENV['FIXTURE_DEBUG']
module ActiveRecord::TestFixtures::ClassMethods
def try_to_load_dependency_with_silence(*args)
@@ -64,9 +57,10 @@ unless ENV['FIXTURE_DEBUG']
end
end
+require "cases/validations_repair_helper"
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
- include ActiveModel::ValidationsRepairHelper
+ include ActiveRecord::ValidationsRepairHelper
self.fixture_path = FIXTURES_ROOT
self.use_instantiated_fixtures = false
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index f946e8699e..dfaecf35cf 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -38,24 +38,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
end
- def test_lock_destroy
- p1 = Person.find(1)
- p2 = Person.find(1)
- assert_equal 0, p1.lock_version
- assert_equal 0, p2.lock_version
-
- p1.first_name = 'stu'
- p1.save!
- assert_equal 1, p1.lock_version
- assert_equal 0, p2.lock_version
-
- assert_raises(ActiveRecord::StaleObjectError) { p2.destroy }
-
- assert p1.destroy
- assert_equal true, p1.frozen?
- assert_raises(ActiveRecord::RecordNotFound) { Person.find(1) }
- end
-
def test_lock_repeating
p1 = Person.find(1)
p2 = Person.find(1)
@@ -243,7 +225,7 @@ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
def test_sane_find_with_scoped_lock
assert_nothing_raised do
Person.transaction do
- Person.with_scope(:find => { :lock => true }) do
+ Person.send(:with_scope, :find => { :lock => true }) do
Person.find 1
end
end
diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb
index eb4ce0e774..cfc6f8772c 100644
--- a/activerecord/test/cases/method_scoping_test.rb
+++ b/activerecord/test/cases/method_scoping_test.rb
@@ -10,19 +10,19 @@ class MethodScopingTest < ActiveRecord::TestCase
fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects
def test_set_conditions
- Developer.with_scope(:find => { :conditions => 'just a test...' }) do
+ Developer.send(:with_scope, :find => { :conditions => 'just a test...' }) do
assert_equal 'just a test...', Developer.send(:current_scoped_methods)[:find][:conditions]
end
end
def test_scoped_find
- Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
assert_nothing_raised { Developer.find(1) }
end
end
def test_scoped_find_first
- Developer.with_scope(:find => { :conditions => "salary = 100000" }) do
+ Developer.send(:with_scope, :find => { :conditions => "salary = 100000" }) do
assert_equal Developer.find(10), Developer.find(:first, :order => 'name')
end
end
@@ -30,7 +30,7 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_scoped_find_last
highest_salary = Developer.find(:first, :order => "salary DESC")
- Developer.with_scope(:find => { :order => "salary" }) do
+ Developer.send(:with_scope, :find => { :order => "salary" }) do
assert_equal highest_salary, Developer.last
end
end
@@ -39,38 +39,38 @@ class MethodScopingTest < ActiveRecord::TestCase
lowest_salary = Developer.find(:first, :order => "salary ASC")
highest_salary = Developer.find(:first, :order => "salary DESC")
- Developer.with_scope(:find => { :order => "salary" }) do
+ Developer.send(:with_scope, :find => { :order => "salary" }) do
assert_equal highest_salary, Developer.last
assert_equal lowest_salary, Developer.first
end
end
def test_scoped_find_combines_conditions
- Developer.with_scope(:find => { :conditions => "salary = 9000" }) do
+ Developer.send(:with_scope, :find => { :conditions => "salary = 9000" }) do
assert_equal developers(:poor_jamis), Developer.find(:first, :conditions => "name = 'Jamis'")
end
end
def test_scoped_find_sanitizes_conditions
- Developer.with_scope(:find => { :conditions => ['salary = ?', 9000] }) do
+ Developer.send(:with_scope, :find => { :conditions => ['salary = ?', 9000] }) do
assert_equal developers(:poor_jamis), Developer.find(:first)
end
end
def test_scoped_find_combines_and_sanitizes_conditions
- Developer.with_scope(:find => { :conditions => ['salary = ?', 9000] }) do
+ Developer.send(:with_scope, :find => { :conditions => ['salary = ?', 9000] }) do
assert_equal developers(:poor_jamis), Developer.find(:first, :conditions => ['name = ?', 'Jamis'])
end
end
def test_scoped_find_all
- Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
assert_equal [developers(:david)], Developer.find(:all)
end
end
def test_scoped_find_select
- Developer.with_scope(:find => { :select => "id, name" }) do
+ Developer.send(:with_scope, :find => { :select => "id, name" }) do
developer = Developer.find(:first, :conditions => "name = 'David'")
assert_equal "David", developer.name
assert !developer.has_attribute?(:salary)
@@ -78,7 +78,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_options_select_replaces_scope_select
- Developer.with_scope(:find => { :select => "id, name" }) do
+ Developer.send(:with_scope, :find => { :select => "id, name" }) do
developer = Developer.find(:first, :select => 'id, salary', :conditions => "name = 'David'")
assert_equal 80000, developer.salary
assert !developer.has_attribute?(:name)
@@ -86,11 +86,11 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_count
- Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
assert_equal 1, Developer.count
end
- Developer.with_scope(:find => { :conditions => 'salary = 100000' }) do
+ Developer.send(:with_scope, :find => { :conditions => 'salary = 100000' }) do
assert_equal 8, Developer.count
assert_equal 1, Developer.count(:conditions => "name LIKE 'fixture_1%'")
end
@@ -98,7 +98,7 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_scoped_find_include
# with the include, will retrieve only developers for the given project
- scoped_developers = Developer.with_scope(:find => { :include => :projects }) do
+ scoped_developers = Developer.send(:with_scope, :find => { :include => :projects }) do
Developer.find(:all, :conditions => 'projects.id = 2')
end
assert scoped_developers.include?(developers(:david))
@@ -107,7 +107,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_joins
- scoped_developers = Developer.with_scope(:find => { :joins => 'JOIN developers_projects ON id = developer_id' } ) do
+ scoped_developers = Developer.send(:with_scope, :find => { :joins => 'JOIN developers_projects ON id = developer_id' } ) do
Developer.find(:all, :conditions => 'developers_projects.project_id = 2')
end
assert scoped_developers.include?(developers(:david))
@@ -117,7 +117,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_using_new_style_joins
- scoped_developers = Developer.with_scope(:find => { :joins => :projects }) do
+ scoped_developers = Developer.send(:with_scope, :find => { :joins => :projects }) do
Developer.find(:all, :conditions => 'projects.id = 2')
end
assert scoped_developers.include?(developers(:david))
@@ -127,7 +127,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_merges_old_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id ' }) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id ' }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'INNER JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
@@ -137,7 +137,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_merges_new_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => :posts }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => :comments, :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
@@ -147,7 +147,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_merges_new_and_old_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => :posts }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
@@ -157,7 +157,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_merges_string_array_style_and_string_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => ["INNER JOIN posts ON posts.author_id = authors.id"]}) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => ["INNER JOIN posts ON posts.author_id = authors.id"]}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'INNER JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
@@ -167,7 +167,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_merges_string_array_style_and_hash_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => :posts}) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => :posts}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => ['INNER JOIN comments ON posts.id = comments.post_id'], :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
@@ -177,7 +177,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_merges_joins_and_eliminates_duplicate_string_joins
- scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON posts.author_id = authors.id'}) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => 'INNER JOIN posts ON posts.author_id = authors.id'}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => ["INNER JOIN posts ON posts.author_id = authors.id", "INNER JOIN comments ON posts.id = comments.post_id"], :conditions => 'comments.id = 1')
end
assert scoped_authors.include?(authors(:david))
@@ -187,7 +187,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_find_strips_spaces_from_string_joins_and_eliminates_duplicate_string_joins
- scoped_authors = Author.with_scope(:find => { :joins => ' INNER JOIN posts ON posts.author_id = authors.id '}) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => ' INNER JOIN posts ON posts.author_id = authors.id '}) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => ['INNER JOIN posts ON posts.author_id = authors.id'], :conditions => 'posts.id = 1')
end
assert scoped_authors.include?(authors(:david))
@@ -198,7 +198,7 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_scoped_count_include
# with the include, will retrieve only developers for the given project
- Developer.with_scope(:find => { :include => :projects }) do
+ Developer.send(:with_scope, :find => { :include => :projects }) do
assert_equal 1, Developer.count(:conditions => 'projects.id = 2')
end
end
@@ -206,7 +206,7 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_scoped_create
new_comment = nil
- VerySpecialComment.with_scope(:create => { :post_id => 1 }) do
+ VerySpecialComment.send(:with_scope, :create => { :post_id => 1 }) do
assert_equal({ :post_id => 1 }, VerySpecialComment.send(:current_scoped_methods)[:create])
new_comment = VerySpecialComment.create :body => "Wonderful world"
end
@@ -216,14 +216,14 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_immutable_scope
options = { :conditions => "name = 'David'" }
- Developer.with_scope(:find => options) do
+ Developer.send(:with_scope, :find => options) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
options[:conditions] = "name != 'David'"
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
scope = { :find => { :conditions => "name = 'David'" }}
- Developer.with_scope(scope) do
+ Developer.send(:with_scope, scope) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
scope[:find][:conditions] = "name != 'David'"
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
@@ -232,7 +232,7 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_scoped_with_duck_typing
scoping = Struct.new(:method_scoping).new(:find => { :conditions => ["name = ?", 'David'] })
- Developer.with_scope(scoping) do
+ Developer.send(:with_scope, scoping) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
end
@@ -241,7 +241,7 @@ class MethodScopingTest < ActiveRecord::TestCase
scoped_methods = Developer.instance_eval('current_scoped_methods')
begin
- Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'Jamis'" }) do
raise "an exception"
end
rescue
@@ -254,8 +254,8 @@ class NestedScopingTest < ActiveRecord::TestCase
fixtures :authors, :developers, :projects, :comments, :posts
def test_merge_options
- Developer.with_scope(:find => { :conditions => 'salary = 80000' }) do
- Developer.with_scope(:find => { :limit => 10 }) do
+ Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do
+ Developer.send(:with_scope, :find => { :limit => 10 }) do
merged_option = Developer.instance_eval('current_scoped_methods')[:find]
assert_equal({ :conditions => 'salary = 80000', :limit => 10 }, merged_option)
end
@@ -263,8 +263,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_merge_inner_scope_has_priority
- Developer.with_scope(:find => { :limit => 5 }) do
- Developer.with_scope(:find => { :limit => 10 }) do
+ Developer.send(:with_scope, :find => { :limit => 5 }) do
+ Developer.send(:with_scope, :find => { :limit => 10 }) do
merged_option = Developer.instance_eval('current_scoped_methods')[:find]
assert_equal({ :limit => 10 }, merged_option)
end
@@ -272,8 +272,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_replace_options
- Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_exclusive_scope, :find => { :conditions => "name = 'Jamis'" }) do
assert_equal({:find => { :conditions => "name = 'Jamis'" }}, Developer.instance_eval('current_scoped_methods'))
assert_equal({:find => { :conditions => "name = 'Jamis'" }}, Developer.send(:scoped_methods)[-1])
end
@@ -281,21 +281,21 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_append_conditions
- Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
- Developer.with_scope(:find => { :conditions => 'salary = 80000' }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do
appended_condition = Developer.instance_eval('current_scoped_methods')[:find][:conditions]
assert_equal("(name = 'David') AND (salary = 80000)", appended_condition)
assert_equal(1, Developer.count)
end
- Developer.with_scope(:find => { :conditions => "name = 'Maiha'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'Maiha'" }) do
assert_equal(0, Developer.count)
end
end
end
def test_merge_and_append_options
- Developer.with_scope(:find => { :conditions => 'salary = 80000', :limit => 10 }) do
- Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_scope, :find => { :conditions => 'salary = 80000', :limit => 10 }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
merged_option = Developer.instance_eval('current_scoped_methods')[:find]
assert_equal({ :conditions => "(salary = 80000) AND (name = 'David')", :limit => 10 }, merged_option)
end
@@ -303,8 +303,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_nested_scoped_find
- Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'Jamis'" }) do
+ Developer.send(:with_exclusive_scope, :find => { :conditions => "name = 'David'" }) do
assert_nothing_raised { Developer.find(1) }
assert_equal('David', Developer.find(:first).name)
end
@@ -313,8 +313,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_nested_scoped_find_include
- Developer.with_scope(:find => { :include => :projects }) do
- Developer.with_scope(:find => { :conditions => "projects.id = 2" }) do
+ Developer.send(:with_scope, :find => { :include => :projects }) do
+ Developer.send(:with_scope, :find => { :conditions => "projects.id = 2" }) do
assert_nothing_raised { Developer.find(1) }
assert_equal('David', Developer.find(:first).name)
end
@@ -323,24 +323,24 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_nested_scoped_find_merged_include
# :include's remain unique and don't "double up" when merging
- Developer.with_scope(:find => { :include => :projects, :conditions => "projects.id = 2" }) do
- Developer.with_scope(:find => { :include => :projects }) do
+ Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do
+ Developer.send(:with_scope, :find => { :include => :projects }) do
assert_equal 1, Developer.instance_eval('current_scoped_methods')[:find][:include].length
assert_equal('David', Developer.find(:first).name)
end
end
# the nested scope doesn't remove the first :include
- Developer.with_scope(:find => { :include => :projects, :conditions => "projects.id = 2" }) do
- Developer.with_scope(:find => { :include => [] }) do
+ Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do
+ Developer.send(:with_scope, :find => { :include => [] }) do
assert_equal 1, Developer.instance_eval('current_scoped_methods')[:find][:include].length
assert_equal('David', Developer.find(:first).name)
end
end
# mixing array and symbol include's will merge correctly
- Developer.with_scope(:find => { :include => [:projects], :conditions => "projects.id = 2" }) do
- Developer.with_scope(:find => { :include => :projects }) do
+ Developer.send(:with_scope, :find => { :include => [:projects], :conditions => "projects.id = 2" }) do
+ Developer.send(:with_scope, :find => { :include => :projects }) do
assert_equal 1, Developer.instance_eval('current_scoped_methods')[:find][:include].length
assert_equal('David', Developer.find(:first).name)
end
@@ -348,21 +348,21 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_nested_scoped_find_replace_include
- Developer.with_scope(:find => { :include => :projects }) do
- Developer.with_exclusive_scope(:find => { :include => [] }) do
+ Developer.send(:with_scope, :find => { :include => :projects }) do
+ Developer.send(:with_exclusive_scope, :find => { :include => [] }) do
assert_equal 0, Developer.instance_eval('current_scoped_methods')[:find][:include].length
end
end
end
def test_three_level_nested_exclusive_scoped_find
- Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'Jamis'" }) do
assert_equal('Jamis', Developer.find(:first).name)
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_exclusive_scope, :find => { :conditions => "name = 'David'" }) do
assert_equal('David', Developer.find(:first).name)
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'Maiha'" }) do
+ Developer.send(:with_exclusive_scope, :find => { :conditions => "name = 'Maiha'" }) do
assert_equal(nil, Developer.find(:first))
end
@@ -377,8 +377,8 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_merged_scoped_find
poor_jamis = developers(:poor_jamis)
- Developer.with_scope(:find => { :conditions => "salary < 100000" }) do
- Developer.with_scope(:find => { :offset => 1, :order => 'id asc' }) do
+ 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_equal(poor_jamis, Developer.find(:first, :order => 'id asc'))
@@ -388,16 +388,16 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_merged_scoped_find_sanitizes_conditions
- Developer.with_scope(:find => { :conditions => ["name = ?", 'David'] }) do
- Developer.with_scope(:find => { :conditions => ['salary = ?', 9000] }) do
+ Developer.send(:with_scope, :find => { :conditions => ["name = ?", 'David'] }) do
+ Developer.send(:with_scope, :find => { :conditions => ['salary = ?', 9000] }) do
assert_raise(ActiveRecord::RecordNotFound) { developers(:poor_jamis) }
end
end
end
def test_nested_scoped_find_combines_and_sanitizes_conditions
- Developer.with_scope(:find => { :conditions => ["name = ?", 'David'] }) do
- Developer.with_exclusive_scope(:find => { :conditions => ['salary = ?', 9000] }) do
+ Developer.send(:with_scope, :find => { :conditions => ["name = ?", 'David'] }) do
+ Developer.send(:with_exclusive_scope, :find => { :conditions => ['salary = ?', 9000] }) do
assert_equal developers(:poor_jamis), Developer.find(:first)
assert_equal developers(:poor_jamis), Developer.find(:first, :conditions => ['name = ?', 'Jamis'])
end
@@ -405,8 +405,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_merged_scoped_find_combines_and_sanitizes_conditions
- Developer.with_scope(:find => { :conditions => ["name = ?", 'David'] }) do
- Developer.with_scope(:find => { :conditions => ['salary > ?', 9000] }) do
+ Developer.send(:with_scope, :find => { :conditions => ["name = ?", 'David'] }) do
+ Developer.send(:with_scope, :find => { :conditions => ['salary > ?', 9000] }) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
end
end
@@ -414,8 +414,8 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_nested_scoped_create
comment = nil
- Comment.with_scope(:create => { :post_id => 1}) do
- Comment.with_scope(:create => { :post_id => 2}) do
+ Comment.send(:with_scope, :create => { :post_id => 1}) do
+ Comment.send(:with_scope, :create => { :post_id => 2}) do
assert_equal({ :post_id => 2 }, Comment.send(:current_scoped_methods)[:create])
comment = Comment.create :body => "Hey guys, nested scopes are broken. Please fix!"
end
@@ -425,8 +425,8 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_nested_exclusive_scope_for_create
comment = nil
- Comment.with_scope(:create => { :body => "Hey guys, nested scopes are broken. Please fix!" }) do
- Comment.with_exclusive_scope(:create => { :post_id => 1 }) do
+ 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.send(:current_scoped_methods)[:create])
comment = Comment.create :body => "Hey guys"
end
@@ -437,8 +437,8 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_merged_scoped_find_on_blank_conditions
[nil, " ", [], {}].each do |blank|
- Developer.with_scope(:find => {:conditions => blank}) do
- Developer.with_scope(:find => {:conditions => blank}) do
+ Developer.send(:with_scope, :find => {:conditions => blank}) do
+ Developer.send(:with_scope, :find => {:conditions => blank}) do
assert_nothing_raised { Developer.find(:first) }
end
end
@@ -447,8 +447,8 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_merged_scoped_find_on_blank_bind_conditions
[ [""], ["",{}] ].each do |blank|
- Developer.with_scope(:find => {:conditions => blank}) do
- Developer.with_scope(:find => {:conditions => blank}) do
+ Developer.send(:with_scope, :find => {:conditions => blank}) do
+ Developer.send(:with_scope, :find => {:conditions => blank}) do
assert_nothing_raised { Developer.find(:first) }
end
end
@@ -458,8 +458,8 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_immutable_nested_scope
options1 = { :conditions => "name = 'Jamis'" }
options2 = { :conditions => "name = 'David'" }
- Developer.with_scope(:find => options1) do
- Developer.with_exclusive_scope(:find => options2) do
+ Developer.send(:with_scope, :find => options1) do
+ Developer.send(:with_exclusive_scope, :find => options2) do
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
options1[:conditions] = options2[:conditions] = nil
assert_equal %w(David), Developer.find(:all).map { |d| d.name }
@@ -470,8 +470,8 @@ class NestedScopingTest < ActiveRecord::TestCase
def test_immutable_merged_scope
options1 = { :conditions => "name = 'Jamis'" }
options2 = { :conditions => "salary > 10000" }
- Developer.with_scope(:find => options1) do
- Developer.with_scope(:find => options2) do
+ Developer.send(:with_scope, :find => options1) do
+ Developer.send(:with_scope, :find => options2) do
assert_equal %w(Jamis), Developer.find(:all).map { |d| d.name }
options1[:conditions] = options2[:conditions] = nil
assert_equal %w(Jamis), Developer.find(:all).map { |d| d.name }
@@ -480,10 +480,10 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_ensure_that_method_scoping_is_correctly_restored
- Developer.with_scope(:find => { :conditions => "name = 'David'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
scoped_methods = Developer.instance_eval('current_scoped_methods')
begin
- Developer.with_scope(:find => { :conditions => "name = 'Maiha'" }) do
+ Developer.send(:with_scope, :find => { :conditions => "name = 'Maiha'" }) do
raise "an exception"
end
rescue
@@ -493,8 +493,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_nested_scoped_find_merges_old_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id' }) do
- Author.with_scope(:find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id' }) do
+ Author.send(:with_scope, :find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do
Author.find(:all, :select => 'DISTINCT authors.*', :conditions => 'comments.id = 1')
end
end
@@ -505,8 +505,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_nested_scoped_find_merges_new_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
- Author.with_scope(:find => { :joins => :comments }) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => :posts }) do
+ Author.send(:with_scope, :find => { :joins => :comments }) do
Author.find(:all, :select => 'DISTINCT authors.*', :conditions => 'comments.id = 1')
end
end
@@ -517,8 +517,8 @@ class NestedScopingTest < ActiveRecord::TestCase
end
def test_nested_scoped_find_merges_new_and_old_style_joins
- scoped_authors = Author.with_scope(:find => { :joins => :posts }) do
- Author.with_scope(:find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do
+ scoped_authors = Author.send(:with_scope, :find => { :joins => :posts }) do
+ Author.send(:with_scope, :find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do
Author.find(:all, :select => 'DISTINCT authors.*', :joins => '', :conditions => 'comments.id = 1')
end
end
@@ -552,7 +552,7 @@ class HasManyScopingTest< ActiveRecord::TestCase
end
def test_nested_scope
- Comment.with_scope(:find => { :conditions => '1=1' }) do
+ Comment.send(:with_scope, :find => { :conditions => '1=1' }) do
assert_equal 'a comment...', @welcome.comments.what_are_you
end
end
@@ -577,7 +577,7 @@ class HasAndBelongsToManyScopingTest< ActiveRecord::TestCase
end
def test_nested_scope
- Category.with_scope(:find => { :conditions => '1=1' }) do
+ Category.send(:with_scope, :find => { :conditions => '1=1' }) do
assert_equal 'a comment...', @welcome.comments.what_are_you
end
end
@@ -633,7 +633,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
def test_nested_scope
expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
- received = DeveloperOrderedBySalary.with_scope(:find => { :order => 'name DESC'}) do
+ received = DeveloperOrderedBySalary.send(:with_scope, :find => { :order => 'name DESC'}) do
DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
end
assert_equal expected, received
@@ -647,7 +647,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
def test_nested_exclusive_scope
expected = Developer.find(:all, :limit => 100).collect { |dev| dev.salary }
- received = DeveloperOrderedBySalary.with_exclusive_scope(:find => { :limit => 100 }) do
+ received = DeveloperOrderedBySalary.send(:with_exclusive_scope, :find => { :limit => 100 }) do
DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
end
assert_equal expected, received
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 6d3f938799..0ef34e440a 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -527,6 +527,53 @@ if ActiveRecord::Base.connection.supports_migrations?
assert !Person.column_methods_hash.include?(:last_name)
end
+ if current_adapter?(:MysqlAdapter)
+ def testing_table_for_positioning
+ Person.connection.create_table :testings, :id => false do |t|
+ t.column :first, :integer
+ t.column :second, :integer
+ t.column :third, :integer
+ end
+
+ yield Person.connection
+ ensure
+ Person.connection.drop_table :testings rescue nil
+ end
+ protected :testing_table_for_positioning
+
+ def test_column_positioning
+ testing_table_for_positioning do |conn|
+ assert_equal %w(first second third), conn.columns(:testings).map {|c| c.name }
+ end
+ end
+
+ def test_add_column_with_positioning
+ testing_table_for_positioning do |conn|
+ conn.add_column :testings, :new_col, :integer
+ assert_equal %w(first second third new_col), conn.columns(:testings).map {|c| c.name }
+ end
+ testing_table_for_positioning do |conn|
+ conn.add_column :testings, :new_col, :integer, :first => true
+ assert_equal %w(new_col first second third), conn.columns(:testings).map {|c| c.name }
+ end
+ testing_table_for_positioning do |conn|
+ conn.add_column :testings, :new_col, :integer, :after => :first
+ assert_equal %w(first new_col second third), conn.columns(:testings).map {|c| c.name }
+ end
+ end
+
+ def test_change_column_with_positioning
+ testing_table_for_positioning do |conn|
+ conn.change_column :testings, :second, :integer, :first => true
+ assert_equal %w(second first third), conn.columns(:testings).map {|c| c.name }
+ end
+ testing_table_for_positioning do |conn|
+ conn.change_column :testings, :second, :integer, :after => :third
+ assert_equal %w(first third second), conn.columns(:testings).map {|c| c.name }
+ end
+ end
+ end
+
def test_add_rename
Person.delete_all
diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb
index 7c3e0f2ca6..6155bfd50a 100644
--- a/activerecord/test/cases/multiple_db_test.rb
+++ b/activerecord/test/cases/multiple_db_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/entrant'
+require 'models/bird'
# So we can test whether Course.connection survives a reload.
require_dependency 'models/course'
@@ -82,4 +83,9 @@ class MultipleDbTest < ActiveRecord::TestCase
assert_equal "Ruby Development", Course.find(1).name
assert_equal "Ruby Developer", Entrant.find(1).name
end
+
+ def test_arel_table_engines
+ assert_not_equal Entrant.active_relation_engine, Course.active_relation_engine
+ assert_equal Entrant.active_relation_engine, Bird.active_relation_engine
+ end
end
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index 13427daf53..5d9232bc52 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -345,8 +345,8 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_chaining_should_use_latest_conditions_when_searching
# Normal hash conditions
- assert_equal Topic.all(:conditions => {:approved => true}).to_a, Topic.rejected.approved.all.to_a
- assert_equal Topic.all(:conditions => {:approved => false}).to_a, Topic.approved.rejected.all.to_a
+ assert_equal Topic.where(:approved => true).to_a, Topic.rejected.approved.all.to_a
+ assert_equal Topic.where(:approved => false).to_a, Topic.approved.rejected.all.to_a
# Nested hash conditions with same keys
assert_equal [posts(:sti_comments)], Post.with_special_comments.with_very_special_comments.all.to_a
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 53fd168e1b..8891282915 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -245,6 +245,27 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_automatically_enable_autosave_on_the_association
assert Pirate.reflect_on_association(:ship).options[:autosave]
end
+
+ def test_should_accept_update_only_option
+ @pirate.update_attribute(:update_only_ship_attributes, { :id => @pirate.ship.id, :name => 'Mayflower' })
+ end
+
+ def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true
+ @ship.delete
+ assert_difference('Ship.count', 1) do
+ @pirate.reload.update_attribute(:update_only_ship_attributes, { :name => 'Mayflower' })
+ end
+ 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
+ assert_equal 'Mayflower', @ship.reload.name
+ end
end
class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
@@ -362,6 +383,27 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_automatically_enable_autosave_on_the_association
assert Ship.reflect_on_association(:pirate).options[:autosave]
end
+
+ def test_should_accept_update_only_option
+ @ship.update_attribute(:update_only_pirate_attributes, { :id => @pirate.ship.id, :catchphrase => 'Arr' })
+ end
+
+ 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_attribute(:update_only_pirate_attributes, { :catchphrase => 'Arr' })
+ end
+ 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
+ assert_equal 'Arr', @pirate.reload.catchphrase
+ end
end
module NestedAttributesOnACollectionAssociationTests
@@ -371,6 +413,15 @@ module NestedAttributesOnACollectionAssociationTests
assert_respond_to @pirate, association_setter
end
+ def test_should_save_only_one_association_on_create
+ pirate = Pirate.create!({
+ :catchphrase => 'Arr',
+ association_getter => { 'foo' => { :name => 'Grace OMalley' } }
+ })
+
+ assert_equal 1, pirate.reload.send(@association_name).count
+ end
+
def test_should_take_a_hash_with_string_keys_and_assign_the_attributes_to_the_associated_models
@alternate_params[association_getter].stringify_keys!
@pirate.update_attributes @alternate_params
@@ -541,7 +592,7 @@ module NestedAttributesOnACollectionAssociationTests
assert_no_difference ['Man.count', 'Interest.count'] do
man = Man.create(:name => 'John',
:interests_attributes => [{:topic=>'Cars'}, {:topic=>'Sports'}])
- assert !man.errors[:interests_man].empty?
+ assert !man.errors[:"interests.man"].empty?
end
end
# restore :inverse_of
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index b921cbdc9c..98011f40a4 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -33,19 +33,20 @@ class ReadOnlyTest < ActiveRecord::TestCase
def test_find_with_readonly_option
Developer.find(:all).each { |d| assert !d.readonly? }
- Developer.find(:all, :readonly => false).each { |d| assert !d.readonly? }
- Developer.find(:all, :readonly => true).each { |d| assert d.readonly? }
+ Developer.readonly(false).each { |d| assert !d.readonly? }
+ Developer.readonly(true).each { |d| assert d.readonly? }
+ Developer.readonly.each { |d| assert d.readonly? }
end
def test_find_with_joins_option_implies_readonly
# Blank joins don't count.
- Developer.find(:all, :joins => ' ').each { |d| assert !d.readonly? }
- Developer.find(:all, :joins => ' ', :readonly => false).each { |d| assert !d.readonly? }
+ Developer.joins(' ').each { |d| assert !d.readonly? }
+ Developer.joins(' ').readonly(false).each { |d| assert !d.readonly? }
# Others do.
- Developer.find(:all, :joins => ', projects').each { |d| assert d.readonly? }
- Developer.find(:all, :joins => ', projects', :readonly => false).each { |d| assert !d.readonly? }
+ Developer.joins(', projects').each { |d| assert d.readonly? }
+ Developer.joins(', projects').readonly(false).each { |d| assert !d.readonly? }
end
@@ -54,7 +55,7 @@ class ReadOnlyTest < ActiveRecord::TestCase
assert !dev.projects.empty?
assert dev.projects.all?(&:readonly?)
assert dev.projects.find(:all).all?(&:readonly?)
- assert dev.projects.find(:all, :readonly => true).all?(&:readonly?)
+ assert dev.projects.readonly(true).all?(&:readonly?)
end
def test_has_many_find_readonly
@@ -62,7 +63,7 @@ class ReadOnlyTest < ActiveRecord::TestCase
assert !post.comments.empty?
assert !post.comments.any?(&:readonly?)
assert !post.comments.find(:all).any?(&:readonly?)
- assert post.comments.find(:all, :readonly => true).all?(&:readonly?)
+ assert post.comments.readonly(true).all?(&:readonly?)
end
def test_has_many_with_through_is_not_implicitly_marked_readonly
@@ -71,32 +72,32 @@ class ReadOnlyTest < ActiveRecord::TestCase
end
def test_readonly_scoping
- Post.with_scope(:find => { :conditions => '1=1' }) do
+ Post.send(:with_scope, :find => { :conditions => '1=1' }) do
assert !Post.find(1).readonly?
- assert Post.find(1, :readonly => true).readonly?
- assert !Post.find(1, :readonly => false).readonly?
+ assert Post.readonly(true).find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
end
- Post.with_scope(:find => { :joins => ' ' }) do
+ Post.send(:with_scope, :find => { :joins => ' ' }) do
assert !Post.find(1).readonly?
- assert Post.find(1, :readonly => true).readonly?
- assert !Post.find(1, :readonly => false).readonly?
+ assert Post.readonly.find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
end
# Oracle barfs on this because the join includes unqualified and
# conflicting column names
unless current_adapter?(:OracleAdapter)
- Post.with_scope(:find => { :joins => ', developers' }) do
+ Post.send(:with_scope, :find => { :joins => ', developers' }) do
assert Post.find(1).readonly?
- assert Post.find(1, :readonly => true).readonly?
- assert !Post.find(1, :readonly => false).readonly?
+ assert Post.readonly.find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
end
end
- Post.with_scope(:find => { :readonly => true }) do
+ Post.send(:with_scope, :find => { :readonly => true }) do
assert Post.find(1).readonly?
- assert Post.find(1, :readonly => true).readonly?
- assert !Post.find(1, :readonly => false).readonly?
+ assert Post.readonly.find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
end
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 1a2c8030fb..f895f8b8d2 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -1,4 +1,6 @@
require "cases/helper"
+require 'models/tag'
+require 'models/tagging'
require 'models/post'
require 'models/topic'
require 'models/comment'
@@ -8,52 +10,115 @@ require 'models/comment'
require 'models/entrant'
require 'models/developer'
require 'models/company'
+require 'models/bird'
class RelationTest < ActiveRecord::TestCase
- fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments
+ fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments,
+ :taggings
+
+ def test_scoped
+ topics = Topic.scoped
+ assert_kind_of ActiveRecord::Relation, topics
+ assert_equal 4, topics.size
+ end
+
+ def test_scoped_all
+ topics = Topic.scoped.all
+ assert_kind_of Array, topics
+ assert_no_queries { assert_equal 4, topics.size }
+ end
+
+ def test_loaded_all
+ topics = Topic.scoped
+
+ assert_queries(1) do
+ 2.times { assert_equal 4, topics.all.size }
+ end
+
+ assert topics.loaded?
+ end
+
+ def test_scoped_first
+ topics = Topic.scoped.order('id ASC')
+
+ assert_queries(1) do
+ 2.times { assert_equal "The First Topic", topics.first.title }
+ end
+
+ assert ! topics.loaded?
+ end
+
+ def test_loaded_first
+ topics = Topic.scoped.order('id ASC')
+
+ assert_queries(1) do
+ topics.all # force load
+ 2.times { assert_equal "The First Topic", topics.first.title }
+ end
+
+ assert topics.loaded?
+ end
+
+ def test_reload
+ topics = Topic.scoped
+
+ assert_queries(1) do
+ 2.times { topics.to_a }
+ end
+
+ assert topics.loaded?
+
+ topics.reload
+ assert ! topics.loaded?
+
+ assert_queries(1) { topics.to_a }
+ end
def test_finding_with_conditions
- assert_equal Author.find(:all, :conditions => "name = 'David'"), Author.all.conditions("name = 'David'").to_a
+ assert_equal ["David"], Author.where(:name => 'David').map(&:name)
+ assert_equal ['Mary'], Author.where(["name = ?", 'Mary']).map(&:name)
+ assert_equal ['Mary'], Author.where("name = ?", 'Mary').map(&:name)
end
def test_finding_with_order
- topics = Topic.all.order('id')
- assert_equal 4, topics.size
+ topics = Topic.order('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.all.order("id ASC").limit(2).to_a
+ entrants = Entrant.order("id ASC").limit(2).to_a
- assert_equal(2, entrants.size)
- assert_equal(entrants(:first).name, entrants.first.name)
+ assert_equal 2, entrants.size
+ assert_equal entrants(:first).name, entrants.first.name
end
def test_finding_with_order_limit_and_offset
- entrants = Entrant.all.order("id ASC").limit(2).offset(1)
+ entrants = Entrant.order("id ASC").limit(2).offset(1)
- assert_equal(2, entrants.size)
- assert_equal(entrants(:second).name, entrants.first.name)
+ assert_equal 2, entrants.to_a.size
+ assert_equal entrants(:second).name, entrants.first.name
- entrants = Entrant.all.order("id ASC").limit(2).offset(2)
- assert_equal(1, entrants.size)
- assert_equal(entrants(:third).name, entrants.first.name)
+ entrants = Entrant.order("id ASC").limit(2).offset(2)
+ assert_equal 1, entrants.to_a.size
+ assert_equal entrants(:third).name, entrants.first.name
end
def test_finding_with_group
- developers = Developer.all.group("salary").select("salary").to_a
+ developers = Developer.group("salary").select("salary").to_a
assert_equal 4, developers.size
assert_equal 4, developers.map(&:salary).uniq.size
end
def test_finding_with_hash_conditions_on_joined_table
- firms = DependentFirm.all.joins(:account).conditions({:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}).to_a
+ firms = DependentFirm.joins(:account).where({:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}).to_a
assert_equal 1, firms.size
assert_equal companies(:rails_core), firms.first
end
def test_find_all_with_join
- developers_on_project_one = Developer.all.joins('LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id').conditions('project_id=1').to_a
+ developers_on_project_one = Developer.joins('LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id').
+ where('project_id=1').to_a
assert_equal 3, developers_on_project_one.length
developer_names = developers_on_project_one.map { |d| d.name }
@@ -62,11 +127,11 @@ class RelationTest < ActiveRecord::TestCase
end
def test_find_on_hash_conditions
- assert_equal Topic.find(:all, :conditions => {:approved => false}), Topic.all.conditions({ :approved => false }).to_a
+ assert_equal Topic.find(:all, :conditions => {:approved => false}), Topic.where({ :approved => false }).to_a
end
def test_joins_with_string_array
- person_with_reader_and_post = Post.all.joins([
+ person_with_reader_and_post = Post.joins([
"INNER JOIN categorizations ON categorizations.post_id = posts.id",
"INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'"
]
@@ -74,22 +139,38 @@ class RelationTest < ActiveRecord::TestCase
assert_equal 1, person_with_reader_and_post.size
end
- def test_relation_responds_to_delegated_methods
- relation = Topic.all
+ def test_scoped_responds_to_delegated_methods
+ relation = Topic.scoped
["map", "uniq", "sort", "insert", "delete", "update"].each do |method|
- assert relation.respond_to?(method), "Topic.all should respond to #{method.inspect}"
+ assert relation.respond_to?(method), "Topic.scoped should respond to #{method.inspect}"
+ end
+ end
+
+ def test_respond_to_private_arel_methods
+ relation = Topic.scoped
+
+ assert ! relation.respond_to?(:matching_attributes)
+ assert relation.respond_to?(:matching_attributes, true)
+ end
+
+ def test_respond_to_dynamic_finders
+ relation = Topic.scoped
+
+ ["find_by_title", "find_by_title_and_author_name", "find_or_create_by_title", "find_or_initialize_by_title_and_author_name"].each do |method|
+ assert relation.respond_to?(method), "Topic.scoped should respond to #{method.inspect}"
end
end
def test_find_with_readonly_option
- Developer.all.each { |d| assert !d.readonly? }
- Developer.all.readonly.each { |d| assert d.readonly? }
- Developer.all(:readonly => true).each { |d| assert d.readonly? }
+ Developer.scoped.each { |d| assert !d.readonly? }
+ Developer.scoped.readonly.each { |d| assert d.readonly? }
end
def test_eager_association_loading_of_stis_with_multiple_references
- authors = Author.all(:include => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :conditions => 'posts.id = 4').to_a
+ authors = Author.eager_load(:posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } }).
+ order('comments.body, very_special_comments_posts.body').where('posts.id = 4').to_a
+
assert_equal [authors(:david)], authors
assert_no_queries do
authors.first.posts.first.special_comments.first.post.special_comments
@@ -97,54 +178,382 @@ class RelationTest < ActiveRecord::TestCase
end
end
- def test_find_with_included_associations
+ def test_find_with_preloaded_associations
assert_queries(2) do
- posts = Post.find(:all, :include => :comments)
- posts.first.comments.first
+ posts = Post.preload(:comments)
+ assert posts.first.comments.first
end
+
assert_queries(2) do
- posts = Post.all(:include => :comments).to_a
- posts.first.comments.first
+ posts = Post.preload(:comments).to_a
+ assert posts.first.comments.first
end
+
assert_queries(2) do
- posts = Post.find(:all, :include => :author)
- posts.first.author
+ posts = Post.preload(:author)
+ assert posts.first.author
end
+
assert_queries(2) do
- posts = Post.all(:include => :author).to_a
- posts.first.author
+ posts = Post.preload(:author).to_a
+ assert posts.first.author
+ end
+
+ assert_queries(3) do
+ posts = Post.preload(:author, :comments).to_a
+ assert posts.first.author
+ assert posts.first.comments.first
end
end
- def test_default_scope_with_conditions_string
- assert_equal Developer.find_all_by_name('David').map(&:id).sort, DeveloperCalledDavid.all.to_a.map(&:id).sort
+ def test_find_with_included_associations
+ assert_queries(2) do
+ posts = Post.includes(:comments)
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.scoped.includes(:comments)
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.includes(:author)
+ assert posts.first.author
+ end
+
+ assert_queries(3) do
+ posts = Post.includes(:author, :comments).to_a
+ assert posts.first.author
+ assert posts.first.comments.first
+ end
+ end
+
+ def test_default_scope_with_conditions_string
+ assert_equal Developer.find_all_by_name('David').map(&:id).sort, DeveloperCalledDavid.scoped.map(&:id).sort
assert_equal nil, DeveloperCalledDavid.create!.name
end
def test_default_scope_with_conditions_hash
- assert_equal Developer.find_all_by_name('Jamis').map(&:id).sort, DeveloperCalledJamis.all.map(&:id).sort
+ assert_equal Developer.find_all_by_name('Jamis').map(&:id).sort, DeveloperCalledJamis.scoped.map(&:id).sort
assert_equal 'Jamis', DeveloperCalledJamis.create!.name
end
- def test_loading_with_one_association
- posts = Post.all(:include => :comments)
+ def test_default_scoping_finder_methods
+ developers = DeveloperCalledDavid.order('id').map(&:id).sort
+ assert_equal Developer.find_all_by_name('David').map(&:id).sort, developers
+ end
+
+ def test_loading_with_one_association
+ posts = Post.preload(:comments)
post = posts.find { |p| p.id == 1 }
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
- post = Post.find(:first, :include => :comments, :conditions => "posts.title = 'Welcome to the weblog'")
+ post = Post.where("posts.title = 'Welcome to the weblog'").preload(:comments).first
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
- posts = Post.all(:include => :last_comment)
+ posts = Post.preload(:last_comment)
post = posts.find { |p| p.id == 1 }
assert_equal Post.find(1).last_comment, post.last_comment
end
def test_loading_with_one_association_with_non_preload
- posts = Post.all(:include => :last_comment, :order => 'comments.id DESC')
+ posts = Post.eager_load(:last_comment).order('comments.id DESC')
post = posts.find { |p| p.id == 1 }
assert_equal Post.find(1).last_comment, post.last_comment
end
-end
+ def test_dynamic_find_by_attributes
+ david = authors(:david)
+ author = Author.preload(:taggings).find_by_id(david.id)
+ expected_taggings = taggings(:welcome_general, :thinking_general)
+
+ assert_no_queries do
+ assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
+ end
+
+ authors = Author.scoped
+ assert_equal david, authors.find_by_id_and_name(david.id, david.name)
+ assert_equal david, authors.find_by_id_and_name!(david.id, david.name)
+ end
+
+ def test_dynamic_find_by_attributes_bang
+ author = Author.scoped.find_by_id!(authors(:david).id)
+ assert_equal "David", author.name
+
+ assert_raises(ActiveRecord::RecordNotFound) { Author.scoped.find_by_id_and_name!(20, 'invalid') }
+ end
+
+ def test_dynamic_find_all_by_attributes
+ authors = Author.scoped
+
+ davids = authors.find_all_by_name('David')
+ assert_kind_of Array, davids
+ assert_equal [authors(:david)], davids
+ end
+
+ def test_dynamic_find_or_initialize_by_attributes
+ authors = Author.scoped
+
+ lifo = authors.find_or_initialize_by_name('Lifo')
+ assert_equal "Lifo", lifo.name
+ assert lifo.new_record?
+
+ assert_equal authors(:david), authors.find_or_initialize_by_name(:name => 'David')
+ end
+
+ def test_dynamic_find_or_create_by_attributes
+ authors = Author.scoped
+
+ lifo = authors.find_or_create_by_name('Lifo')
+ assert_equal "Lifo", lifo.name
+ assert ! lifo.new_record?
+
+ assert_equal authors(:david), authors.find_or_create_by_name(:name => 'David')
+ end
+
+ def test_find_id
+ authors = Author.scoped
+
+ david = authors.find(authors(:david).id)
+ assert_equal 'David', david.name
+
+ assert_raises(ActiveRecord::RecordNotFound) { authors.where(:name => 'lifo').find('42') }
+ end
+
+ def test_find_ids
+ authors = Author.order('id ASC')
+
+ results = authors.find(authors(:david).id, authors(:mary).id)
+ assert_kind_of Array, results
+ assert_equal 2, results.size
+ assert_equal 'David', results[0].name
+ assert_equal 'Mary', results[1].name
+ assert_equal results, authors.find([authors(:david).id, authors(:mary).id])
+
+ assert_raises(ActiveRecord::RecordNotFound) { authors.where(:name => 'lifo').find(authors(:david).id, '42') }
+ assert_raises(ActiveRecord::RecordNotFound) { authors.find(['42', 43]) }
+ end
+
+ def test_exists
+ davids = Author.where(:name => 'David')
+ assert davids.exists?
+ assert davids.exists?(authors(:david).id)
+ assert ! davids.exists?(authors(:mary).id)
+ assert ! davids.exists?("42")
+ assert ! davids.exists?(42)
+
+ fake = Author.where(:name => 'fake author')
+ assert ! fake.exists?
+ assert ! fake.exists?(authors(:david).id)
+ end
+
+ def test_last
+ authors = Author.scoped
+ assert_equal authors(:mary), authors.last
+ end
+
+ def test_destroy_all
+ davids = Author.where(:name => 'David')
+
+ # Force load
+ assert_equal [authors(:david)], davids.to_a
+ assert davids.loaded?
+
+ assert_difference('Author.count', -1) { davids.destroy_all }
+
+ assert_equal [], davids.to_a
+ assert davids.loaded?
+ end
+
+ def test_delete_all
+ davids = Author.where(:name => 'David')
+
+ assert_difference('Author.count', -1) { davids.delete_all }
+ assert ! davids.loaded?
+ end
+
+ def test_delete_all_loaded
+ davids = Author.where(:name => 'David')
+
+ # Force load
+ assert_equal [authors(:david)], davids.to_a
+ assert davids.loaded?
+
+ assert_difference('Author.count', -1) { davids.delete_all }
+
+ assert_equal [], davids.to_a
+ assert davids.loaded?
+ end
+
+ def test_relation_merging
+ devs = Developer.where("salary >= 80000") & Developer.limit(2) & 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.*')
+ 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.each do |posts|
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+ end
+
+ def test_relation_merging_with_locks
+ devs = Developer.lock.where("salary >= 80000").order("id DESC") & Developer.limit(2)
+ assert devs.locked.present?
+ 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 }
+ end
+ end
+
+ def test_invalid_merge
+ assert_raises(ArgumentError) { Post.scoped & Developer.scoped }
+ 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 1, posts.where('comments_count > 1').count
+ assert_equal 5, 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 3, posts.select(:comments_count).count(:distinct => true)
+ assert_equal 7, posts.select(:comments_count).count(:distinct => false)
+ end
+
+ def test_count_explicit_columns
+ Post.update_all(:comments_count => nil)
+ posts = Post.scoped
+
+ assert_equal [0], posts.select('comments_count').where('id is not null').group('id').order('id').count.values.uniq
+ assert_equal 0, posts.where('id is not null').select('comments_count').count
+
+ assert_equal 7, posts.select('comments_count').count('id')
+ assert_equal 0, posts.select('comments_count').count
+ assert_equal 0, posts.count(:comments_count)
+ assert_equal 0, posts.count('comments_count')
+ end
+
+ def test_size
+ posts = Post.scoped
+
+ assert_queries(1) { assert_equal 7, 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 }
+ end
+
+ def test_count_complex_chained_relations
+ posts = Post.select('comments_count').where('id is not null').group("author_id").where("comments_count > 0")
+
+ expected = { 1 => 2 }
+ assert_equal expected, posts.count
+ end
+
+ def test_any
+ posts = Post.scoped
+
+ assert_queries(3) do
+ assert posts.any? # Uses COUNT()
+ assert ! posts.where(:id => nil).any?
+
+ assert posts.any? {|p| p.id > 0 }
+ assert ! posts.any? {|p| p.id <= 0 }
+ end
+
+ assert posts.loaded?
+ end
+
+ def test_many
+ posts = Post.scoped
+
+ assert_queries(2) do
+ assert posts.many? # Uses COUNT()
+ assert posts.many? {|p| p.id > 0 }
+ assert ! posts.many? {|p| p.id < 2 }
+ end
+
+ assert posts.loaded?
+ end
+
+ def test_many_with_limits
+ posts = Post.scoped
+
+ assert posts.many?
+ assert ! posts.limit(1).many?
+ end
+
+ def test_build
+ posts = Post.scoped
+
+ post = posts.new
+ assert_kind_of Post, post
+ end
+
+ def test_scoped_build
+ posts = Post.where(:title => 'You told a lie')
+
+ post = posts.new
+ assert_kind_of Post, post
+ assert_equal 'You told a lie', post.title
+ end
+
+ def test_create
+ birds = Bird.scoped
+
+ sparrow = birds.create
+ assert_kind_of Bird, sparrow
+ assert sparrow.new_record?
+
+ hen = birds.where(:name => 'hen').create
+ assert ! hen.new_record?
+ assert_equal 'hen', hen.name
+ end
+
+ def test_create_bang
+ birds = Bird.scoped
+
+ assert_raises(ActiveRecord::RecordInvalid) { birds.create! }
+
+ hen = birds.where(:name => 'hen').create!
+ assert_kind_of Bird, hen
+ assert ! hen.new_record?
+ assert_equal 'hen', hen.name
+ end
+
+ def test_except
+ relation = Post.where(:author_id => 1).order('id ASC').limit(1)
+ assert_equal [posts(:welcome)], relation.all
+
+ author_posts = relation.except(:order, :limit)
+ assert_equal Post.where(:author_id => 1).all, author_posts.all
+
+ all_posts = relation.except(:where, :order, :limit)
+ assert_equal Post.all, all_posts.all
+ end
+
+end
diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb
index 278a7a6a06..5ed997356b 100644
--- a/activerecord/test/cases/validations/association_validation_test.rb
+++ b/activerecord/test/cases/validations/association_validation_test.rb
@@ -10,7 +10,7 @@ require 'models/interest'
class AssociationValidationTest < ActiveRecord::TestCase
fixtures :topics, :owners
- repair_validations(Topic)
+ repair_validations(Topic, Reply)
def test_validates_size_of_association
repair_validations(Owner) do
@@ -40,7 +40,8 @@ class AssociationValidationTest < ActiveRecord::TestCase
end
def test_validates_associated_many
- Topic.validates_associated( :replies )
+ Topic.validates_associated(:replies)
+ Reply.validates_presence_of(:content)
t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
t.replies << [r = Reply.new("title" => "A reply"), r2 = Reply.new("title" => "Another reply", "content" => "non-empty"), r3 = Reply.new("title" => "Yet another reply"), r4 = Reply.new("title" => "The last reply", "content" => "non-empty")]
assert !t.valid?
diff --git a/activerecord/test/cases/validations/i18n_validation_test.rb b/activerecord/test/cases/validations/i18n_validation_test.rb
index 532de67d99..f017f24048 100644
--- a/activerecord/test/cases/validations/i18n_validation_test.rb
+++ b/activerecord/test/cases/validations/i18n_validation_test.rb
@@ -3,8 +3,9 @@ require 'models/topic'
require 'models/reply'
class I18nValidationTest < ActiveRecord::TestCase
+ repair_validations(Topic, Reply)
def setup
- Topic.reset_callbacks(:validate)
+ Reply.validates_presence_of(:title)
@topic = Topic.new
@old_load_path, @old_backend = I18n.load_path, I18n.backend
I18n.load_path.clear
@@ -13,7 +14,6 @@ class I18nValidationTest < ActiveRecord::TestCase
end
def teardown
- Topic.reset_callbacks(:validate)
I18n.load_path.replace @old_load_path
I18n.backend = @old_backend
end
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 17ba4e2f8a..8f84841fe6 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -5,7 +5,6 @@ require 'models/reply'
require 'models/warehouse_thing'
require 'models/guid'
require 'models/event'
-require 'models/developer'
# The following methods in Topic are used in test_conditional_validation_*
class Topic
@@ -213,7 +212,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
def test_validates_uniqueness_inside_with_scope
Topic.validates_uniqueness_of(:title)
- Topic.with_scope(:find => { :conditions => { :author_name => "David" } }) do
+ Topic.send(:with_scope, :find => { :conditions => { :author_name => "David" } }) do
t1 = Topic.new("title" => "I'm unique!", "author_name" => "Mary")
assert t1.save
t2 = Topic.new("title" => "I'm unique!", "author_name" => "David")
@@ -276,14 +275,4 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert w6.errors[:city].any?, "Should have errors for city"
assert_equal ["has already been taken"], w6.errors[:city], "Should have uniqueness message for city"
end
-
- def test_validates_uniqueness_of_with_custom_message_using_quotes
- repair_validations(Developer) do
- Developer.validates_uniqueness_of :name, :message=> "This string contains 'single' and \"double\" quotes"
- d = Developer.new
- d.name = "David"
- assert !d.valid?
- assert_equal ["This string contains 'single' and \"double\" quotes"], d.errors[:name]
- end
- end
end
diff --git a/activerecord/test/cases/validations_repair_helper.rb b/activerecord/test/cases/validations_repair_helper.rb
new file mode 100644
index 0000000000..11912ca1cc
--- /dev/null
+++ b/activerecord/test/cases/validations_repair_helper.rb
@@ -0,0 +1,23 @@
+module ActiveRecord
+ module ValidationsRepairHelper
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def repair_validations(*model_classes)
+ teardown do
+ model_classes.each do |k|
+ k.reset_callbacks(:validate)
+ end
+ end
+ end
+ end
+
+ def repair_validations(*model_classes)
+ yield
+ ensure
+ model_classes.each do |k|
+ k.reset_callbacks(:validate)
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb
index 130231c622..3a1d5ae212 100644
--- a/activerecord/test/cases/validations_test.rb
+++ b/activerecord/test/cases/validations_test.rb
@@ -42,7 +42,7 @@ class ValidationsTest < ActiveRecord::TestCase
repair_validations(Topic)
def test_error_on_create
- r = Reply.new
+ r = WrongReply.new
r.title = "Wrong Create"
assert !r.valid?
assert r.errors[:title].any?, "A reply with a bad title should mark that attribute as invalid"
@@ -50,7 +50,7 @@ class ValidationsTest < ActiveRecord::TestCase
end
def test_error_on_update
- r = Reply.new
+ r = WrongReply.new
r.title = "Bad"
r.content = "Good"
assert r.save, "First save should be successful"
@@ -63,11 +63,11 @@ class ValidationsTest < ActiveRecord::TestCase
end
def test_invalid_record_exception
- assert_raise(ActiveRecord::RecordInvalid) { Reply.create! }
- assert_raise(ActiveRecord::RecordInvalid) { Reply.new.save! }
+ assert_raise(ActiveRecord::RecordInvalid) { WrongReply.create! }
+ assert_raise(ActiveRecord::RecordInvalid) { WrongReply.new.save! }
begin
- r = Reply.new
+ r = WrongReply.new
r.save!
flunk
rescue ActiveRecord::RecordInvalid => invalid
@@ -77,13 +77,13 @@ class ValidationsTest < ActiveRecord::TestCase
def test_exception_on_create_bang_many
assert_raise(ActiveRecord::RecordInvalid) do
- Reply.create!([ { "title" => "OK" }, { "title" => "Wrong Create" }])
+ WrongReply.create!([ { "title" => "OK" }, { "title" => "Wrong Create" }])
end
end
def test_exception_on_create_bang_with_block
assert_raise(ActiveRecord::RecordInvalid) do
- Reply.create!({ "title" => "OK" }) do |r|
+ WrongReply.create!({ "title" => "OK" }) do |r|
r.content = nil
end
end
@@ -91,21 +91,21 @@ class ValidationsTest < ActiveRecord::TestCase
def test_exception_on_create_bang_many_with_block
assert_raise(ActiveRecord::RecordInvalid) do
- Reply.create!([{ "title" => "OK" }, { "title" => "Wrong Create" }]) do |r|
+ WrongReply.create!([{ "title" => "OK" }, { "title" => "Wrong Create" }]) do |r|
r.content = nil
end
end
end
def test_scoped_create_without_attributes
- Reply.with_scope(:create => {}) do
- assert_raise(ActiveRecord::RecordInvalid) { Reply.create! }
+ WrongReply.send(:with_scope, :create => {}) do
+ assert_raise(ActiveRecord::RecordInvalid) { WrongReply.create! }
end
end
def test_create_with_exceptions_using_scope_for_protected_attributes
assert_nothing_raised do
- ProtectedPerson.with_scope( :create => { :first_name => "Mary" } ) do
+ ProtectedPerson.send(:with_scope, :create => { :first_name => "Mary" } ) do
person = ProtectedPerson.create! :addon => "Addon"
assert_equal person.first_name, "Mary", "scope should ignore attr_protected"
end
@@ -114,7 +114,7 @@ class ValidationsTest < ActiveRecord::TestCase
def test_create_with_exceptions_using_scope_and_empty_attributes
assert_nothing_raised do
- ProtectedPerson.with_scope( :create => { :first_name => "Mary" } ) do
+ ProtectedPerson.send(:with_scope, :create => { :first_name => "Mary" } ) do
person = ProtectedPerson.create!
assert_equal person.first_name, "Mary", "should be ok when no attributes are passed to create!"
end
@@ -122,15 +122,15 @@ class ValidationsTest < ActiveRecord::TestCase
end
def test_create_without_validation
- reply = Reply.new
+ reply = WrongReply.new
assert !reply.save
assert reply.save(false)
end
def test_create_without_validation_bang
- count = Reply.count
- assert_nothing_raised { Reply.new.save_without_validation! }
- assert count+1, Reply.count
+ count = WrongReply.count
+ assert_nothing_raised { WrongReply.new.save_without_validation! }
+ assert count+1, WrongReply.count
end
def test_validates_acceptance_of_with_non_existant_table
diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb
new file mode 100644
index 0000000000..f221def6b6
--- /dev/null
+++ b/activerecord/test/cases/yaml_serialization_test.rb
@@ -0,0 +1,11 @@
+require "cases/helper"
+require 'models/topic'
+
+class YamlSerializationTest < ActiveRecord::TestCase
+ 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
+end
diff --git a/activerecord/test/fixtures/edges.yml b/activerecord/test/fixtures/edges.yml
index c16c70dd2f..b804f7b6a6 100644
--- a/activerecord/test/fixtures/edges.yml
+++ b/activerecord/test/fixtures/edges.yml
@@ -1,6 +1,5 @@
<% (1..4).each do |id| %>
edge_<%= id %>:
- id: <%= id %>
source_id: <%= id %>
sink_id: <%= id + 1 %>
-<% end %> \ No newline at end of file
+<% end %>
diff --git a/activerecord/test/fixtures/faces.yml b/activerecord/test/fixtures/faces.yml
index 1dd2907cf7..c8e4a34484 100644
--- a/activerecord/test/fixtures/faces.yml
+++ b/activerecord/test/fixtures/faces.yml
@@ -5,3 +5,7 @@ trusting:
weather_beaten:
description: weather beaten
man: steve
+
+confused:
+ description: confused
+ polymorphic_man: gordon (Man)
diff --git a/activerecord/test/fixtures/interests.yml b/activerecord/test/fixtures/interests.yml
index ec71890ab6..9200a19d5a 100644
--- a/activerecord/test/fixtures/interests.yml
+++ b/activerecord/test/fixtures/interests.yml
@@ -23,7 +23,11 @@ woodsmanship:
zine: going_out
man: steve
-survial:
+survival:
topic: Survival
zine: going_out
man: steve
+
+llama_wrangling:
+ topic: Llama Wrangling
+ polymorphic_man: gordon (Man)
diff --git a/activerecord/test/models/face.rb b/activerecord/test/models/face.rb
index 1540dbf741..edb75d333f 100644
--- a/activerecord/test/models/face.rb
+++ b/activerecord/test/models/face.rb
@@ -1,5 +1,7 @@
class Face < ActiveRecord::Base
belongs_to :man, :inverse_of => :face
- # This is a "broken" inverse_of for the purposes of testing
+ belongs_to :polymorphic_man, :polymorphic => true, :inverse_of => :polymorphic_face
+ # These is a "broken" inverse_of for the purposes of testing
belongs_to :horrible_man, :class_name => 'Man', :inverse_of => :horrible_face
+ belongs_to :horrible_polymorphic_man, :polymorphic => true, :inverse_of => :horrible_polymorphic_face
end
diff --git a/activerecord/test/models/interest.rb b/activerecord/test/models/interest.rb
index d8291d00cc..d5d9226204 100644
--- a/activerecord/test/models/interest.rb
+++ b/activerecord/test/models/interest.rb
@@ -1,4 +1,5 @@
class Interest < ActiveRecord::Base
belongs_to :man, :inverse_of => :interests
+ belongs_to :polymorphic_man, :polymorphic => true, :inverse_of => :polymorphic_interests
belongs_to :zine, :inverse_of => :interests
end
diff --git a/activerecord/test/models/man.rb b/activerecord/test/models/man.rb
index f40bc9d0fc..4bff92dc98 100644
--- a/activerecord/test/models/man.rb
+++ b/activerecord/test/models/man.rb
@@ -1,6 +1,8 @@
class Man < ActiveRecord::Base
has_one :face, :inverse_of => :man
+ has_one :polymorphic_face, :class_name => 'Face', :as => :polymorphic_man, :inverse_of => :polymorphic_man
has_many :interests, :inverse_of => :man
+ has_many :polymorphic_interests, :class_name => 'Interest', :as => :polymorphic_man, :inverse_of => :polymorphic_man
# These are "broken" inverse_of associations for the purposes of testing
has_one :dirty_face, :class_name => 'Face', :inverse_of => :dirty_man
has_many :secret_interests, :class_name => 'Interest', :inverse_of => :secret_man
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index f2c05dd48f..88c1634717 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -19,6 +19,7 @@ class Pirate < ActiveRecord::Base
# These both have :autosave enabled because accepts_nested_attributes_for is used on them.
has_one :ship
+ has_one :update_only_ship, :class_name => 'Ship'
has_one :non_validated_ship, :class_name => 'Ship'
has_many :birds
has_many :birds_with_method_callbacks, :class_name => "Bird",
@@ -35,6 +36,7 @@ class Pirate < ActiveRecord::Base
accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ accepts_nested_attributes_for :update_only_ship, :update_only => true
accepts_nested_attributes_for :parrots_with_method_callbacks, :parrots_with_proc_callbacks,
:birds_with_method_callbacks, :birds_with_proc_callbacks, :allow_destroy => true
accepts_nested_attributes_for :birds_with_reject_all_blank, :reject_if => :all_blank
diff --git a/activerecord/test/models/reply.rb b/activerecord/test/models/reply.rb
index ba5a1d1d01..f1ba45b528 100644
--- a/activerecord/test/models/reply.rb
+++ b/activerecord/test/models/reply.rb
@@ -7,11 +7,13 @@ class Reply < Topic
belongs_to :topic_with_primary_key, :class_name => "Topic", :primary_key => "title", :foreign_key => "parent_title", :counter_cache => "replies_count"
has_many :replies, :class_name => "SillyReply", :dependent => :destroy, :foreign_key => "parent_id"
+ attr_accessible :title, :author_name, :author_email_address, :written_on, :content, :last_read, :parent_title
+end
+
+class WrongReply < Reply
validate :errors_on_empty_content
validate :title_is_wrong_create, :on => :create
- attr_accessible :title, :author_name, :author_email_address, :written_on, :content, :last_read, :parent_title
-
validate :check_empty_title
validate :check_content_mismatch, :on => :create
validate :check_wrong_update, :on => :update
diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb
index 06759d64b8..a96e38ab41 100644
--- a/activerecord/test/models/ship.rb
+++ b/activerecord/test/models/ship.rb
@@ -2,9 +2,11 @@ class Ship < ActiveRecord::Base
self.record_timestamps = false
belongs_to :pirate
+ belongs_to :update_only_pirate, :class_name => 'Pirate'
has_many :parts, :class_name => 'ShipPart', :autosave => true
accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ accepts_nested_attributes_for :update_only_pirate, :update_only => true
validates_presence_of :name
end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 15e5e12d03..1ec36e7832 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -160,7 +160,7 @@ ActiveRecord::Schema.define do
t.integer :access_level, :default => 1
end
- create_table :edges, :force => true do |t|
+ create_table :edges, :force => true, :id => false do |t|
t.column :source_id, :integer, :null => false
t.column :sink_id, :integer, :null => false
end
@@ -520,11 +520,15 @@ ActiveRecord::Schema.define do
create_table :faces, :force => true do |t|
t.string :description
t.integer :man_id
+ t.integer :polymorphic_man_id
+ t.string :polymorphic_man_type
end
create_table :interests, :force => true do |t|
t.string :topic
t.integer :man_id
+ t.integer :polymorphic_man_id
+ t.string :polymorphic_man_type
t.integer :zine_id
end
diff --git a/activeresource/Rakefile b/activeresource/Rakefile
index 6566e84d4c..9fa1f86914 100644
--- a/activeresource/Rakefile
+++ b/activeresource/Rakefile
@@ -27,11 +27,8 @@ task :default => [ :test ]
# Run the unit tests
Rake::TestTask.new { |t|
- activesupport_path = "#{File.dirname(__FILE__)}/../activesupport/lib"
- t.libs << activesupport_path if File.directory?(activesupport_path)
t.libs << "test"
t.pattern = 'test/**/*_test.rb'
- t.verbose = true
t.warning = true
}
diff --git a/activeresource/lib/active_resource.rb b/activeresource/lib/active_resource.rb
index fd4c199b48..3e4a1dd4a1 100644
--- a/activeresource/lib/active_resource.rb
+++ b/activeresource/lib/active_resource.rb
@@ -21,20 +21,24 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib"
-$:.unshift(activesupport_path) if File.directory?(activesupport_path)
-require 'active_support'
+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)
-activemodel_path = "#{File.dirname(__FILE__)}/../../activemodel/lib"
-$:.unshift(activemodel_path) if File.directory?(activemodel_path)
+require 'active_support'
require 'active_model'
module ActiveResource
- autoload :Base, 'active_resource/base'
- autoload :Connection, 'active_resource/connection'
- autoload :CustomMethods, 'active_resource/custom_methods'
- autoload :Formats, 'active_resource/formats'
- autoload :Observing, 'active_resource/observing'
- autoload :Validations, 'active_resource/validations'
- autoload :HttpMock, 'active_resource/http_mock'
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Connection
+ autoload :CustomMethods
+ autoload :Formats
+ autoload :HttpMock
+ autoload :Observing
+ autoload :Schema
+ autoload :Validations
end
diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb
index 0e74592b0c..b841108bd1 100644
--- a/activeresource/lib/active_resource/base.rb
+++ b/activeresource/lib/active_resource/base.rb
@@ -13,6 +13,9 @@ require 'set'
require 'uri'
require 'active_resource/exceptions'
+require 'active_resource/connection'
+require 'active_resource/formats'
+require 'active_resource/schema'
module ActiveResource
# ActiveResource::Base is the main class for mapping RESTful resources as models in a Rails application.
@@ -248,6 +251,124 @@ module ActiveResource
cattr_accessor :logger
class << self
+ # Creates a schema for this resource - setting the attributes that are
+ # known prior to fetching an instance from the remote system.
+ #
+ # The schema helps define the set of <tt>known_attributes</tt> of the
+ # current resource.
+ #
+ # There is no need to specify a schema for your Active Resource. If
+ # you do not, the <tt>known_attributes</tt> will be guessed from the
+ # instance attributes returned when an instance is fetched from the
+ # remote system.
+ #
+ # example:
+ # class Person < ActiveResource::Base
+ # schema do
+ # # define each attribute separately
+ # attribute 'name', :string
+ #
+ # # or use the convenience methods and pass >=1 attribute names
+ # string 'eye_colour', 'hair_colour'
+ # integer 'age'
+ # float 'height', 'weight'
+ #
+ # # unsupported types should be left as strings
+ # # overload the accessor methods if you need to convert them
+ # attribute 'created_at', 'string'
+ # end
+ # end
+ #
+ # p = Person.new
+ # p.respond_to? :name # => true
+ # p.respond_to? :age # => true
+ # p.name # => nil
+ # p.age # => nil
+ #
+ # j = Person.find_by_name('John') # <person><name>John</name><age>34</age><num_children>3</num_children></person>
+ # j.respond_to? :name # => true
+ # j.respond_to? :age # => true
+ # j.name # => 'John'
+ # j.age # => '34' # note this is a string!
+ # j.num_children # => '3' # note this is a string!
+ #
+ # p.num_children # => NoMethodError
+ #
+ # Attribute-types must be one of:
+ # string, integer, float
+ #
+ # Note: at present the attribute-type doesn't do anything, but stay
+ # tuned...
+ # Shortly it will also *cast* the value of the returned attribute.
+ # ie:
+ # j.age # => 34 # cast to an integer
+ # j.weight # => '65' # still a string!
+ #
+ def schema(&block)
+ if block_given?
+ schema_definition = Schema.new
+ schema_definition.instance_eval(&block)
+
+ # skip out if we didn't define anything
+ return unless schema_definition.attrs.present?
+
+ @schema ||= {}.with_indifferent_access
+ @known_attributes ||= []
+
+ schema_definition.attrs.each do |k,v|
+ @schema[k] = v
+ @known_attributes << k
+ end
+
+ schema
+ else
+ @schema ||= nil
+ end
+ end
+
+ # Alternative, direct way to specify a <tt>schema</tt> for this
+ # Resource. <tt>schema</tt> is more flexible, but this is quick
+ # for a very simple schema.
+ #
+ # Pass the schema as a hash with the keys being the attribute-names
+ # and the value being one of the accepted attribute types (as defined
+ # in <tt>schema</tt>)
+ #
+ # example:
+ #
+ # class Person < ActiveResource::Base
+ # schema = {'name' => :string, 'age' => :integer }
+ # end
+ #
+ # The keys/values can be strings or symbols. They will be converted to
+ # strings.
+ #
+ def schema=(the_schema)
+ unless the_schema.present?
+ # purposefully nulling out the schema
+ @schema = nil
+ @known_attributes = []
+ return
+ end
+
+ raise ArgumentError, "Expected a hash" unless the_schema.kind_of? Hash
+
+ schema do
+ the_schema.each {|k,v| attribute(k,v) }
+ end
+ end
+
+ # Returns the list of known attributes for this resource, gathered
+ # from the provided <tt>schema</tt>
+ # Attributes that are known will cause your resource to return 'true'
+ # when <tt>respond_to?</tt> is called on them. A known attribute will
+ # return nil if not set (rather than <t>MethodNotFound</tt>); thus
+ # known attributes can be used with <tt>validates_presence_of</tt>
+ # without a getter-method.
+ def known_attributes
+ @known_attributes ||= []
+ end
+
# Gets the URI of the REST resources to map for this class. The site variable is required for
# Active Resource's mapping to work.
def site
@@ -783,6 +904,21 @@ module ActiveResource
attr_accessor :attributes #:nodoc:
attr_accessor :prefix_options #:nodoc:
+ # If no schema has been defined for the class (see
+ # <tt>ActiveResource::schema=</tt>), the default automatic schema is
+ # generated from the current instance's attributes
+ def schema
+ self.class.schema || self.attributes
+ end
+
+ # This is a list of known attributes for this resource. Either
+ # gathered fromthe provided <tt>schema</tt>, or from the attributes
+ # set on this instance after it has been fetched from the remote system.
+ def known_attributes
+ self.class.known_attributes + self.attributes.keys.map(&:to_s)
+ end
+
+
# Constructor method for \new resources; the optional +attributes+ parameter takes a \hash
# of attributes for the \new resource.
#
@@ -1164,7 +1300,7 @@ module ActiveResource
method_name = method.to_s
if attributes.nil?
super
- elsif attributes.has_key?(method_name)
+ elsif known_attributes.include?(method_name)
true
elsif method_name =~ /(?:=|\?)$/ && attributes.include?($`)
true
@@ -1269,7 +1405,10 @@ module ActiveResource
attributes[$`]
end
else
- attributes.include?(method_name) ? attributes[method_name] : super
+ return attributes[method_name] if attributes.include?(method_name)
+ # not set right now but we know about it
+ return nil if known_attributes.include?(method_name)
+ super
end
end
end
diff --git a/activeresource/lib/active_resource/railtie.rb b/activeresource/lib/active_resource/railtie.rb
new file mode 100644
index 0000000000..4f264c82b8
--- /dev/null
+++ b/activeresource/lib/active_resource/railtie.rb
@@ -0,0 +1,2 @@
+require "active_resource"
+require "rails" \ No newline at end of file
diff --git a/activeresource/lib/active_resource/schema.rb b/activeresource/lib/active_resource/schema.rb
new file mode 100644
index 0000000000..8368b652c2
--- /dev/null
+++ b/activeresource/lib/active_resource/schema.rb
@@ -0,0 +1,55 @@
+require 'active_resource/exceptions'
+
+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 )
+
+ # An array of attribute definitions, representing the attributes that
+ # have been defined.
+ attr_accessor :attrs
+
+ # The internals of an Active Resource Schema are very simple -
+ # unlike an Active Record TableDefinition (on which it is based).
+ # It provides a set of convenience methods for people to define their
+ # schema using the syntax:
+ # schema do
+ # string :foo
+ # integer :bar
+ # end
+ #
+ # The schema stores the name and type of each attribute. That is then
+ # read out by the schema method to populate the actual
+ # Resource's schema
+ def initialize
+ @attrs = {}
+ end
+
+ def attribute(name, type, options = {})
+ raise ArgumentError, "Unknown Attribute type: #{type.inspect} for key: #{name.inspect}" unless type.nil? || Schema::KNOWN_ATTRIBUTE_TYPES.include?(type.to_s)
+
+ the_type = type.to_s
+ # TODO: add defaults
+ #the_attr = [type.to_s]
+ #the_attr << options[:default] if options.has_key? :default
+ @attrs[name.to_s] = the_type
+ self
+ end
+
+ # 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
+ def #{attr_type.to_s}(*args)
+ options = args.extract_options!
+ attr_names = args
+
+ attr_names.each { |name| attribute(name, '#{attr_type}', options) }
+ end
+ EOV
+ end
+ end
+end
diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb
index 10849be20c..5fa6d3023b 100644
--- a/activeresource/test/abstract_unit.rb
+++ b/activeresource/test/abstract_unit.rb
@@ -1,18 +1,17 @@
-root = File.expand_path('../../..', __FILE__)
begin
- require "#{root}/vendor/gems/environment"
+ require File.expand_path('../../../vendor/gems/environment', __FILE__)
rescue LoadError
- $:.unshift("#{root}/activesupport/lib")
end
-lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
+lib = File.expand_path('../../lib', __FILE__)
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
require 'rubygems'
require 'test/unit'
+require 'active_resource'
require 'active_support'
require 'active_support/test_case'
-require 'active_resource'
+require 'active_model/test_case'
$:.unshift "#{File.dirname(__FILE__)}/../test"
require 'setter_trap'
diff --git a/activeresource/test/cases/base/schema_test.rb b/activeresource/test/cases/base/schema_test.rb
new file mode 100644
index 0000000000..d9dc679941
--- /dev/null
+++ b/activeresource/test/cases/base/schema_test.rb
@@ -0,0 +1,420 @@
+require 'abstract_unit'
+require 'active_support/core_ext/hash/conversions'
+require "fixtures/person"
+require "fixtures/street_address"
+
+########################################################################
+# Testing the schema of your Active Resource models
+########################################################################
+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
+ end
+ def teardown
+ Person.schema = nil # hack to stop test bleedthrough...
+ end
+
+
+ #####################################################
+ # Passing in a schema directly and returning it
+ ####
+
+ test "schema on a new model should be empty" do
+ assert Person.schema.blank?, "should have a blank class schema"
+ assert Person.new.schema.blank?, "should have a blank instance schema"
+ end
+
+ test "schema should only accept a hash" do
+ ["blahblah", ['one','two'], [:age, :name], Person.new].each do |bad_schema|
+ assert_raises(ArgumentError,"should only accept a hash (or nil), but accepted: #{bad_schema.inspect}") do
+ Person.schema = bad_schema
+ end
+ end
+ end
+
+ test "schema should accept a simple hash" do
+ new_schema = {'age' => 'integer', 'name' => 'string'}
+
+ 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'}
+
+ assert_nothing_raised { Person.schema = new_schema }
+ assert_equal new_schema, Person.schema
+ end
+
+ test "schema should accept all known attribute types as values" do
+ # I'd prefer to use here...
+ ActiveResource::Schema::KNOWN_ATTRIBUTE_TYPES.each do |the_type|
+ assert_nothing_raised("should have accepted #{the_type.inspect}"){ Person.schema = {'my_key' => the_type }}
+ end
+ end
+
+ test "schema should not accept unknown values" do
+ bad_values = [ :oogle, :blob, 'thing']
+
+ bad_values.each do |bad_value|
+ assert_raises(ArgumentError,"should only accept a known attribute type, but accepted: #{bad_value.inspect}") do
+ Person.schema = {'key' => bad_value}
+ end
+ end
+ end
+
+ test "schema should accept nil and remove the schema" do
+ new_schema = {'age' => 'integer', 'name' => 'string'}
+ assert_nothing_raised { Person.schema = new_schema }
+ assert_equal new_schema, Person.schema # sanity check
+
+
+ assert_nothing_raised { Person.schema = nil }
+ assert_nil Person.schema, "should have nulled out the schema, but still had: #{Person.schema.inspect}"
+ end
+
+
+ test "schema should be with indifferent access" do
+ new_schema = {:age => :integer, 'name' => 'string'}
+ new_schema_syms = new_schema.keys
+
+ assert_nothing_raised { Person.schema = new_schema }
+ new_schema_syms.each do |col|
+ assert Person.new.respond_to?(col.to_s), "should respond to the schema's string key, but failed on: #{col.to_s}"
+ assert Person.new.respond_to?(col.to_sym), "should respond to the schema's symbol key, but failed on: #{col.to_sym}"
+ end
+ end
+
+
+ test "schema on a fetched resource should return all the attributes of that model instance" do
+ p = Person.find(1)
+ s = p.schema
+
+ assert s.present?, "should have found a non-empty schema!"
+
+ p.attributes.each do |the_attr, val|
+ assert s.has_key?(the_attr), "should have found attr: #{the_attr} in schema, but only had: #{s.inspect}"
+ end
+ end
+
+ test "with two instances, default schema should match the attributes of the individual instances - even if they differ" do
+ matz = Person.find(1)
+ rick = Person.find(5)
+
+ m_attrs = matz.attributes.keys.sort
+ r_attrs = rick.attributes.keys.sort
+
+ assert_not_equal m_attrs, r_attrs, "should have different attributes on each model"
+
+ assert_not_equal matz.schema, rick.schema, "should have had different schemas too"
+ end
+
+ 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'}
+ assert_nothing_raised {
+ Person.schema = new_schema
+ assert_equal new_schema, Person.schema, "should have saved the schema on the class"
+ assert_equal new_schema, Person.new.schema, "should have mde the schema available to every instance"
+ }
+ end
+
+ 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'}
+
+ matz = Person.find(1)
+ assert !matz.schema.blank?, "should have some sort of schema on an instance variable"
+ assert_not_equal new_schema, matz.schema, "should not have the class-level schema until it's been added to the class!"
+
+ assert_nothing_raised {
+ Person.schema = new_schema
+ assert_equal new_schema, matz.schema, "class-level schema should override instance-level schema"
+ }
+ end
+
+
+ #####################################################
+ # Using the schema syntax
+ ####
+
+ test "should be able to use schema" do
+ assert Person.respond_to?(:schema), "should at least respond to the schema method"
+
+ assert_nothing_raised("Should allow the schema to take a block") do
+ Person.schema { }
+ end
+ end
+
+ test "schema definition should store and return attribute set" do
+ assert_nothing_raised do
+ s = nil
+ Person.schema do
+ s = self
+ attribute :foo, :string
+ end
+ assert s.respond_to?(:attrs), "should return attributes in theory"
+ assert_equal({'foo' => 'string' }, s.attrs, "should return attributes in practice")
+ end
+ end
+
+ test "should be able to add attributes through schema" do
+ assert_nothing_raised do
+ s = nil
+ Person.schema do
+ s = self
+ attribute('foo', 'string')
+ end
+ assert s.attrs.has_key?('foo'), "should have saved the attribute name"
+ assert_equal 'string', s.attrs['foo'], "should have saved the attribute type"
+ end
+ end
+
+ test "should convert symbol attributes to strings" do
+ assert_nothing_raised do
+ s = nil
+ Person.schema do
+ attribute(:foo, :integer)
+ s = self
+ end
+
+ assert s.attrs.has_key?('foo'), "should have saved the attribute name as a string"
+ assert_equal 'integer', s.attrs['foo'], "should have saved the attribute type as a string"
+ end
+ end
+
+ test "should be able to add all known attribute types" do
+ assert_nothing_raised do
+ ActiveResource::Schema::KNOWN_ATTRIBUTE_TYPES.each do |the_type|
+ s = nil
+ Person.schema do
+ s = self
+ attribute('foo', the_type)
+ end
+ assert s.attrs.has_key?('foo'), "should have saved the attribute name"
+ assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}"
+ end
+ end
+ end
+
+ test "attributes should not accept unknown values" do
+ bad_values = [ :oogle, :blob, 'thing']
+
+ bad_values.each do |bad_value|
+ s = nil
+ assert_raises(ArgumentError,"should only accept a known attribute type, but accepted: #{bad_value.inspect}") do
+ Person.schema do
+ s = self
+ attribute 'key', bad_value
+ end
+ end
+ assert !self.respond_to?(bad_value), "should only respond to a known attribute type, but accepted: #{bad_value.inspect}"
+ assert_raises(NoMethodError,"should only have methods for known attribute types, but accepted: #{bad_value.inspect}") do
+ Person.schema do
+ send bad_value, 'key'
+ end
+ end
+ end
+ end
+
+
+ test "should accept attribute types as the type's name as the method" do
+ ActiveResource::Schema::KNOWN_ATTRIBUTE_TYPES.each do |the_type|
+ s = nil
+ Person.schema do
+ s = self
+ send(the_type,'foo')
+ end
+ assert s.attrs.has_key?('foo'), "should now have saved the attribute name"
+ assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}"
+ end
+ end
+
+ test "should accept multiple attribute names for an attribute method" do
+ names = ['foo','bar','baz']
+ s = nil
+ Person.schema do
+ s = self
+ string(*names)
+ end
+ names.each do |the_name|
+ assert s.attrs.has_key?(the_name), "should now have saved the attribute name: #{the_name}"
+ assert_equal 'string', s.attrs[the_name], "should have saved the attribute as a string"
+ end
+ end
+
+ #####################################################
+ # What a schema does for us
+ ####
+
+ # respond_to?
+
+ test "should respond positively to attributes that are only in the schema" do
+ new_attr_name = :my_new_schema_attribute
+ new_attr_name_two = :another_new_schema_attribute
+ assert Person.schema.blank?, "sanity check - should have a blank class schema"
+
+ assert !Person.new.respond_do?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet"
+ assert !Person.new.respond_do?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet"
+
+ assert_nothing_raised do
+ Person.schema = {new_attr_name.to_s => 'string'}
+ Person.schema { string new_attr_name_two }
+ end
+
+ assert Person.new.respond_to?(new_attr_name), "should respond to the attribute in a passed-in schema, but failed on: #{new_attr_name}"
+ assert Person.new.respond_to?(new_attr_name_two), "should respond to the attribute from the schema, but failed on: #{new_attr_name_two}"
+ end
+
+ test "should not care about ordering of schema definitions" do
+ new_attr_name = :my_new_schema_attribute
+ new_attr_name_two = :another_new_schema_attribute
+
+ assert Person.schema.blank?, "sanity check - should have a blank class schema"
+
+ assert !Person.new.respond_do?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet"
+ assert !Person.new.respond_do?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet"
+
+ assert_nothing_raised do
+ Person.schema { string new_attr_name_two }
+ Person.schema = {new_attr_name.to_s => 'string'}
+ end
+
+ assert Person.new.respond_to?(new_attr_name), "should respond to the attribute in a passed-in schema, but failed on: #{new_attr_name}"
+ assert Person.new.respond_to?(new_attr_name_two), "should respond to the attribute from the schema, but failed on: #{new_attr_name_two}"
+ end
+
+ # method_missing effects
+
+ test "should not give method_missing for attribute only in schema" do
+ new_attr_name = :another_new_schema_attribute
+ new_attr_name_two = :another_new_schema_attribute
+
+ assert Person.schema.blank?, "sanity check - should have a blank class schema"
+
+ assert_raises(NoMethodError, "should not have found the attribute: #{new_attr_name} as a method") do
+ Person.new.send(new_attr_name)
+ end
+ assert_raises(NoMethodError, "should not have found the attribute: #{new_attr_name_two} as a method") do
+ Person.new.send(new_attr_name_two)
+ end
+
+ Person.schema = {new_attr_name.to_s => :float}
+ Person.schema { string new_attr_name_two }
+
+ assert_nothing_raised do
+ Person.new.send(new_attr_name)
+ Person.new.send(new_attr_name_two)
+ end
+ end
+
+
+ ########
+ # Known attributes
+ #
+ # Attributes can be known to be attributes even if they aren't actually
+ # 'set' on a particular instance.
+ # This will only differ from 'attributes' if a schema has been set.
+
+ test "new model should have no known attributes" do
+ assert Person.known_attributes.blank?, "should have no known attributes"
+ assert Person.new.known_attributes.blank?, "should have no known attributes on a new instance"
+ end
+
+ test "setting schema should set known attributes on class and instance" do
+ new_schema = {'age' => 'integer', 'name' => 'string'}
+
+ assert_nothing_raised { Person.schema = new_schema }
+
+ assert_equal new_schema.keys, Person.known_attributes
+ assert_equal new_schema.keys, Person.new.known_attributes
+ end
+
+ test "known attributes on a fetched resource should return all the attributes of the instance" do
+ p = Person.find(1)
+ attrs = p.known_attributes
+
+ assert attrs.present?, "should have found some attributes!"
+
+ p.attributes.each do |the_attr, val|
+ assert attrs.include?(the_attr), "should have found attr: #{the_attr} in known attributes, but only had: #{attrs.inspect}"
+ end
+ end
+
+ test "with two instances, known attributes should match the attributes of the individual instances - even if they differ" do
+ matz = Person.find(1)
+ rick = Person.find(5)
+
+ m_attrs = matz.attributes.keys.sort
+ r_attrs = rick.attributes.keys.sort
+
+ assert_not_equal m_attrs, r_attrs, "should have different attributes on each model"
+
+ 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
+ # an attribute in common with fetched instance and one that isn't
+ new_schema = {'name' => 'string', 'my_strange_attribute' => 'string'}
+
+ assert_nothing_raised { Person.schema = new_schema }
+
+ matz = Person.find(1)
+ known_attrs = matz.known_attributes
+
+ matz.attributes.keys.each do |the_attr|
+ assert known_attrs.include?(the_attr), "should have found instance attr: #{the_attr} in known attributes, but only had: #{known_attrs.inspect}"
+ end
+ new_schema.keys.each do |the_attr|
+ assert known_attrs.include?(the_attr), "should have found schema attr: #{the_attr} in known attributes, but only had: #{known_attrs.inspect}"
+ end
+ end
+
+
+end
diff --git a/activeresource/test/cases/base_test.rb b/activeresource/test/cases/base_test.rb
index 1d3f7891ec..91349b810a 100644
--- a/activeresource/test/cases/base_test.rb
+++ b/activeresource/test/cases/base_test.rb
@@ -543,9 +543,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%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?name[]=bob&name[]=your+uncle%2Bme&name[]=&name[]=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false])
- assert_equal '/people.xml?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => {:a => [2,1], 'b' => 'fred'})
+ assert_equal '/people.xml?struct[a][]=2&struct[a][]=1&struct[b]=fred', Person.collection_path(:struct => {:a => [2,1], 'b' => 'fred'})
end
def test_custom_element_path
@@ -581,7 +581,7 @@ 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%5B%5D=work&type%5B%5D=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
+ assert_equal '/people/1/addresses/1.xml?type[]=work&type[]=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time'])
end
def test_custom_element_path_with_prefix_and_parameters
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
index 4edeadf10c..9b0a84678a 100644
--- a/activesupport/CHANGELOG
+++ b/activesupport/CHANGELOG
@@ -1,5 +1,9 @@
*Edge*
+* Added Object#presence that returns the object if it's #present? otherwise returns nil [DHH/Colin Kelley]
+
+* Add Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?/else calls [DHH]
+
* Update Edinburgh TimeZone to use "Europe/London" instead of "Europe/Dublin" #3310 [Phil Ross]
* Update bundled TZInfo to v0.3.15 [Geoff Buesing]
diff --git a/activesupport/Rakefile b/activesupport/Rakefile
index 2ada91830f..08af1d6fca 100644
--- a/activesupport/Rakefile
+++ b/activesupport/Rakefile
@@ -18,7 +18,6 @@ task :default => :test
Rake::TestTask.new do |t|
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
- t.verbose = true
t.warning = true
end
diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
index cabda2b073..2d2cbf6448 100644
--- a/activesupport/activesupport.gemspec
+++ b/activesupport/activesupport.gemspec
@@ -6,6 +6,8 @@ Gem::Specification.new do |s|
s.summary = "Support and utility classes used by the Rails framework."
s.description = %q{Utility library which carries commonly used classes and goodies from the Rails framework}
+ s.add_dependency('i18n', '>= 0.1.3')
+
s.files = Dir['CHANGELOG', 'README', 'lib/**/*']
s.require_path = 'lib'
s.has_rdoc = true
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 0478ae4ebc..3463000529 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -34,8 +34,38 @@ module ActiveSupport
end
end
-require 'active_support/autoload'
-require 'active_support/vendor'
+require "active_support/dependencies/autoload"
+
+module ActiveSupport
+ extend ActiveSupport::Autoload
-require 'i18n'
-I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml"
+ # 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 :Memoizable
+ autoload :MessageEncryptor
+ autoload :MessageVerifier
+ autoload :Multibyte
+ autoload :OptionMerger
+ autoload :OrderedHash
+ autoload :OrderedOptions
+ autoload :Notifications
+ autoload :Rescuable
+ autoload :SecureRandom
+ autoload :StringInquirer
+ autoload :XmlMini
+ end
+end
+
+require 'active_support/vendor'
diff --git a/activesupport/lib/active_support/all.rb b/activesupport/lib/active_support/all.rb
index f537818300..64600575d9 100644
--- a/activesupport/lib/active_support/all.rb
+++ b/activesupport/lib/active_support/all.rb
@@ -1,3 +1,4 @@
require 'active_support'
+require 'active_support/i18n'
require 'active_support/time'
require 'active_support/core_ext'
diff --git a/activesupport/lib/active_support/autoload.rb b/activesupport/lib/active_support/autoload.rb
deleted file mode 100644
index 63f7338a68..0000000000
--- a/activesupport/lib/active_support/autoload.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-module ActiveSupport
- autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
- autoload :Base64, 'active_support/base64'
- autoload :BasicObject, 'active_support/basic_object'
- autoload :Benchmarkable, 'active_support/benchmarkable'
- autoload :BufferedLogger, 'active_support/buffered_logger'
- autoload :Cache, 'active_support/cache'
- autoload :Callbacks, 'active_support/callbacks'
- autoload :Concern, 'active_support/concern'
- autoload :Configurable, 'active_support/configurable'
- autoload :DependencyModule, 'active_support/dependency_module'
- autoload :DeprecatedCallbacks, 'active_support/deprecated_callbacks'
- autoload :Deprecation, 'active_support/deprecation'
- autoload :Gzip, 'active_support/gzip'
- autoload :Inflector, 'active_support/inflector'
- autoload :Memoizable, 'active_support/memoizable'
- autoload :MessageEncryptor, 'active_support/message_encryptor'
- autoload :MessageVerifier, 'active_support/message_verifier'
- autoload :Multibyte, 'active_support/multibyte'
- autoload :OptionMerger, 'active_support/option_merger'
- autoload :OrderedHash, 'active_support/ordered_hash'
- autoload :OrderedOptions, 'active_support/ordered_options'
- autoload :Notifications, 'active_support/notifications'
- autoload :Rescuable, 'active_support/rescuable'
- autoload :SecureRandom, 'active_support/secure_random'
- autoload :StringInquirer, 'active_support/string_inquirer'
- autoload :XmlMini, 'active_support/xml_mini'
-end
diff --git a/activesupport/lib/active_support/benchmarkable.rb b/activesupport/lib/active_support/benchmarkable.rb
index 6a41aab166..ee02ecb043 100644
--- a/activesupport/lib/active_support/benchmarkable.rb
+++ b/activesupport/lib/active_support/benchmarkable.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/benchmark'
+require 'active_support/core_ext/hash/keys'
module ActiveSupport
module Benchmarkable
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index f2d957f154..ad238c1d96 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -4,6 +4,7 @@ require 'active_support/core_ext/benchmark'
require 'active_support/core_ext/exception'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/object/to_param'
+require 'active_support/core_ext/string/inflections'
module ActiveSupport
# See ActiveSupport::Cache::Store for documentation.
diff --git a/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb b/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb
index d87eb17337..d2370d78c5 100644
--- a/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb
@@ -1,3 +1,5 @@
+require 'active_support/gzip'
+
module ActiveSupport
module Cache
class CompressedMemCacheStore < MemCacheStore
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index 1b6b820ca4..d584c9e254 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -1,4 +1,5 @@
require 'memcache'
+require 'active_support/core_ext/array/extract_options'
module ActiveSupport
module Cache
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
index 5f6fe22416..86c7703c27 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/object/duplicable'
+require 'active_support/core_ext/string/inflections'
module ActiveSupport
module Cache
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 274df12e5d..6727eda811 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -1,6 +1,7 @@
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/class/inheritable_attributes'
require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/object/metaclass'
module ActiveSupport
# Callbacks are hooks into the lifecycle of an object that allow you to trigger logic
@@ -90,7 +91,7 @@ module ActiveSupport
class Callback
@@_callback_sequence = 0
- attr_accessor :chain, :filter, :kind, :options, :per_key, :klass
+ attr_accessor :chain, :filter, :kind, :options, :per_key, :klass, :raw_filter
def initialize(chain, filter, kind, options, klass)
@chain, @kind, @klass = chain, kind, klass
@@ -367,12 +368,6 @@ module ActiveSupport
method << "halted ? false : (block_given? ? value : true)"
method.compact.join("\n")
end
-
- def clone(klass)
- chain = CallbackChain.new(@name, @config.dup)
- callbacks = map { |c| c.clone(chain, klass) }
- chain.push(*callbacks)
- end
end
module ClassMethods
@@ -389,10 +384,16 @@ module ActiveSupport
# key. See #define_callbacks for more information.
#
def __define_runner(symbol) #:nodoc:
+ send("_update_#{symbol}_superclass_callbacks")
body = send("_#{symbol}_callbacks").compile(nil)
body, line = <<-RUBY_EVAL, __LINE__
def _run_#{symbol}_callbacks(key = nil, &blk)
+ if self.class.send("_update_#{symbol}_superclass_callbacks")
+ self.class.__define_runner(#{symbol.inspect})
+ return _run_#{symbol}_callbacks(key, &blk)
+ end
+
if key
name = "_run__\#{self.class.name.hash.abs}__#{symbol}__\#{key.hash.abs}__callbacks"
@@ -431,6 +432,8 @@ module ActiveSupport
# CallbackChain.
#
def __update_callbacks(name, filters = [], block = nil) #:nodoc:
+ send("_update_#{name}_superclass_callbacks")
+
type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before
options = filters.last.is_a?(Hash) ? filters.pop : {}
filters.unshift(block) if block
@@ -467,10 +470,11 @@ module ActiveSupport
# method that took into consideration the per_key conditions. This
# is a speed improvement for ActionPack.
#
- def set_callback(name, *filters, &block)
- __update_callbacks(name, filters, block) do |chain, type, filters, options|
+ def set_callback(name, *filter_list, &block)
+ __update_callbacks(name, filter_list, block) do |chain, type, filters, options|
filters.map! do |filter|
- chain.delete_if {|c| c.matches?(type, filter) }
+ removed = chain.delete_if {|c| c.matches?(type, filter) }
+ send("_removed_#{name}_callbacks").push(*removed)
Callback.new(chain, filter, type, options.dup, self)
end
@@ -480,18 +484,19 @@ module ActiveSupport
# Skip a previously defined callback for a given type.
#
- def skip_callback(name, *filters, &block)
- __update_callbacks(name, filters, block) do |chain, type, filters, options|
- chain = send("_#{name}_callbacks=", chain.clone(self))
-
+ def skip_callback(name, *filter_list, &block)
+ __update_callbacks(name, filter_list, block) do |chain, type, filters, options|
filters.each do |filter|
filter = chain.find {|c| c.matches?(type, filter) }
if filter && options.any?
- filter.recompile!(options, options[:per_key] || {})
- else
- chain.delete(filter)
+ new_filter = filter.clone(chain, self)
+ chain.insert(chain.index(filter), new_filter)
+ new_filter.recompile!(options, options[:per_key] || {})
end
+
+ chain.delete(filter)
+ send("_removed_#{name}_callbacks") << filter
end
end
end
@@ -499,7 +504,9 @@ module ActiveSupport
# Reset callbacks for a given type.
#
def reset_callbacks(symbol)
- send("_#{symbol}_callbacks").clear
+ callbacks = send("_#{symbol}_callbacks")
+ callbacks.clear
+ send("_removed_#{symbol}_callbacks").concat(callbacks)
__define_runner(symbol)
end
@@ -546,14 +553,46 @@ module ActiveSupport
#
# Defaults to :kind.
#
- def define_callbacks(*symbols)
- config = symbols.last.is_a?(Hash) ? symbols.pop : {}
- symbols.each do |symbol|
- extlib_inheritable_accessor("_#{symbol}_callbacks") do
- CallbackChain.new(symbol, config)
+ 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
+
+ extlib_inheritable_reader("_removed_#{callback}_callbacks") do
+ []
end
- __define_runner(symbol)
+ class_eval <<-METHOD, __FILE__, __LINE__ + 1
+ def self._#{callback}_superclass_callbacks
+ if superclass.respond_to?(:_#{callback}_callbacks)
+ superclass._#{callback}_callbacks + superclass._#{callback}_superclass_callbacks
+ else
+ []
+ end
+ end
+
+ def self._update_#{callback}_superclass_callbacks
+ changed, index = false, 0
+
+ callbacks = (_#{callback}_superclass_callbacks -
+ _#{callback}_callbacks) - _removed_#{callback}_callbacks
+
+ callbacks.each do |callback|
+ if new_index = _#{callback}_callbacks.index(callback)
+ index = new_index + 1
+ else
+ changed = true
+ _#{callback}_callbacks.insert(index, callback)
+ index = index + 1
+ end
+ end
+ changed
+ end
+ METHOD
+
+ __define_runner(callback)
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
index db140225e8..7fcef38372 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -1,6 +1,7 @@
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/inflector'
+require 'active_support/i18n'
class Array
# Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:
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
index 1c3ef05526..d3c3575748 100644
--- a/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb
+++ b/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb
@@ -1,3 +1,5 @@
+require 'cgi'
+
class CGI #:nodoc:
if RUBY_VERSION >= '1.9'
def self.escape_skipping_slashes(str)
diff --git a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb
index 301c09fc73..72e0eefb0a 100644
--- a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb
+++ b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/object/duplicable'
require 'active_support/core_ext/array/extract_options'
class Class
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 e4d22516c1..2b8e2b544f 100644
--- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
+++ b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
@@ -159,7 +159,7 @@ class Class
# (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)
+ def extlib_inheritable_reader(*ivars, &block)
options = ivars.extract_options!
ivars.each do |ivar|
@@ -178,6 +178,7 @@ class Class
end
RUBY
end
+ instance_variable_set(:"@#{ivar}", yield) if block_given?
end
end
diff --git a/activesupport/lib/active_support/core_ext/class/removal.rb b/activesupport/lib/active_support/core_ext/class/removal.rb
index 2dea3c24d5..652be4ed78 100644
--- a/activesupport/lib/active_support/core_ext/class/removal.rb
+++ b/activesupport/lib/active_support/core_ext/class/removal.rb
@@ -2,7 +2,11 @@ require 'active_support/core_ext/object/extending'
require 'active_support/core_ext/module/introspection'
class Class #:nodoc:
-
+
+ def reachable?
+ eval("defined?(::#{self}) && ::#{self}.equal?(self)")
+ end
+
# Unassociates the class with its subclasses and removes the subclasses
# themselves.
#
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index 3dd61334d0..9d2ad2bbcf 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -1,5 +1,7 @@
+require 'date'
require 'active_support/duration'
require 'active_support/core_ext/time/zones'
+require 'active_support/core_ext/object/acts_like'
class Date
class << self
diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb
index f6c870035b..90ab1eb281 100644
--- a/activesupport/lib/active_support/core_ext/date/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date/conversions.rb
@@ -1,3 +1,4 @@
+require 'date'
require 'active_support/inflector'
class Date
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 e93abfa4a3..26979aa906 100644
--- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
@@ -1,4 +1,5 @@
require 'rational' unless RUBY_VERSION >= '1.9.2'
+require 'active_support/core_ext/object/acts_like'
class DateTime
class << self
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 5f01bc4fd6..47a31839a6 100644
--- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -78,7 +78,18 @@ class DateTime
# Converts self to a floating-point number of seconds since the Unix epoch
def to_f
- days_since_unix_epoch = self - ::DateTime.civil(1970)
- (days_since_unix_epoch * 86_400).to_f
+ seconds_since_unix_epoch.to_f
+ end
+
+ # Converts self to an integer number of seconds since the Unix epoch
+ def to_i
+ seconds_since_unix_epoch.to_i
+ end
+
+ private
+
+ def seconds_since_unix_epoch
+ seconds_per_day = 86_400
+ (self - ::DateTime.civil(1970)) * seconds_per_day
end
end
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index b11c916f61..d0821a7c68 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -101,6 +101,11 @@ module Enumerable
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)
+ end
end
class Range #:nodoc:
diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb
index c6b6dc1e5e..48b185d05e 100644
--- a/activesupport/lib/active_support/core_ext/hash/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb
@@ -1,6 +1,8 @@
require 'active_support/time'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/hash/reverse_merge'
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/inflections'
class Hash
# This module exists to decorate files deserialized using Hash.from_xml with
diff --git a/activesupport/lib/active_support/core_ext/integer/multiple.rb b/activesupport/lib/active_support/core_ext/integer/multiple.rb
index 40bea54c67..8dff217ddc 100644
--- a/activesupport/lib/active_support/core_ext/integer/multiple.rb
+++ b/activesupport/lib/active_support/core_ext/integer/multiple.rb
@@ -1,6 +1,6 @@
class Integer
# Check whether the integer is evenly divisible by the argument.
def multiple_of?(number)
- self % number == 0
+ number != 0 ? self % number == 0 : zero?
end
end
diff --git a/activesupport/lib/active_support/core_ext/module/loading.rb b/activesupport/lib/active_support/core_ext/module/loading.rb
index 4b4b110b25..43d0578ae6 100644
--- a/activesupport/lib/active_support/core_ext/module/loading.rb
+++ b/activesupport/lib/active_support/core_ext/module/loading.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/string/inflections'
+
class Module
# Returns String#underscore applied to the module name minus trailing classes.
#
diff --git a/activesupport/lib/active_support/core_ext/module/synchronization.rb b/activesupport/lib/active_support/core_ext/module/synchronization.rb
index f72d512340..115b8abd4e 100644
--- a/activesupport/lib/active_support/core_ext/module/synchronization.rb
+++ b/activesupport/lib/active_support/core_ext/module/synchronization.rb
@@ -1,4 +1,5 @@
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
diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb
index 9a1f663bf3..eb99bb1a36 100644
--- a/activesupport/lib/active_support/core_ext/object/blank.rb
+++ b/activesupport/lib/active_support/core_ext/object/blank.rb
@@ -2,11 +2,11 @@ class Object
# An object is blank if it's false, empty, or a whitespace string.
# For example, "", " ", +nil+, [], and {} are blank.
#
- # This simplifies
+ # This simplifies:
#
# if !address.nil? && !address.empty?
#
- # to
+ # ...to:
#
# if !address.blank?
def blank?
@@ -17,6 +17,24 @@ class Object
def present?
!blank?
end
+
+ # Returns object if it's #present? otherwise returns nil.
+ # object.presence is equivalent to object.present? ? object : nil.
+ #
+ # This is handy for any representation of objects where blank is the same
+ # as not present at all. For example, this simplifies a common check for
+ # HTTP POST/query parameters:
+ #
+ # state = params[:state] if params[:state].present?
+ # country = params[:country] if params[:country].present?
+ # region = state || country || 'US'
+ #
+ # ...becomes:
+ #
+ # region = params[:state].presence || params[:country].presence || 'US'
+ def presence
+ self if present?
+ end
end
class NilClass #:nodoc:
diff --git a/activesupport/lib/active_support/core_ext/object/extending.rb b/activesupport/lib/active_support/core_ext/object/extending.rb
index 0cc74c8298..b8b6970382 100644
--- a/activesupport/lib/active_support/core_ext/object/extending.rb
+++ b/activesupport/lib/active_support/core_ext/object/extending.rb
@@ -1,46 +1,56 @@
-class Object
- def remove_subclasses_of(*superclasses) #:nodoc:
- Class.remove_class(*subclasses_of(*superclasses))
- end
-
- begin
- ObjectSpace.each_object(Class.new) {}
+require 'active_support/core_ext/class/removal'
+require 'active_support/core_ext/object/blank'
- # Exclude this class unless it's a subclass of our supers and is defined.
- # We check defined? in case we find a removed class that has yet to be
- # garbage collected. This also fails for anonymous classes -- please
- # submit a patch if you have a workaround.
- def subclasses_of(*superclasses) #:nodoc:
+class Class
+ # Rubinius
+ if defined?(Class.__subclasses__)
+ def descendents
subclasses = []
-
- superclasses.each do |sup|
- ObjectSpace.each_object(class << sup; self; end) do |k|
- if k != sup && (k.name.blank? || eval("defined?(::#{k}) && ::#{k}.object_id == k.object_id"))
- subclasses << k
- end
- end
- end
-
+ __subclasses__.each {|k| subclasses << k; subclasses.concat k.descendents }
subclasses
end
- rescue RuntimeError
- # JRuby and any implementations which cannot handle the objectspace traversal
- # above fall back to this implementation
- def subclasses_of(*superclasses) #:nodoc:
- subclasses = []
+ else
+ # MRI
+ begin
+ ObjectSpace.each_object(Class.new) {}
- superclasses.each do |sup|
+ def descendents
+ subclasses = []
+ ObjectSpace.each_object(class << self; self; end) do |k|
+ subclasses << k unless k == self
+ end
+ subclasses
+ end
+ # JRuby
+ rescue StandardError
+ def descendents
+ subclasses = []
ObjectSpace.each_object(Class) do |k|
- if superclasses.any? { |superclass| k < superclass } &&
- (k.name.blank? || eval("defined?(::#{k}) && ::#{k}.object_id == k.object_id"))
- subclasses << k
- end
+ subclasses << k if k < self
end
subclasses.uniq!
+ subclasses
end
- subclasses
end
end
+end
+
+class Object
+ def remove_subclasses_of(*superclasses) #:nodoc:
+ Class.remove_class(*subclasses_of(*superclasses))
+ end
+
+ # Exclude this class unless it's a subclass of our supers and is defined.
+ # We check defined? in case we find a removed class that has yet to be
+ # garbage collected. This also fails for anonymous classes -- please
+ # submit a patch if you have a workaround.
+ def subclasses_of(*superclasses) #:nodoc:
+ subclasses = []
+ superclasses.each do |klass|
+ subclasses.concat klass.descendents.select {|k| k.name.blank? || k.reachable?}
+ end
+ subclasses
+ end
def extended_by #:nodoc:
ancestors = class << self; ancestors end
diff --git a/activesupport/lib/active_support/core_ext/object/to_param.rb b/activesupport/lib/active_support/core_ext/object/to_param.rb
index a5e2260791..49e41e919a 100644
--- a/activesupport/lib/active_support/core_ext/object/to_param.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_param.rb
@@ -1,3 +1,5 @@
+
+
class Object
# Alias of <tt>to_s</tt>.
def to_param
@@ -38,7 +40,7 @@ class Hash
# ==== Examples
# { :name => 'David', :nationality => 'Danish' }.to_query # => "name=David&nationality=Danish"
#
- # { :name => 'David', :nationality => 'Danish' }.to_query('user') # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
+ # { :name => 'David', :nationality => 'Danish' }.to_query('user') # => "user[name]=David&user[nationality]=Danish"
def to_param(namespace = nil)
collect do |key, value|
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
diff --git a/activesupport/lib/active_support/core_ext/object/to_query.rb b/activesupport/lib/active_support/core_ext/object/to_query.rb
index 3f1540f685..c9981895b4 100644
--- a/activesupport/lib/active_support/core_ext/object/to_query.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_query.rb
@@ -7,7 +7,7 @@ class Object
# Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.
def to_query(key)
require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
- "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}"
+ "#{CGI.escape(key.to_s).gsub(/%(5B|5D)/n) { [$1].pack('H*') }}=#{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%5B%5D=Rails&hobbies%5B%5D=coding"
+ # ['Rails', 'coding'].to_query('hobbies') # => "hobbies[]=Rails&hobbies[]=coding"
def to_query(key)
prefix = "#{key}[]"
collect { |value| value.to_query(prefix) }.join '&'
diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb
index 0365b6af1c..411ea0f016 100644
--- a/activesupport/lib/active_support/core_ext/string.rb
+++ b/activesupport/lib/active_support/core_ext/string.rb
@@ -7,4 +7,5 @@ require 'active_support/core_ext/string/access'
require 'active_support/core_ext/string/xchar'
require 'active_support/core_ext/string/behavior'
require 'active_support/core_ext/string/interpolation'
-require 'active_support/core_ext/string/output_safety' \ No newline at end of file
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/string/exclude'
diff --git a/activesupport/lib/active_support/core_ext/string/exclude.rb b/activesupport/lib/active_support/core_ext/string/exclude.rb
new file mode 100644
index 0000000000..5ca268b953
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/exclude.rb
@@ -0,0 +1,6 @@
+class String
+ # The inverse of String#include?. Returns true if the string does not include the other string.
+ def exclude?(string)
+ !include?(string)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/interpolation.rb b/activesupport/lib/active_support/core_ext/string/interpolation.rb
index 41a061c1a4..2048d35091 100644
--- a/activesupport/lib/active_support/core_ext/string/interpolation.rb
+++ b/activesupport/lib/active_support/core_ext/string/interpolation.rb
@@ -5,7 +5,7 @@
You may redistribute it and/or modify it under the same license terms as Ruby.
=end
-if RUBY_VERSION < '1.9'
+if RUBY_VERSION < '1.9' && !"".respond_to?(:interpolate_without_ruby_19_syntax)
# KeyError is raised by String#% when the string contains a named placeholder
# that is not contained in the given arguments hash. Ruby 1.9 includes and
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 2cca4763f4..ceed90ce79 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -1,43 +1,41 @@
-class String
+class Object
+ def html_safe?
+ false
+ end
+end
+
+class Fixnum
def html_safe?
- defined?(@_rails_html_safe) && @_rails_html_safe
+ true
end
+end
+
+class String
+ attr_accessor :_rails_html_safe
+ alias html_safe? _rails_html_safe
def html_safe!
@_rails_html_safe = true
self
end
-
+
def html_safe
dup.html_safe!
end
-
+
alias original_plus +
def +(other)
result = original_plus(other)
- if html_safe? && also_html_safe?(other)
- result.html_safe!
- else
- result
- end
+ result._rails_html_safe = html_safe? && other.html_safe?
+ result
end
-
+
alias original_concat <<
+ alias safe_concat <<
def <<(other)
+ @_rails_html_safe = false unless other.html_safe?
result = original_concat(other)
- unless html_safe? && also_html_safe?(other)
- @_rails_html_safe = false
- end
- result
- end
-
- def concat(other)
- self << other
end
-
- private
- def also_html_safe?(other)
- other.respond_to?(:html_safe?) && other.html_safe?
- end
-
+
+ alias concat <<
end \ No newline at end of file
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index 4f4492f0fd..703b89ffd0 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -1,4 +1,5 @@
require 'active_support/duration'
+require 'active_support/core_ext/date/acts_like'
require 'active_support/core_ext/date/calculations'
class Time
diff --git a/activesupport/lib/active_support/dependencies/autoload.rb b/activesupport/lib/active_support/dependencies/autoload.rb
new file mode 100644
index 0000000000..44edb89ad5
--- /dev/null
+++ b/activesupport/lib/active_support/dependencies/autoload.rb
@@ -0,0 +1,49 @@
+require "active_support/inflector/methods"
+
+module ActiveSupport
+ module Autoload
+ @@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
+
+ def autoload_under(path)
+ @@under_path, old_path = path, @@under_path
+ yield
+ ensure
+ @@under_path = old_path
+ end
+
+ def autoload_at(path)
+ @@at_path, old_path = path, @@at_path
+ yield
+ ensure
+ @@at_path = old_path
+ end
+
+ def eager_autoload
+ old_eager, @@eager_autoload = @@eager_autoload, true
+ yield
+ ensure
+ @@eager_autoload = old_eager
+ end
+
+ def self.eager_autoload!
+ @@autoloads.values.each { |file| require file }
+ end
+
+ def autoloads
+ @@autoloads
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecated_callbacks.rb b/activesupport/lib/active_support/deprecated_callbacks.rb
deleted file mode 100644
index f56fef0b6d..0000000000
--- a/activesupport/lib/active_support/deprecated_callbacks.rb
+++ /dev/null
@@ -1,284 +0,0 @@
-require 'active_support/core_ext/array/extract_options'
-require 'active_support/core_ext/array/wrap'
-
-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.
- #
- # Mixing in this module allows you to define callbacks in your class.
- #
- # Example:
- # class Storage
- # include ActiveSupport::DeprecatedCallbacks
- #
- # define_callbacks :before_save, :after_save
- # end
- #
- # class ConfigStorage < Storage
- # before_save :saving_message
- # def saving_message
- # puts "saving..."
- # end
- #
- # after_save do |object|
- # puts "saved"
- # end
- #
- # def save
- # run_callbacks(:before_save)
- # puts "- save"
- # run_callbacks(:after_save)
- # end
- # end
- #
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # saving...
- # - save
- # saved
- #
- # Callbacks from parent classes are inherited.
- #
- # Example:
- # class Storage
- # include ActiveSupport::DeprecatedCallbacks
- #
- # define_callbacks :before_save, :after_save
- #
- # before_save :prepare
- # def prepare
- # puts "preparing save"
- # end
- # end
- #
- # class ConfigStorage < Storage
- # before_save :saving_message
- # def saving_message
- # puts "saving..."
- # end
- #
- # after_save do |object|
- # puts "saved"
- # end
- #
- # def save
- # run_callbacks(:before_save)
- # puts "- save"
- # run_callbacks(:after_save)
- # end
- # end
- #
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # preparing save
- # saving...
- # - save
- # saved
- module DeprecatedCallbacks
- class CallbackChain < Array
- def self.build(kind, *methods, &block)
- methods, options = extract_options(*methods, &block)
- methods.map! { |method| Callback.new(kind, method, options) }
- new(methods)
- end
-
- def run(object, options = {}, &terminator)
- enumerator = options[:enumerator] || :each
-
- unless block_given?
- send(enumerator) { |callback| callback.call(object) }
- else
- send(enumerator) do |callback|
- result = callback.call(object)
- break result if terminator.call(result, object)
- end
- end
- end
-
- # TODO: Decompose into more Array like behavior
- def replace_or_append!(chain)
- if index = index(chain)
- self[index] = chain
- else
- self << chain
- end
- self
- end
-
- def find(callback, &block)
- select { |c| c == callback && (!block_given? || yield(c)) }.first
- end
-
- def delete(callback)
- super(callback.is_a?(Callback) ? callback : find(callback))
- end
-
- private
- def self.extract_options(*methods, &block)
- methods.flatten!
- options = methods.extract_options!
- methods << block if block_given?
- return methods, options
- end
-
- def extract_options(*methods, &block)
- self.class.extract_options(*methods, &block)
- end
- end
-
- class Callback
- attr_reader :kind, :method, :identifier, :options
-
- def initialize(kind, method, options = {})
- @kind = kind
- @method = method
- @identifier = options[:identifier]
- @options = options
- end
-
- def ==(other)
- case other
- when Callback
- (self.identifier && self.identifier == other.identifier) || self.method == other.method
- else
- (self.identifier && self.identifier == other) || self.method == other
- end
- end
-
- def eql?(other)
- self == other
- end
-
- def dup
- self.class.new(@kind, @method, @options.dup)
- end
-
- def hash
- if @identifier
- @identifier.hash
- else
- @method.hash
- end
- end
-
- def call(*args, &block)
- evaluate_method(method, *args, &block) if should_run_callback?(*args)
- rescue LocalJumpError
- raise ArgumentError,
- "Cannot yield from a Proc type filter. The Proc must take two " +
- "arguments and execute #call on the second argument."
- end
-
- private
- def evaluate_method(method, *args, &block)
- case method
- when Symbol
- object = args.shift
- object.send(method, *args, &block)
- when String
- eval(method, args.first.instance_eval { binding })
- when Proc, Method
- method.call(*args, &block)
- else
- if method.respond_to?(kind)
- method.send(kind, *args, &block)
- else
- raise ArgumentError,
- "Callbacks must be a symbol denoting the method to call, a string to be evaluated, " +
- "a block to be invoked, or an object responding to the callback method."
- end
- end
- end
-
- def should_run_callback?(*args)
- Array.wrap(options[:if]).flatten.compact.all? { |a| evaluate_method(a, *args) } &&
- !Array.wrap(options[:unless]).flatten.compact.any? { |a| evaluate_method(a, *args) }
- end
- end
-
- def self.included(base)
- base.extend ClassMethods
- end
-
- module ClassMethods
- def define_callbacks(*callbacks)
- ActiveSupport::Deprecation.warn('ActiveSupport::DeprecatedCallbacks has been deprecated in favor of ActiveSupport::Callbacks', caller)
-
- callbacks.each do |callback|
- class_eval <<-"end_eval", __FILE__, __LINE__ + 1
- def self.#{callback}(*methods, &block) # def self.before_save(*methods, &block)
- callbacks = CallbackChain.build(:#{callback}, *methods, &block) # callbacks = CallbackChain.build(:before_save, *methods, &block)
- @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
- @#{callback}_callbacks.concat callbacks # @before_save_callbacks.concat callbacks
- end # end
- #
- def self.#{callback}_callback_chain # def self.before_save_callback_chain
- @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
- #
- if superclass.respond_to?(:#{callback}_callback_chain) # if superclass.respond_to?(:before_save_callback_chain)
- CallbackChain.new( # CallbackChain.new(
- superclass.#{callback}_callback_chain + # superclass.before_save_callback_chain +
- @#{callback}_callbacks # @before_save_callbacks
- ) # )
- else # else
- @#{callback}_callbacks # @before_save_callbacks
- end # end
- end # end
- end_eval
- end
- end
- end
-
- # Runs all the callbacks defined for the given options.
- #
- # If a block is given it will be called after each callback receiving as arguments:
- #
- # * the result from the callback
- # * the object which has the callback
- #
- # If the result from the block evaluates to +true+, the callback chain is stopped.
- #
- # Example:
- # class Storage
- # include ActiveSupport::DeprecatedCallbacks
- #
- # define_callbacks :before_save, :after_save
- # end
- #
- # class ConfigStorage < Storage
- # before_save :pass
- # before_save :pass
- # before_save :stop
- # before_save :pass
- #
- # def pass
- # puts "pass"
- # end
- #
- # def stop
- # puts "stop"
- # return false
- # end
- #
- # def save
- # result = run_callbacks(:before_save) { |result, object| result == false }
- # puts "- save" if result
- # end
- # end
- #
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # pass
- # pass
- # stop
- def run_callbacks(kind, options = {}, &block)
- self.class.send("#{kind}_callback_chain").run(self, options, &block)
- end
- end
-end
diff --git a/activesupport/lib/active_support/deprecation/method_wrappers.rb b/activesupport/lib/active_support/deprecation/method_wrappers.rb
index deb29a82b8..cec8024b17 100644
--- a/activesupport/lib/active_support/deprecation/method_wrappers.rb
+++ b/activesupport/lib/active_support/deprecation/method_wrappers.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/module/deprecation'
require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/array/extract_options'
module ActiveSupport
class << Deprecation
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 713ae1b671..c1f0e4bf81 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -1,5 +1,6 @@
require 'active_support/basic_object'
require 'active_support/core_ext/array/conversions'
+require 'active_support/core_ext/object/acts_like'
module ActiveSupport
# Provides accurate date and time measurements using Date#advance and
diff --git a/activesupport/lib/active_support/i18n.rb b/activesupport/lib/active_support/i18n.rb
new file mode 100644
index 0000000000..854c60eec1
--- /dev/null
+++ b/activesupport/lib/active_support/i18n.rb
@@ -0,0 +1,2 @@
+require 'i18n'
+I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml" \ No newline at end of file
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 3c15056c41..c8415d5449 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -65,6 +65,15 @@ module ActiveSupport
ESCAPED_CHARS = {
+ "\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002',
+ "\x03" => '\u0003', "\x04" => '\u0004', "\x05" => '\u0005',
+ "\x06" => '\u0006', "\x07" => '\u0007', "\x0B" => '\u000B',
+ "\x0E" => '\u000E', "\x0F" => '\u000F', "\x10" => '\u0010',
+ "\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013',
+ "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
+ "\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019',
+ "\x1A" => '\u001A', "\x1B" => '\u001B', "\x1C" => '\u001C',
+ "\x1D" => '\u001D', "\x1E" => '\u001E', "\x1F" => '\u001F',
"\010" => '\b',
"\f" => '\f',
"\n" => '\n',
@@ -86,9 +95,9 @@ module ActiveSupport
def escape_html_entities_in_json=(value)
self.escape_regex = \
if @escape_html_entities_in_json = value
- /[\010\f\n\r\t"\\><&]/
+ /[\x00-\x1F"\\><&]/
else
- /[\010\f\n\r\t"\\]/
+ /[\x00-\x1F"\\]/
end
end
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
index 347af9dc76..51fa626b45 100644
--- a/activesupport/lib/active_support/message_encryptor.rb
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -1,4 +1,5 @@
require 'openssl'
+require 'active_support/base64'
module ActiveSupport
# MessageEncryptor is a simple way to encrypt values which get stored somewhere
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index 87e4b1ad33..6c46b68eaf 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -1,3 +1,6 @@
+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
# to prevent tampering.
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index 7a9f76b26a..d9bfcbfcab 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -1,7 +1,4 @@
-require 'thread'
require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/secure_random'
module ActiveSupport
# Notifications provides an instrumentation API for Ruby. To instrument an
@@ -41,149 +38,42 @@ module ActiveSupport
# to subscribers in a thread. You can use any queue implementation you want.
#
module Notifications
- mattr_accessor :queue
+ autoload :Instrumenter, 'active_support/notifications/instrumenter'
+ autoload :Event, 'active_support/notifications/instrumenter'
+ autoload :Fanout, 'active_support/notifications/fanout'
class << self
- delegate :instrument, :transaction_id, :transaction, :to => :instrumenter
+ attr_writer :notifier
+ delegate :publish, :subscribe, :instrument, :to => :notifier
- def instrumenter
- Thread.current[:notifications_instrumeter] ||= Instrumenter.new(publisher)
- end
-
- def publisher
- @publisher ||= Publisher.new(queue)
- end
-
- def subscribe(pattern=nil, &block)
- Subscriber.new(queue).bind(pattern).subscribe(&block)
+ def notifier
+ @notifier ||= Notifier.new
end
end
- class Instrumenter
- def initialize(publisher)
- @publisher = publisher
- @id = random_id
- end
-
- def transaction
- @id, old_id = random_id, @id
- yield
- ensure
- @id = old_id
- end
-
- def transaction_id
- @id
- end
-
- def instrument(name, payload={})
- time = Time.now
- result = yield if block_given?
- ensure
- @publisher.publish(name, time, Time.now, result, @id, payload)
- end
-
- private
- def random_id
- SecureRandom.hex(10)
- end
- end
-
- class Publisher
- def initialize(queue)
+ class Notifier
+ def initialize(queue = Fanout.new)
@queue = queue
end
def publish(*args)
@queue.publish(*args)
end
- end
- class Subscriber
- def initialize(queue)
- @queue = queue
+ def subscribe(pattern = nil, &block)
+ @queue.bind(pattern).subscribe(&block)
end
- def bind(pattern)
- @pattern = pattern
- self
+ def wait
+ @queue.wait
end
- def subscribe
- @queue.subscribe(@pattern) do |*args|
- yield(*args)
- end
- end
- end
-
- class Event
- attr_reader :name, :time, :end, :transaction_id, :result, :payload
-
- def initialize(name, start, ending, result, transaction_id, payload)
- @name = name
- @payload = payload.dup
- @time = start
- @transaction_id = transaction_id
- @end = ending
- @result = result
- end
+ delegate :instrument, :to => :current_instrumenter
- def duration
- @duration ||= 1000.0 * (@end - @time)
- end
-
- def parent_of?(event)
- start = (self.time - event.time) * 1000
- start <= 0 && (start + duration >= event.duration)
- end
- end
-
- # This is a default queue implementation that ships with Notifications. It
- # consumes events in a thread and publish them to all registered subscribers.
- #
- class LittleFanout
- def initialize
- @listeners = []
- end
-
- def publish(*args)
- @listeners.each { |l| l.publish(*args) }
- end
-
- def subscribe(pattern=nil, &block)
- @listeners << Listener.new(pattern, &block)
- end
-
- def drained?
- @listeners.all? &:drained?
- end
-
- class Listener
- def initialize(pattern, &block)
- @pattern = pattern
- @subscriber = block
- @queue = Queue.new
- Thread.new { consume }
+ private
+ def current_instrumenter
+ Thread.current[:"instrumentation_#{object_id}"] ||= Notifications::Instrumenter.new(self)
end
-
- def publish(name, *args)
- if !@pattern || @pattern === name.to_s
- @queue << args.unshift(name)
- end
- end
-
- def consume
- while args = @queue.shift
- @subscriber.call(*args)
- end
- end
-
- def drained?
- @queue.size.zero?
- end
- end
end
end
-
- Notifications.queue = Notifications::LittleFanout.new
end
diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb
new file mode 100644
index 0000000000..bb07e4765c
--- /dev/null
+++ b/activesupport/lib/active_support/notifications/fanout.rb
@@ -0,0 +1,101 @@
+require 'thread'
+
+module ActiveSupport
+ module Notifications
+ # This is a default queue implementation that ships with Notifications. It
+ # consumes events in a thread and publish them to all registered subscribers.
+ #
+ class Fanout
+ def initialize(sync = false)
+ @subscriber_klass = sync ? Subscriber : AsyncSubscriber
+ @subscribers = []
+ end
+
+ def bind(pattern)
+ Binding.new(self, pattern)
+ end
+
+ def subscribe(pattern = nil, &block)
+ @subscribers << @subscriber_klass.new(pattern, &block)
+ end
+
+ def publish(*args)
+ @subscribers.each { |s| s.publish(*args) }
+ end
+
+ def wait
+ sleep(0.05) until @subscribers.all?(&:drained?)
+ end
+
+ # Used for internal implementation only.
+ class Binding #:nodoc:
+ def initialize(queue, pattern)
+ @queue = queue
+ @pattern =
+ case pattern
+ when Regexp, NilClass
+ pattern
+ else
+ /^#{Regexp.escape(pattern.to_s)}/
+ end
+ end
+
+ def subscribe(&block)
+ @queue.subscribe(@pattern, &block)
+ end
+ end
+
+ class Subscriber #:nodoc:
+ def initialize(pattern, &block)
+ @pattern = pattern
+ @block = block
+ end
+
+ def publish(*args)
+ push(*args) if matches?(args.first)
+ end
+
+ def drained?
+ true
+ end
+
+ private
+ def matches?(name)
+ !@pattern || @pattern =~ name.to_s
+ end
+
+ def push(*args)
+ @block.call(*args)
+ end
+ end
+
+ # Used for internal implementation only.
+ class AsyncSubscriber < Subscriber #:nodoc:
+ def initialize(pattern, &block)
+ super
+ @events = Queue.new
+ start_consumer
+ end
+
+ def drained?
+ @events.empty?
+ end
+
+ private
+ def start_consumer
+ Thread.new { consume }
+ end
+
+ def consume
+ while args = @events.shift
+ @block.call(*args)
+ end
+ end
+
+ def push(*args)
+ @events << args
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/notifications/instrumenter.rb b/activesupport/lib/active_support/notifications/instrumenter.rb
new file mode 100644
index 0000000000..0655dd0cb6
--- /dev/null
+++ b/activesupport/lib/active_support/notifications/instrumenter.rb
@@ -0,0 +1,46 @@
+require 'active_support/secure_random'
+require 'active_support/core_ext/module/delegation'
+
+module ActiveSupport
+ module Notifications
+ class Instrumenter
+ def initialize(notifier)
+ @id = unique_id
+ @notifier = notifier
+ end
+
+ def instrument(name, payload={})
+ time = Time.now
+ yield if block_given?
+ ensure
+ @notifier.publish(name, time, Time.now, @id, payload)
+ end
+
+ private
+ def unique_id
+ SecureRandom.hex(10)
+ end
+ end
+
+ class Event
+ attr_reader :name, :time, :end, :transaction_id, :payload
+
+ def initialize(name, start, ending, transaction_id, payload)
+ @name = name
+ @payload = payload.dup
+ @time = start
+ @transaction_id = transaction_id
+ @end = ending
+ end
+
+ def duration
+ @duration ||= 1000.0 * (@end - @time)
+ end
+
+ def parent_of?(event)
+ start = (self.time - event.time) * 1000
+ start <= 0 && (start + duration >= event.duration)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
index f0119f5994..6e660f8647 100644
--- a/activesupport/lib/active_support/rescuable.rb
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -1,5 +1,7 @@
require 'active_support/core_ext/class/inheritable_attributes'
require 'active_support/core_ext/proc'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/array/extract_options'
module ActiveSupport
# Rescuable module adds support for easier exception handling.
diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb
index f811239077..1e49ccdade 100644
--- a/activesupport/lib/active_support/ruby/shim.rb
+++ b/activesupport/lib/active_support/ruby/shim.rb
@@ -14,5 +14,6 @@ require 'active_support/core_ext/date_time/conversions'
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/process/daemon'
require 'active_support/core_ext/string/conversions'
+require 'active_support/core_ext/string/interpolation'
require 'active_support/core_ext/rexml'
require 'active_support/core_ext/time/conversions'
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
index c75b59c284..453f4fcc0f 100644
--- a/activesupport/lib/active_support/testing/isolation.rb
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -1,10 +1,25 @@
module ActiveSupport
module Testing
+ class RemoteError < StandardError
+
+ attr_reader :message, :backtrace
+
+ def initialize(exception)
+ @message = "caught #{exception.class.name}: #{exception.message}"
+ @backtrace = exception.backtrace
+ end
+ end
+
class ProxyTestResult
def initialize
@calls = []
end
+ def add_error(e)
+ e = Test::Unit::Error.new(e.test_name, RemoteError.new(e.exception))
+ @calls << [:add_error, e]
+ end
+
def __replay__(result)
@calls.each do |name, args|
result.send(name, *args)
@@ -21,28 +36,56 @@ module ActiveSupport
!ENV["NO_FORK"] && RUBY_PLATFORM !~ /mswin|mingw|java/
end
- def run(result)
- unless defined?(@@ran_class_setup)
- self.class.setup if self.class.respond_to?(:setup)
- @@ran_class_setup = true
+ def self.included(base)
+ if defined?(::MiniTest) && base < ::MiniTest::Unit::TestCase
+ base.send :include, MiniTest
+ elsif defined?(Test::Unit)
+ base.send :include, TestUnit
end
+ end
+
+ module TestUnit
+ def run(result)
+ unless defined?(@@ran_class_setup)
+ self.class.setup if self.class.respond_to?(:setup)
+ @@ran_class_setup = true
+ end
- yield(Test::Unit::TestCase::STARTED, name)
+ yield(Test::Unit::TestCase::STARTED, name)
- @_result = result
+ @_result = result
- serialized = run_in_isolation do |proxy|
- begin
- super(proxy) { }
- rescue Exception => e
- proxy.add_error(Test::Unit::Error.new(name, e))
+ serialized = run_in_isolation do |proxy|
+ begin
+ super(proxy) { }
+ rescue Exception => e
+ proxy.add_error(Test::Unit::Error.new(name, e))
+ end
end
+
+ retval, proxy = Marshal.load(serialized)
+ proxy.__replay__(@_result)
+
+ yield(Test::Unit::TestCase::FINISHED, name)
+ retval
end
+ end
- proxy = Marshal.load(serialized)
- proxy.__replay__(@_result)
+ module MiniTest
+ def run(runner)
+ unless defined?(@@ran_class_setup)
+ self.class.setup if self.class.respond_to?(:setup)
+ @@ran_class_setup = true
+ end
+
+ serialized = run_in_isolation do |runner|
+ super(runner)
+ end
- yield(Test::Unit::TestCase::FINISHED, name)
+ retval, proxy = Marshal.load(serialized)
+ proxy.__replay__(runner)
+ retval
+ end
end
module Forking
@@ -52,8 +95,8 @@ module ActiveSupport
pid = fork do
read.close
proxy = ProxyTestResult.new
- yield proxy
- write.puts [Marshal.dump(proxy)].pack("m")
+ retval = yield proxy
+ write.puts [Marshal.dump([retval, proxy])].pack("m")
exit!
end
@@ -72,9 +115,9 @@ module ActiveSupport
if ENV["ISOLATION_TEST"]
proxy = ProxyTestResult.new
- yield proxy
+ retval = yield proxy
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
- file.puts [Marshal.dump(proxy)].pack("m")
+ file.puts [Marshal.dump([retval, proxy])].pack("m")
end
exit!
else
diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb
index ab34f975f6..24eea1e40b 100644
--- a/activesupport/lib/active_support/testing/performance.rb
+++ b/activesupport/lib/active_support/testing/performance.rb
@@ -1,450 +1,455 @@
-require 'ruby-prof'
-
-require 'fileutils'
-require 'rails/version'
-
-module ActiveSupport
- module Testing
- module Performance
- DEFAULTS =
- if benchmark = ARGV.include?('--benchmark') # HAX for rake test
- { :benchmark => true,
- :runs => 4,
- :metrics => [:wall_time, :memory, :objects, :gc_runs, :gc_time],
- :output => 'tmp/performance' }
- else
- { :benchmark => false,
- :runs => 1,
- :min_percent => 0.01,
- :metrics => [:process_time, :memory, :objects],
- :formats => [:flat, :graph_html, :call_tree],
- :output => 'tmp/performance' }
- end.freeze
-
- def self.included(base)
- base.superclass_delegating_accessor :profile_options
- base.profile_options = DEFAULTS
- end
+begin
+ require 'ruby-prof'
+
+ require 'fileutils'
+ require 'rails/version'
+ require 'active_support/core_ext/class/delegating_attributes'
+ require 'active_support/core_ext/string/inflections'
+
+ module ActiveSupport
+ module Testing
+ module Performance
+ DEFAULTS =
+ if benchmark = ARGV.include?('--benchmark') # HAX for rake test
+ { :benchmark => true,
+ :runs => 4,
+ :metrics => [:wall_time, :memory, :objects, :gc_runs, :gc_time],
+ :output => 'tmp/performance' }
+ else
+ { :benchmark => false,
+ :runs => 1,
+ :min_percent => 0.01,
+ :metrics => [:process_time, :memory, :objects],
+ :formats => [:flat, :graph_html, :call_tree],
+ :output => 'tmp/performance' }
+ end.freeze
+
+ def self.included(base)
+ base.superclass_delegating_accessor :profile_options
+ base.profile_options = DEFAULTS
+ end
- def full_test_name
- "#{self.class.name}##{method_name}"
- end
+ def full_test_name
+ "#{self.class.name}##{method_name}"
+ end
- def run(result)
- return if method_name =~ /^default_test$/
+ def run(result)
+ return if method_name =~ /^default_test$/
- yield(self.class::STARTED, name)
- @_result = result
+ yield(self.class::STARTED, name)
+ @_result = result
- run_warmup
- if profile_options && metrics = profile_options[:metrics]
- metrics.each do |metric_name|
- if klass = Metrics[metric_name.to_sym]
- run_profile(klass.new)
- result.add_run
+ run_warmup
+ if profile_options && metrics = profile_options[:metrics]
+ metrics.each do |metric_name|
+ if klass = Metrics[metric_name.to_sym]
+ run_profile(klass.new)
+ result.add_run
+ end
end
end
- end
- yield(self.class::FINISHED, name)
- end
+ yield(self.class::FINISHED, name)
+ end
- def run_test(metric, mode)
- run_callbacks :setup
- setup
- metric.send(mode) { __send__ @method_name }
- rescue ::Test::Unit::AssertionFailedError => e
- add_failure(e.message, e.backtrace)
- rescue StandardError, ScriptError
- add_error($!)
- ensure
- begin
- teardown
- run_callbacks :teardown, :enumerator => :reverse_each
+ def run_test(metric, mode)
+ run_callbacks :setup
+ setup
+ metric.send(mode) { __send__ @method_name }
rescue ::Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue StandardError, ScriptError
add_error($!)
+ 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($!)
+ end
end
- end
- protected
- def run_warmup
- GC.start
+ protected
+ def run_warmup
+ GC.start
- time = Metrics::Time.new
- run_test(time, :benchmark)
- puts "%s (%s warmup)" % [full_test_name, time.format(time.total)]
+ time = Metrics::Time.new
+ run_test(time, :benchmark)
+ puts "%s (%s warmup)" % [full_test_name, time.format(time.total)]
- GC.start
- end
-
- def run_profile(metric)
- klass = profile_options[:benchmark] ? Benchmarker : Profiler
- performer = klass.new(self, metric)
+ GC.start
+ end
- performer.run
- puts performer.report
- performer.record
- end
+ def run_profile(metric)
+ klass = profile_options[:benchmark] ? Benchmarker : Profiler
+ performer = klass.new(self, metric)
- class Performer
- delegate :run_test, :profile_options, :full_test_name, :to => :@harness
+ performer.run
+ puts performer.report
+ performer.record
+ end
- def initialize(harness, metric)
- @harness, @metric = harness, metric
- end
+ class Performer
+ delegate :run_test, :profile_options, :full_test_name, :to => :@harness
- def report
- rate = @total / profile_options[:runs]
- '%20s: %s' % [@metric.name, @metric.format(rate)]
- end
+ def initialize(harness, metric)
+ @harness, @metric = harness, metric
+ end
- protected
- def output_filename
- "#{profile_options[:output]}/#{full_test_name}_#{@metric.name}"
+ def report
+ rate = @total / profile_options[:runs]
+ '%20s: %s' % [@metric.name, @metric.format(rate)]
end
- end
- class Benchmarker < Performer
- def run
- profile_options[:runs].to_i.times { run_test(@metric, :benchmark) }
- @total = @metric.total
+ protected
+ def output_filename
+ "#{profile_options[:output]}/#{full_test_name}_#{@metric.name}"
+ end
end
- def record
- avg = @metric.total / profile_options[:runs].to_i
- now = Time.now.utc.xmlschema
- with_output_file do |file|
- file.puts "#{avg},#{now},#{environment}"
+ class Benchmarker < Performer
+ def run
+ profile_options[:runs].to_i.times { run_test(@metric, :benchmark) }
+ @total = @metric.total
end
- end
- def environment
- unless defined? @env
- app = "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
-
- rails = Rails::VERSION::STRING
- if File.directory?('vendor/rails/.git')
- Dir.chdir('vendor/rails') do
- rails += ".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
- end
+ def record
+ avg = @metric.total / profile_options[:runs].to_i
+ now = Time.now.utc.xmlschema
+ with_output_file do |file|
+ file.puts "#{avg},#{now},#{environment}"
end
-
- ruby = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
- ruby += "-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
-
- @env = [app, rails, ruby, RUBY_PLATFORM] * ','
end
- @env
- end
+ def environment
+ unless defined? @env
+ app = "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
- protected
- HEADER = 'measurement,created_at,app,rails,ruby,platform'
+ rails = Rails::VERSION::STRING
+ if File.directory?('vendor/rails/.git')
+ Dir.chdir('vendor/rails') do
+ rails += ".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
+ end
+ end
- def with_output_file
- fname = output_filename
+ ruby = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
+ ruby += "-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
- if new = !File.exist?(fname)
- FileUtils.mkdir_p(File.dirname(fname))
+ @env = [app, rails, ruby, RUBY_PLATFORM] * ','
end
- File.open(fname, 'ab') do |file|
- file.puts(HEADER) if new
- yield file
- end
+ @env
end
- def output_filename
- "#{super}.csv"
- end
- end
+ protected
+ HEADER = 'measurement,created_at,app,rails,ruby,platform'
- class Profiler < Performer
- def initialize(*args)
- super
- @supported = @metric.measure_mode rescue false
- end
+ def with_output_file
+ fname = output_filename
+
+ if new = !File.exist?(fname)
+ FileUtils.mkdir_p(File.dirname(fname))
+ end
- def run
- return unless @supported
+ File.open(fname, 'ab') do |file|
+ file.puts(HEADER) if new
+ yield file
+ end
+ end
- RubyProf.measure_mode = @metric.measure_mode
- RubyProf.start
- RubyProf.pause
- profile_options[:runs].to_i.times { run_test(@metric, :profile) }
- @data = RubyProf.stop
- @total = @data.threads.values.sum(0) { |method_infos| method_infos.sort.last.total_time }
+ def output_filename
+ "#{super}.csv"
+ end
end
- def report
- if @supported
+ class Profiler < Performer
+ def initialize(*args)
super
- else
- '%20s: unsupported' % @metric.name
+ @supported = @metric.measure_mode rescue false
end
- end
- def record
- return unless @supported
+ def run
+ return unless @supported
- klasses = profile_options[:formats].map { |f| RubyProf.const_get("#{f.to_s.camelize}Printer") }.compact
+ RubyProf.measure_mode = @metric.measure_mode
+ RubyProf.start
+ RubyProf.pause
+ profile_options[:runs].to_i.times { run_test(@metric, :profile) }
+ @data = RubyProf.stop
+ @total = @data.threads.values.sum(0) { |method_infos| method_infos.sort.last.total_time }
+ end
- klasses.each do |klass|
- fname = output_filename(klass)
- FileUtils.mkdir_p(File.dirname(fname))
- File.open(fname, 'wb') do |file|
- klass.new(@data).print(file, profile_options.slice(:min_percent))
+ def report
+ if @supported
+ super
+ else
+ '%20s: unsupported' % @metric.name
end
end
- end
- protected
- def output_filename(printer_class)
- suffix =
- case printer_class.name.demodulize
- when 'FlatPrinter'; 'flat.txt'
- when 'GraphPrinter'; 'graph.txt'
- when 'GraphHtmlPrinter'; 'graph.html'
- when 'CallTreePrinter'; 'tree.txt'
- else printer_class.name.sub(/Printer$/, '').underscore
- end
+ def record
+ return unless @supported
+
+ klasses = profile_options[:formats].map { |f| RubyProf.const_get("#{f.to_s.camelize}Printer") }.compact
- "#{super()}_#{suffix}"
+ klasses.each do |klass|
+ fname = output_filename(klass)
+ FileUtils.mkdir_p(File.dirname(fname))
+ File.open(fname, 'wb') do |file|
+ klass.new(@data).print(file, profile_options.slice(:min_percent))
+ end
+ end
end
- end
- module Metrics
- def self.[](name)
- const_get(name.to_s.camelize)
- rescue NameError
- nil
+ protected
+ def output_filename(printer_class)
+ suffix =
+ case printer_class.name.demodulize
+ when 'FlatPrinter'; 'flat.txt'
+ when 'GraphPrinter'; 'graph.txt'
+ when 'GraphHtmlPrinter'; 'graph.html'
+ when 'CallTreePrinter'; 'tree.txt'
+ else printer_class.name.sub(/Printer$/, '').underscore
+ end
+
+ "#{super()}_#{suffix}"
+ end
end
- class Base
- attr_reader :total
-
- def initialize
- @total = 0
+ module Metrics
+ def self.[](name)
+ const_get(name.to_s.camelize)
+ rescue NameError
+ nil
end
- def name
- @name ||= self.class.name.demodulize.underscore
- end
+ class Base
+ attr_reader :total
- def measure_mode
- self.class::Mode
- end
+ def initialize
+ @total = 0
+ end
- def measure
- 0
- end
+ def name
+ @name ||= self.class.name.demodulize.underscore
+ end
- def benchmark
- with_gc_stats do
- before = measure
- yield
- @total += (measure - before)
+ def measure_mode
+ self.class::Mode
end
- end
- def profile
- RubyProf.resume
- yield
- ensure
- RubyProf.pause
- end
+ def measure
+ 0
+ end
- protected
- if GC.respond_to?(:enable_stats)
- def with_gc_stats
- GC.enable_stats
- yield
- ensure
- GC.disable_stats
- end
- elsif defined?(GC::Profiler)
- def with_gc_stats
- GC.start
- GC.disable
- GC::Profiler.enable
- yield
- ensure
- GC::Profiler.disable
- GC.enable
- end
- else
- def with_gc_stats
+ def benchmark
+ with_gc_stats do
+ before = measure
yield
+ @total += (measure - before)
end
end
- end
- class Time < Base
- def measure
- ::Time.now.to_f
- end
-
- def format(measurement)
- if measurement < 2
- '%d ms' % (measurement * 1000)
- else
- '%.2f sec' % measurement
+ def profile
+ RubyProf.resume
+ yield
+ ensure
+ RubyProf.pause
end
- end
- end
-
- class ProcessTime < Time
- Mode = RubyProf::PROCESS_TIME
-
- def measure
- RubyProf.measure_process_time
- end
- end
-
- class WallTime < Time
- Mode = RubyProf::WALL_TIME
- def measure
- RubyProf.measure_wall_time
+ protected
+ if GC.respond_to?(:enable_stats)
+ def with_gc_stats
+ GC.enable_stats
+ yield
+ ensure
+ GC.disable_stats
+ end
+ elsif defined?(GC::Profiler)
+ def with_gc_stats
+ GC.start
+ GC.disable
+ GC::Profiler.enable
+ yield
+ ensure
+ GC::Profiler.disable
+ GC.enable
+ end
+ else
+ def with_gc_stats
+ yield
+ end
+ end
end
- end
- class CpuTime < Time
- Mode = RubyProf::CPU_TIME if RubyProf.const_defined?(:CPU_TIME)
-
- def initialize(*args)
- # FIXME: yeah my CPU is 2.33 GHz
- RubyProf.cpu_frequency = 2.33e9
- super
- end
+ class Time < Base
+ def measure
+ ::Time.now.to_f
+ end
- def measure
- RubyProf.measure_cpu_time
+ def format(measurement)
+ if measurement < 2
+ '%d ms' % (measurement * 1000)
+ else
+ '%.2f sec' % measurement
+ end
+ end
end
- end
- class Memory < Base
- Mode = RubyProf::MEMORY if RubyProf.const_defined?(:MEMORY)
+ class ProcessTime < Time
+ Mode = RubyProf::PROCESS_TIME
- # ruby-prof wrapper
- if RubyProf.respond_to?(:measure_memory)
def measure
- RubyProf.measure_memory / 1024.0
+ RubyProf.measure_process_time
end
+ end
- # Ruby 1.8 + railsbench patch
- elsif GC.respond_to?(:allocated_size)
- def measure
- GC.allocated_size / 1024.0
- end
+ class WallTime < Time
+ Mode = RubyProf::WALL_TIME
- # Ruby 1.8 + lloyd patch
- elsif GC.respond_to?(:heap_info)
def measure
- GC.heap_info['heap_current_memory'] / 1024.0
+ RubyProf.measure_wall_time
end
+ end
- # Ruby 1.9 with total_malloc_allocated_size patch
- elsif GC.respond_to?(:malloc_total_allocated_size)
- def measure
- GC.total_malloc_allocated_size / 1024.0
- end
+ class CpuTime < Time
+ Mode = RubyProf::CPU_TIME if RubyProf.const_defined?(:CPU_TIME)
- # Ruby 1.9 unpatched
- elsif GC.respond_to?(:malloc_allocated_size)
- def measure
- GC.malloc_allocated_size / 1024.0
+ def initialize(*args)
+ # FIXME: yeah my CPU is 2.33 GHz
+ RubyProf.cpu_frequency = 2.33e9
+ super
end
- # Ruby 1.9 + GC profiler patch
- elsif defined?(GC::Profiler)
def measure
- GC.enable
- GC.start
- kb = GC::Profiler.data.last[:HEAP_USE_SIZE] / 1024.0
- GC.disable
- kb
+ RubyProf.measure_cpu_time
end
end
- def format(measurement)
- '%.2f KB' % measurement
- end
- end
+ class Memory < Base
+ Mode = RubyProf::MEMORY if RubyProf.const_defined?(:MEMORY)
- class Objects < Base
- Mode = RubyProf::ALLOCATIONS if RubyProf.const_defined?(:ALLOCATIONS)
+ # ruby-prof wrapper
+ if RubyProf.respond_to?(:measure_memory)
+ def measure
+ RubyProf.measure_memory / 1024.0
+ end
- if RubyProf.respond_to?(:measure_allocations)
- def measure
- RubyProf.measure_allocations
- end
+ # Ruby 1.8 + railsbench patch
+ elsif GC.respond_to?(:allocated_size)
+ def measure
+ GC.allocated_size / 1024.0
+ end
- # Ruby 1.8 + railsbench patch
- elsif ObjectSpace.respond_to?(:allocated_objects)
- def measure
- ObjectSpace.allocated_objects
+ # Ruby 1.8 + lloyd patch
+ elsif GC.respond_to?(:heap_info)
+ def measure
+ GC.heap_info['heap_current_memory'] / 1024.0
+ end
+
+ # Ruby 1.9 with total_malloc_allocated_size patch
+ elsif GC.respond_to?(:malloc_total_allocated_size)
+ def measure
+ GC.total_malloc_allocated_size / 1024.0
+ end
+
+ # Ruby 1.9 unpatched
+ elsif GC.respond_to?(:malloc_allocated_size)
+ def measure
+ GC.malloc_allocated_size / 1024.0
+ end
+
+ # Ruby 1.9 + GC profiler patch
+ elsif defined?(GC::Profiler)
+ def measure
+ GC.enable
+ GC.start
+ kb = GC::Profiler.data.last[:HEAP_USE_SIZE] / 1024.0
+ GC.disable
+ kb
+ end
end
- # Ruby 1.9 + GC profiler patch
- elsif defined?(GC::Profiler)
- def measure
- GC.enable
- GC.start
- last = GC::Profiler.data.last
- count = last[:HEAP_LIVE_OBJECTS] + last[:HEAP_FREE_OBJECTS]
- GC.disable
- count
+ def format(measurement)
+ '%.2f KB' % measurement
end
end
- def format(measurement)
- measurement.to_i.to_s
- end
- end
+ class Objects < Base
+ Mode = RubyProf::ALLOCATIONS if RubyProf.const_defined?(:ALLOCATIONS)
- class GcRuns < Base
- Mode = RubyProf::GC_RUNS if RubyProf.const_defined?(:GC_RUNS)
+ if RubyProf.respond_to?(:measure_allocations)
+ def measure
+ RubyProf.measure_allocations
+ end
- if RubyProf.respond_to?(:measure_gc_runs)
- def measure
- RubyProf.measure_gc_runs
- end
- elsif GC.respond_to?(:collections)
- def measure
- GC.collections
- end
- elsif GC.respond_to?(:heap_info)
- def measure
- GC.heap_info['num_gc_passes']
+ # Ruby 1.8 + railsbench patch
+ elsif ObjectSpace.respond_to?(:allocated_objects)
+ def measure
+ ObjectSpace.allocated_objects
+ end
+
+ # Ruby 1.9 + GC profiler patch
+ elsif defined?(GC::Profiler)
+ def measure
+ GC.enable
+ GC.start
+ last = GC::Profiler.data.last
+ count = last[:HEAP_LIVE_OBJECTS] + last[:HEAP_FREE_OBJECTS]
+ GC.disable
+ count
+ end
end
- end
- def format(measurement)
- measurement.to_i.to_s
+ def format(measurement)
+ measurement.to_i.to_s
+ end
end
- end
- class GcTime < Base
- Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME)
+ class GcRuns < Base
+ Mode = RubyProf::GC_RUNS if RubyProf.const_defined?(:GC_RUNS)
- if RubyProf.respond_to?(:measure_gc_time)
- def measure
- RubyProf.measure_gc_time
+ if RubyProf.respond_to?(:measure_gc_runs)
+ def measure
+ RubyProf.measure_gc_runs
+ end
+ elsif GC.respond_to?(:collections)
+ def measure
+ GC.collections
+ end
+ elsif GC.respond_to?(:heap_info)
+ def measure
+ GC.heap_info['num_gc_passes']
+ end
end
- elsif GC.respond_to?(:time)
- def measure
- GC.time
+
+ def format(measurement)
+ measurement.to_i.to_s
end
end
- def format(measurement)
- '%d ms' % (measurement / 1000)
+ class GcTime < Base
+ Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME)
+
+ if RubyProf.respond_to?(:measure_gc_time)
+ def measure
+ RubyProf.measure_gc_time
+ end
+ elsif GC.respond_to?(:time)
+ def measure
+ GC.time
+ end
+ end
+
+ def format(measurement)
+ '%d ms' % (measurement / 1000)
+ end
end
end
end
end
end
-end
+rescue LoadError
+end \ No newline at end of file
diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb
index 0e998d2dbe..6ce9495cee 100644
--- a/activesupport/lib/active_support/testing/setup_and_teardown.rb
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -1,16 +1,26 @@
module ActiveSupport
module Testing
module SetupAndTeardown
- def self.included(base)
- base.class_eval do
- include ActiveSupport::DeprecatedCallbacks
- define_callbacks :setup, :teardown
+ extend ActiveSupport::Concern
- if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
- include ForMiniTest
- else
- include ForClassicTestUnit
- end
+ included do
+ include ActiveSupport::Callbacks
+ define_callbacks :setup, :teardown
+
+ if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
+ include ForMiniTest
+ else
+ include ForClassicTestUnit
+ end
+ end
+
+ module ClassMethods
+ def setup(*args, &block)
+ set_callback(:setup, :before, *args, &block)
+ end
+
+ def teardown(*args, &block)
+ set_callback(:teardown, :after, *args, &block)
end
end
@@ -18,13 +28,14 @@ module ActiveSupport
def run(runner)
result = '.'
begin
- run_callbacks :setup
- result = super
+ _run_setup_callbacks do
+ result = super
+ end
rescue Exception => e
result = runner.puke(self.class, method_name, e)
ensure
begin
- run_callbacks :teardown, :enumerator => :reverse_each
+ _run_teardown_callbacks
rescue Exception => e
result = runner.puke(self.class, method_name, e)
end
@@ -42,23 +53,17 @@ module ActiveSupport
def run(result)
return if @method_name.to_s == "default_test"
- if using_mocha = respond_to?(:mocha_verify)
- assertion_counter_klass = if defined?(Mocha::TestCaseAdapter::AssertionCounter)
- Mocha::TestCaseAdapter::AssertionCounter
- else
- Mocha::Integration::TestUnit::AssertionCounter
- end
- assertion_counter = assertion_counter_klass.new(result)
- end
-
+ mocha_counter = retrieve_mocha_counter(result)
yield(Test::Unit::TestCase::STARTED, name)
@_result = result
+
begin
begin
- run_callbacks :setup
- setup
- __send__(@method_name)
- mocha_verify(assertion_counter) if using_mocha
+ _run_setup_callbacks do
+ setup
+ __send__(@method_name)
+ mocha_verify(mocha_counter) if mocha_counter
+ end
rescue Mocha::ExpectationError => e
add_failure(e.message, e.backtrace)
rescue Test::Unit::AssertionFailedError => e
@@ -69,7 +74,7 @@ module ActiveSupport
ensure
begin
teardown
- run_callbacks :teardown, :enumerator => :reverse_each
+ _run_teardown_callbacks
rescue Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue Exception => e
@@ -78,12 +83,26 @@ module ActiveSupport
end
end
ensure
- mocha_teardown if using_mocha
+ mocha_teardown if mocha_counter
end
+
result.add_run
yield(Test::Unit::TestCase::FINISHED, name)
end
+
+ protected
+
+ def retrieve_mocha_counter(result) #:nodoc:
+ if using_mocha = respond_to?(:mocha_verify)
+ if defined?(Mocha::TestCaseAdapter::AssertionCounter)
+ Mocha::TestCaseAdapter::AssertionCounter.new(result)
+ else
+ Mocha::Integration::TestUnit::AssertionCounter.new(result)
+ end
+ end
+ end
end
+
end
end
end
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 8304f6c434..6b554e7158 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -1,4 +1,5 @@
require "active_support/values/time_zone"
+require 'active_support/core_ext/object/acts_like'
module ActiveSupport
# A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are
diff --git a/activesupport/lib/active_support/vendor.rb b/activesupport/lib/active_support/vendor.rb
index eb5080888c..1e46491d83 100644
--- a/activesupport/lib/active_support/vendor.rb
+++ b/activesupport/lib/active_support/vendor.rb
@@ -4,7 +4,7 @@ def ActiveSupport.requirable?(file)
$LOAD_PATH.any? { |p| Dir.glob("#{p}/#{file}.*").any? }
end
-[%w(builder 2.1.2), %w(i18n 0.1.3), %w(memcache-client 1.7.5), %w(tzinfo 0.3.15)].each do |lib, version|
+[%w(builder 2.1.2), %w(memcache-client 1.7.5), %w(tzinfo 0.3.15)].each do |lib, version|
# If the lib is not already requirable
unless ActiveSupport.requirable? lib
# Try to activate a gem ~> satisfying the requested version first.
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE b/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE
deleted file mode 100755
index ed8e9ee66d..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/MIT-LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2008 The Ruby I18n team
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile b/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile
deleted file mode 100644
index a07fc8426d..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/README.textile
+++ /dev/null
@@ -1,20 +0,0 @@
-h1. Ruby I18n gem
-
-I18n and localization solution for Ruby.
-
-For information please refer to http://rails-i18n.org
-
-h2. Authors
-
-* "Matt Aimonetti":http://railsontherun.com
-* "Sven Fuchs":http://www.artweb-design.de
-* "Joshua Harvey":http://www.workingwithrails.com/person/759-joshua-harvey
-* "Saimon Moore":http://saimonmoore.net
-* "Stephan Soller":http://www.arkanis-development.de
-
-h2. License
-
-MIT License. See the included MIT-LICENCE file.
-
-
-
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile b/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile
deleted file mode 100644
index 2164e13e69..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/Rakefile
+++ /dev/null
@@ -1,5 +0,0 @@
-task :default => [:test]
-
-task :test do
- ruby "test/all.rb"
-end
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec b/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec
deleted file mode 100644
index f102689a6f..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/i18n.gemspec
+++ /dev/null
@@ -1,27 +0,0 @@
-Gem::Specification.new do |s|
- s.name = "i18n"
- s.version = "0.1.3"
- s.date = "2009-01-09"
- s.summary = "Internationalization support for Ruby"
- s.email = "rails-i18n@googlegroups.com"
- s.homepage = "http://rails-i18n.org"
- s.description = "Add Internationalization support to your Ruby application."
- s.has_rdoc = false
- s.authors = ['Sven Fuchs', 'Joshua Harvey', 'Matt Aimonetti', 'Stephan Soller', 'Saimon Moore']
- s.files = [
- 'i18n.gemspec',
- 'lib/i18n/backend/simple.rb',
- 'lib/i18n/exceptions.rb',
- 'lib/i18n.rb',
- 'MIT-LICENSE',
- 'README.textile'
- ]
- s.test_files = [
- 'test/all.rb',
- 'test/i18n_exceptions_test.rb',
- 'test/i18n_test.rb',
- 'test/locale/en.rb',
- 'test/locale/en.yml',
- 'test/simple_backend_test.rb'
- ]
-end
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb
deleted file mode 100755
index 1b49debc05..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb
+++ /dev/null
@@ -1,204 +0,0 @@
-#--
-# Authors:: Matt Aimonetti (http://railsontherun.com/),
-# Sven Fuchs (http://www.artweb-design.de),
-# Joshua Harvey (http://www.workingwithrails.com/person/759-joshua-harvey),
-# Saimon Moore (http://saimonmoore.net),
-# Stephan Soller (http://www.arkanis-development.de/)
-# Copyright:: Copyright (c) 2008 The Ruby i18n Team
-# License:: MIT
-#++
-
-module I18n
- autoload :ArgumentError, 'i18n/exceptions'
- module Backend
- autoload :Simple, 'i18n/backend/simple'
- end
-
- @@backend = nil
- @@load_path = nil
- @@default_locale = :'en'
- @@exception_handler = :default_exception_handler
-
- class << self
- # Returns the current backend. Defaults to +Backend::Simple+.
- def backend
- @@backend ||= Backend::Simple.new
- end
-
- # Sets the current backend. Used to set a custom backend.
- def backend=(backend)
- @@backend = backend
- end
-
- # Returns the current default locale. Defaults to :'en'
- def default_locale
- @@default_locale
- end
-
- # Sets the current default locale. Used to set a custom default locale.
- def default_locale=(locale)
- @@default_locale = locale
- end
-
- # Returns the current locale. Defaults to I18n.default_locale.
- def locale
- Thread.current[:locale] ||= default_locale
- end
-
- # Sets the current locale pseudo-globally, i.e. in the Thread.current hash.
- def locale=(locale)
- Thread.current[:locale] = locale
- end
-
- # Returns an array of locales for which translations are available
- def available_locales
- backend.available_locales
- end
-
- # Sets the exception handler.
- def exception_handler=(exception_handler)
- @@exception_handler = exception_handler
- end
-
- # Allow clients to register paths providing translation data sources. The
- # backend defines acceptable sources.
- #
- # E.g. the provided SimpleBackend accepts a list of paths to translation
- # files which are either named *.rb and contain plain Ruby Hashes or are
- # named *.yml and contain YAML data. So for the SimpleBackend clients may
- # register translation files like this:
- # I18n.load_path << 'path/to/locale/en.yml'
- def load_path
- @@load_path ||= []
- end
-
- # Sets the load path instance. Custom implementations are expected to
- # behave like a Ruby Array.
- def load_path=(load_path)
- @@load_path = load_path
- end
-
- # Tells the backend to reload translations. Used in situations like the
- # Rails development environment. Backends can implement whatever strategy
- # is useful.
- def reload!
- backend.reload!
- end
-
- # Translates, pluralizes and interpolates a given key using a given locale,
- # scope, and default, as well as interpolation values.
- #
- # *LOOKUP*
- #
- # Translation data is organized as a nested hash using the upper-level keys
- # as namespaces. <em>E.g.</em>, ActionView ships with the translation:
- # <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
- #
- # Translations can be looked up at any level of this hash using the key argument
- # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
- # returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
- #
- # Key can be either a single key or a dot-separated key (both Strings and Symbols
- # work). <em>E.g.</em>, the short format can be looked up using both:
- # I18n.t 'date.formats.short'
- # I18n.t :'date.formats.short'
- #
- # Scope can be either a single key, a dot-separated key or an array of keys
- # or dot-separated keys. Keys and scopes can be combined freely. So these
- # examples will all look up the same short date format:
- # I18n.t 'date.formats.short'
- # I18n.t 'formats.short', :scope => 'date'
- # I18n.t 'short', :scope => 'date.formats'
- # I18n.t 'short', :scope => %w(date formats)
- #
- # *INTERPOLATION*
- #
- # Translations can contain interpolation variables which will be replaced by
- # values passed to #translate as part of the options hash, with the keys matching
- # the interpolation variable names.
- #
- # <em>E.g.</em>, with a translation <tt>:foo => "foo {{bar}}"</tt> the option
- # value for the key +bar+ will be interpolated into the translation:
- # I18n.t :foo, :bar => 'baz' # => 'foo baz'
- #
- # *PLURALIZATION*
- #
- # Translation data can contain pluralized translations. Pluralized translations
- # are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
- #
- # Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
- # pluralization rules. Other algorithms can be supported by custom backends.
- #
- # This returns the singular version of a pluralized translation:
- # I18n.t :foo, :count => 1 # => 'Foo'
- #
- # These both return the plural version of a pluralized translation:
- # I18n.t :foo, :count => 0 # => 'Foos'
- # I18n.t :foo, :count => 2 # => 'Foos'
- #
- # The <tt>:count</tt> option can be used both for pluralization and interpolation.
- # <em>E.g.</em>, with the translation
- # <tt>:foo => ['{{count}} foo', '{{count}} foos']</tt>, count will
- # be interpolated to the pluralized translation:
- # I18n.t :foo, :count => 1 # => '1 foo'
- #
- # *DEFAULTS*
- #
- # This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
- # I18n.t :foo, :default => 'default'
- #
- # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
- # translation for <tt>:foo</tt> was found:
- # I18n.t :foo, :default => :bar
- #
- # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
- # or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
- # I18n.t :foo, :default => [:bar, 'default']
- #
- # <b>BULK LOOKUP</b>
- #
- # This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
- # I18n.t [:foo, :bar]
- #
- # Can be used with dot-separated nested keys:
- # I18n.t [:'baz.foo', :'baz.bar']
- #
- # Which is the same as using a scope option:
- # I18n.t [:foo, :bar], :scope => :baz
- def translate(key, options = {})
- locale = options.delete(:locale) || I18n.locale
- backend.translate(locale, key, options)
- rescue I18n::ArgumentError => e
- raise e if options[:raise]
- send(@@exception_handler, e, locale, key, options)
- end
- alias :t :translate
-
- # Localizes certain objects, such as dates and numbers to local formatting.
- def localize(object, options = {})
- locale = options[:locale] || I18n.locale
- format = options[:format] || :default
- backend.localize(locale, object, format)
- end
- alias :l :localize
-
- protected
- # Handles exceptions raised in the backend. All exceptions except for
- # MissingTranslationData exceptions are re-raised. When a MissingTranslationData
- # was caught and the option :raise is not set the handler returns an error
- # message string containing the key/scope.
- def default_exception_handler(exception, locale, key, options)
- return exception.message if MissingTranslationData === exception
- raise exception
- end
-
- # Merges the given locale, key and scope into a single array of keys.
- # Splits keys that contain dots into multiple keys. Makes sure all
- # keys are Symbols.
- def normalize_translation_keys(locale, key, scope)
- keys = [locale] + Array(scope) + [key]
- keys = keys.map { |k| k.to_s.split(/\./) }
- keys.flatten.map { |k| k.to_sym }
- end
- end
-end
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb
deleted file mode 100644
index c32cc76f34..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/backend/simple.rb
+++ /dev/null
@@ -1,215 +0,0 @@
-require 'i18n/exceptions'
-
-module I18n
- module Backend
- class Simple
- INTERPOLATION_RESERVED_KEYS = %w(scope default)
- MATCH = /(\\\\)?\{\{([^\}]+)\}\}/
-
- # Accepts a list of paths to translation files. Loads translations from
- # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
- # for details.
- def load_translations(*filenames)
- filenames.each { |filename| load_file(filename) }
- end
-
- # Stores translations for the given locale in memory.
- # This uses a deep merge for the translations hash, so existing
- # translations will be overwritten by new ones only at the deepest
- # level of the hash.
- def store_translations(locale, data)
- merge_translations(locale, data)
- end
-
- def translate(locale, key, options = {})
- raise InvalidLocale.new(locale) if locale.nil?
- return key.map { |k| translate(locale, k, options) } if key.is_a? Array
-
- reserved = :scope, :default
- count, scope, default = options.values_at(:count, *reserved)
- options.delete(:default)
- values = options.reject { |name, value| reserved.include?(name) }
-
- entry = lookup(locale, key, scope)
- if entry.nil?
- entry = default(locale, default, options)
- if entry.nil?
- raise(I18n::MissingTranslationData.new(locale, key, options))
- end
- end
- entry = pluralize(locale, entry, count)
- entry = interpolate(locale, entry, values)
- entry
- end
-
- # Acts the same as +strftime+, but returns a localized version of the
- # formatted date string. Takes a key from the date/time formats
- # translations as a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
- def localize(locale, object, format = :default)
- raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
-
- type = object.respond_to?(:sec) ? 'time' : 'date'
- # TODO only translate these if format is a String?
- formats = translate(locale, :"#{type}.formats")
- format = formats[format.to_sym] if formats && formats[format.to_sym]
- # TODO raise exception unless format found?
- format = format.to_s.dup
-
- # TODO only translate these if the format string is actually present
- # TODO check which format strings are present, then bulk translate then, then replace them
- format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday])
- format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday])
- format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon])
- format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon])
- format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour
- object.strftime(format)
- end
-
- def initialized?
- @initialized ||= false
- end
-
- # Returns an array of locales for which translations are available
- def available_locales
- init_translations unless initialized?
- translations.keys
- end
-
- def reload!
- @initialized = false
- @translations = nil
- end
-
- protected
- def init_translations
- load_translations(*I18n.load_path.flatten)
- @initialized = true
- end
-
- def translations
- @translations ||= {}
- end
-
- # Looks up a translation from the translations hash. Returns nil if
- # eiher key is nil, or locale, scope or key do not exist as a key in the
- # nested translations hash. Splits keys or scopes containing dots
- # into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
- # <tt>%w(currency format)</tt>.
- def lookup(locale, key, scope = [])
- return unless key
- init_translations unless initialized?
- keys = I18n.send(:normalize_translation_keys, locale, key, scope)
- keys.inject(translations) do |result, k|
- if (x = result[k.to_sym]).nil?
- return nil
- else
- x
- end
- end
- end
-
- # Evaluates a default translation.
- # If the given default is a String it is used literally. If it is a Symbol
- # it will be translated with the given options. If it is an Array the first
- # translation yielded will be returned.
- #
- # <em>I.e.</em>, <tt>default(locale, [:foo, 'default'])</tt> will return +default+ if
- # <tt>translate(locale, :foo)</tt> does not yield a result.
- def default(locale, default, options = {})
- case default
- when String then default
- when Symbol then translate locale, default, options
- when Array then default.each do |obj|
- result = default(locale, obj, options.dup) and return result
- end and nil
- end
- rescue MissingTranslationData
- nil
- end
-
- # Picks a translation from an array according to English pluralization
- # rules. It will pick the first translation if count is not equal to 1
- # and the second translation if it is equal to 1. Other backends can
- # implement more flexible or complex pluralization rules.
- def pluralize(locale, entry, count)
- return entry unless entry.is_a?(Hash) and count
- # raise InvalidPluralizationData.new(entry, count) unless entry.is_a?(Hash)
- key = :zero if count == 0 && entry.has_key?(:zero)
- key ||= count == 1 ? :one : :other
- raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
- entry[key]
- end
-
- # Interpolates values into a given string.
- #
- # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X'
- # # => "file test.txt opened by {{user}}"
- #
- # Note that you have to double escape the <tt>\\</tt> when you want to escape
- # the <tt>{{...}}</tt> key in a string (once for the string and once for the
- # interpolation).
- def interpolate(locale, string, values = {})
- return string unless string.is_a?(String)
-
- string.gsub(MATCH) do
- escaped, pattern, key = $1, $2, $2.to_sym
-
- if escaped
- pattern
- elsif INTERPOLATION_RESERVED_KEYS.include?(pattern)
- raise ReservedInterpolationKey.new(pattern, string)
- elsif !values.include?(key)
- raise MissingInterpolationArgument.new(pattern, string)
- else
- values[key].to_s
- end
- end
- end
-
- # Loads a single translations file by delegating to #load_rb or
- # #load_yml depending on the file extension and directly merges the
- # data to the existing translations. Raises I18n::UnknownFileType
- # for all other file extensions.
- def load_file(filename)
- type = File.extname(filename).tr('.', '').downcase
- raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}")
- data = send :"load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash
- data.each { |locale, d| merge_translations(locale, d) }
- end
-
- # Loads a plain Ruby translations file. eval'ing the file must yield
- # a Hash containing translation data with locales as toplevel keys.
- def load_rb(filename)
- eval(IO.read(filename), binding, filename)
- end
-
- # Loads a YAML translations file. The data must have locales as
- # toplevel keys.
- def load_yml(filename)
- require 'yaml' unless defined? :YAML
- YAML::load(IO.read(filename))
- end
-
- # Deep merges the given translations hash with the existing translations
- # for the given locale
- def merge_translations(locale, data)
- locale = locale.to_sym
- translations[locale] ||= {}
- data = deep_symbolize_keys(data)
-
- # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
- merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
- translations[locale].merge!(data, &merger)
- end
-
- # Return a new hash with all keys and nested keys converted to symbols.
- def deep_symbolize_keys(hash)
- hash.inject({}) { |result, (key, value)|
- value = deep_symbolize_keys(value) if value.is_a? Hash
- result[(key.to_sym rescue key) || key] = value
- result
- }
- end
- end
- end
-end
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb
deleted file mode 100644
index 6897055d6d..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n/exceptions.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-module I18n
- class ArgumentError < ::ArgumentError; end
-
- class InvalidLocale < ArgumentError
- attr_reader :locale
- def initialize(locale)
- @locale = locale
- super "#{locale.inspect} is not a valid locale"
- end
- end
-
- class MissingTranslationData < ArgumentError
- attr_reader :locale, :key, :options
- def initialize(locale, key, options)
- @key, @locale, @options = key, locale, options
- keys = I18n.send(:normalize_translation_keys, locale, key, options[:scope])
- keys << 'no key' if keys.size < 2
- super "translation missing: #{keys.join(', ')}"
- end
- end
-
- class InvalidPluralizationData < ArgumentError
- attr_reader :entry, :count
- def initialize(entry, count)
- @entry, @count = entry, count
- super "translation data #{entry.inspect} can not be used with :count => #{count}"
- end
- end
-
- class MissingInterpolationArgument < ArgumentError
- attr_reader :key, :string
- def initialize(key, string)
- @key, @string = key, string
- super "interpolation argument #{key} missing in #{string.inspect}"
- end
- end
-
- class ReservedInterpolationKey < ArgumentError
- attr_reader :key, :string
- def initialize(key, string)
- @key, @string = key, string
- super "reserved key #{key.inspect} used in #{string.inspect}"
- end
- end
-
- class UnknownFileType < ArgumentError
- attr_reader :type, :filename
- def initialize(type, filename)
- @type, @filename = type, filename
- super "can not load translations from #{filename}, the file type #{type} is not known"
- end
- end
-end
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb
deleted file mode 100644
index 353712da49..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/all.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-dir = File.dirname(__FILE__)
-require dir + '/i18n_test.rb'
-require dir + '/simple_backend_test.rb'
-require dir + '/i18n_exceptions_test.rb'
-# *require* dir + '/custom_backend_test.rb' \ No newline at end of file
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb
deleted file mode 100644
index 4e78e71b34..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_exceptions_test.rb
+++ /dev/null
@@ -1,99 +0,0 @@
-$:.unshift "lib"
-
-require 'rubygems'
-require 'test/unit'
-require 'i18n'
-require 'active_support'
-
-class I18nExceptionsTest < Test::Unit::TestCase
- def test_invalid_locale_stores_locale
- force_invalid_locale
- rescue I18n::ArgumentError => e
- assert_nil e.locale
- end
-
- def test_invalid_locale_message
- force_invalid_locale
- rescue I18n::ArgumentError => e
- assert_equal 'nil is not a valid locale', e.message
- end
-
- def test_missing_translation_data_stores_locale_key_and_options
- force_missing_translation_data
- rescue I18n::ArgumentError => e
- options = {:scope => :bar}
- assert_equal 'de', e.locale
- assert_equal :foo, e.key
- assert_equal options, e.options
- end
-
- def test_missing_translation_data_message
- force_missing_translation_data
- rescue I18n::ArgumentError => e
- assert_equal 'translation missing: de, bar, foo', e.message
- end
-
- def test_invalid_pluralization_data_stores_entry_and_count
- force_invalid_pluralization_data
- rescue I18n::ArgumentError => e
- assert_equal [:bar], e.entry
- assert_equal 1, e.count
- end
-
- def test_invalid_pluralization_data_message
- force_invalid_pluralization_data
- rescue I18n::ArgumentError => e
- assert_equal 'translation data [:bar] can not be used with :count => 1', e.message
- end
-
- def test_missing_interpolation_argument_stores_key_and_string
- force_missing_interpolation_argument
- rescue I18n::ArgumentError => e
- assert_equal 'bar', e.key
- assert_equal "{{bar}}", e.string
- end
-
- def test_missing_interpolation_argument_message
- force_missing_interpolation_argument
- rescue I18n::ArgumentError => e
- assert_equal 'interpolation argument bar missing in "{{bar}}"', e.message
- end
-
- def test_reserved_interpolation_key_stores_key_and_string
- force_reserved_interpolation_key
- rescue I18n::ArgumentError => e
- assert_equal 'scope', e.key
- assert_equal "{{scope}}", e.string
- end
-
- def test_reserved_interpolation_key_message
- force_reserved_interpolation_key
- rescue I18n::ArgumentError => e
- assert_equal 'reserved key "scope" used in "{{scope}}"', e.message
- end
-
- private
- def force_invalid_locale
- I18n.backend.translate nil, :foo
- end
-
- def force_missing_translation_data
- I18n.backend.store_translations 'de', :bar => nil
- I18n.backend.translate 'de', :foo, :scope => :bar
- end
-
- def force_invalid_pluralization_data
- I18n.backend.store_translations 'de', :foo => [:bar]
- I18n.backend.translate 'de', :foo, :count => 1
- end
-
- def force_missing_interpolation_argument
- I18n.backend.store_translations 'de', :foo => "{{bar}}"
- I18n.backend.translate 'de', :foo, :baz => 'baz'
- end
-
- def force_reserved_interpolation_key
- I18n.backend.store_translations 'de', :foo => "{{scope}}"
- I18n.backend.translate 'de', :foo, :baz => 'baz'
- end
-end \ No newline at end of file
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb
deleted file mode 100644
index 2835ec4eab..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/i18n_test.rb
+++ /dev/null
@@ -1,124 +0,0 @@
-$:.unshift "lib"
-
-require 'rubygems'
-require 'test/unit'
-require 'i18n'
-require 'active_support'
-
-class I18nTest < Test::Unit::TestCase
- def setup
- I18n.backend.store_translations :'en', {
- :currency => {
- :format => {
- :separator => '.',
- :delimiter => ',',
- }
- }
- }
- end
-
- def test_uses_simple_backend_set_by_default
- assert I18n.backend.is_a?(I18n::Backend::Simple)
- end
-
- def test_can_set_backend
- assert_nothing_raised{ I18n.backend = self }
- assert_equal self, I18n.backend
- I18n.backend = I18n::Backend::Simple.new
- end
-
- def test_uses_en_us_as_default_locale_by_default
- assert_equal 'en', I18n.default_locale
- end
-
- def test_can_set_default_locale
- assert_nothing_raised{ I18n.default_locale = 'de' }
- assert_equal 'de', I18n.default_locale
- I18n.default_locale = 'en'
- end
-
- def test_uses_default_locale_as_locale_by_default
- assert_equal I18n.default_locale, I18n.locale
- end
-
- def test_can_set_locale_to_thread_current
- assert_nothing_raised{ I18n.locale = 'de' }
- assert_equal 'de', I18n.locale
- assert_equal 'de', Thread.current[:locale]
- I18n.locale = 'en'
- end
-
- def test_can_set_exception_handler
- assert_nothing_raised{ I18n.exception_handler = :custom_exception_handler }
- I18n.exception_handler = :default_exception_handler # revert it
- end
-
- def test_uses_custom_exception_handler
- I18n.exception_handler = :custom_exception_handler
- I18n.expects(:custom_exception_handler)
- I18n.translate :bogus
- I18n.exception_handler = :default_exception_handler # revert it
- end
-
- def test_delegates_translate_to_backend
- I18n.backend.expects(:translate).with 'de', :foo, {}
- I18n.translate :foo, :locale => 'de'
- end
-
- def test_delegates_localize_to_backend
- I18n.backend.expects(:localize).with 'de', :whatever, :default
- I18n.localize :whatever, :locale => 'de'
- end
-
- def test_translate_given_no_locale_uses_i18n_locale
- I18n.backend.expects(:translate).with 'en', :foo, {}
- I18n.translate :foo
- end
-
- def test_translate_on_nested_symbol_keys_works
- assert_equal ".", I18n.t(:'currency.format.separator')
- end
-
- def test_translate_with_nested_string_keys_works
- assert_equal ".", I18n.t('currency.format.separator')
- end
-
- def test_translate_with_array_as_scope_works
- assert_equal ".", I18n.t(:separator, :scope => ['currency.format'])
- end
-
- def test_translate_with_array_containing_dot_separated_strings_as_scope_works
- assert_equal ".", I18n.t(:separator, :scope => ['currency.format'])
- end
-
- def test_translate_with_key_array_and_dot_separated_scope_works
- assert_equal [".", ","], I18n.t(%w(separator delimiter), :scope => 'currency.format')
- end
-
- def test_translate_with_dot_separated_key_array_and_scope_works
- assert_equal [".", ","], I18n.t(%w(format.separator format.delimiter), :scope => 'currency')
- end
-
- def test_translate_with_options_using_scope_works
- I18n.backend.expects(:translate).with('de', :precision, :scope => :"currency.format")
- I18n.with_options :locale => 'de', :scope => :'currency.format' do |locale|
- locale.t :precision
- end
- end
-
- # def test_translate_given_no_args_raises_missing_translation_data
- # assert_equal "translation missing: en, no key", I18n.t
- # end
-
- def test_translate_given_a_bogus_key_raises_missing_translation_data
- assert_equal "translation missing: en, bogus", I18n.t(:bogus)
- end
-
- def test_localize_nil_raises_argument_error
- assert_raise(I18n::ArgumentError) { I18n.l nil }
- end
-
- def test_localize_object_raises_argument_error
- assert_raise(I18n::ArgumentError) { I18n.l Object.new }
- end
-end
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb
deleted file mode 100644
index 6044ce10d9..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.rb
+++ /dev/null
@@ -1 +0,0 @@
-{:'en-Ruby' => {:foo => {:bar => "baz"}}} \ No newline at end of file
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml
deleted file mode 100644
index 0b298c9c0e..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/locale/en.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-en-Yaml:
- foo:
- bar: baz \ No newline at end of file
diff --git a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb b/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb
deleted file mode 100644
index a1696c77f6..0000000000
--- a/activesupport/lib/active_support/vendor/i18n-0.1.3/test/simple_backend_test.rb
+++ /dev/null
@@ -1,567 +0,0 @@
-# encoding: utf-8
-$:.unshift "lib"
-
-require 'rubygems'
-require 'test/unit'
-require 'i18n'
-require 'time'
-require 'yaml'
-
-module I18nSimpleBackendTestSetup
- def setup_backend
- # backend_reset_translations!
- @backend = I18n::Backend::Simple.new
- @backend.store_translations 'en', :foo => {:bar => 'bar', :baz => 'baz'}
- @locale_dir = File.dirname(__FILE__) + '/locale'
- end
- alias :setup :setup_backend
-
- # def backend_reset_translations!
- # I18n::Backend::Simple::ClassMethods.send :class_variable_set, :@@translations, {}
- # end
-
- def backend_get_translations
- # I18n::Backend::Simple::ClassMethods.send :class_variable_get, :@@translations
- @backend.instance_variable_get :@translations
- end
-
- def add_datetime_translations
- @backend.store_translations :'de', {
- :date => {
- :formats => {
- :default => "%d.%m.%Y",
- :short => "%d. %b",
- :long => "%d. %B %Y",
- },
- :day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag),
- :abbr_day_names => %w(So Mo Di Mi Do Fr Sa),
- :month_names => %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember).unshift(nil),
- :abbr_month_names => %w(Jan Feb Mar Apr Mai Jun Jul Aug Sep Okt Nov Dez).unshift(nil),
- :order => [:day, :month, :year]
- },
- :time => {
- :formats => {
- :default => "%a, %d. %b %Y %H:%M:%S %z",
- :short => "%d. %b %H:%M",
- :long => "%d. %B %Y %H:%M",
- },
- :am => 'am',
- :pm => 'pm'
- },
- :datetime => {
- :distance_in_words => {
- :half_a_minute => 'half a minute',
- :less_than_x_seconds => {
- :one => 'less than 1 second',
- :other => 'less than {{count}} seconds'
- },
- :x_seconds => {
- :one => '1 second',
- :other => '{{count}} seconds'
- },
- :less_than_x_minutes => {
- :one => 'less than a minute',
- :other => 'less than {{count}} minutes'
- },
- :x_minutes => {
- :one => '1 minute',
- :other => '{{count}} minutes'
- },
- :about_x_hours => {
- :one => 'about 1 hour',
- :other => 'about {{count}} hours'
- },
- :x_days => {
- :one => '1 day',
- :other => '{{count}} days'
- },
- :about_x_months => {
- :one => 'about 1 month',
- :other => 'about {{count}} months'
- },
- :x_months => {
- :one => '1 month',
- :other => '{{count}} months'
- },
- :about_x_years => {
- :one => 'about 1 year',
- :other => 'about {{count}} year'
- },
- :over_x_years => {
- :one => 'over 1 year',
- :other => 'over {{count}} years'
- }
- }
- }
- }
- end
-end
-
-class I18nSimpleBackendTranslationsTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def test_store_translations_adds_translations # no, really :-)
- @backend.store_translations :'en', :foo => 'bar'
- assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations
- end
-
- def test_store_translations_deep_merges_translations
- @backend.store_translations :'en', :foo => {:bar => 'bar'}
- @backend.store_translations :'en', :foo => {:baz => 'baz'}
- assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations
- end
-
- def test_store_translations_forces_locale_to_sym
- @backend.store_translations 'en', :foo => 'bar'
- assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations
- end
-
- def test_store_translations_converts_keys_to_symbols
- # backend_reset_translations!
- @backend.store_translations 'en', 'foo' => {'bar' => 'bar', 'baz' => 'baz'}
- assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations
- end
-end
-
-class I18nSimpleBackendAvailableLocalesTest < Test::Unit::TestCase
- def test_available_locales
- @backend = I18n::Backend::Simple.new
- @backend.store_translations 'de', :foo => 'bar'
- @backend.store_translations 'en', :foo => 'foo'
-
- assert_equal ['de', 'en'], @backend.available_locales.map{|locale| locale.to_s }.sort
- end
-end
-
-class I18nSimpleBackendTranslateTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def test_translate_calls_lookup_with_locale_given
- @backend.expects(:lookup).with('de', :bar, [:foo]).returns 'bar'
- @backend.translate 'de', :bar, :scope => [:foo]
- end
-
- def test_given_no_keys_it_returns_the_default
- assert_equal 'default', @backend.translate('en', nil, :default => 'default')
- end
-
- def test_translate_given_a_symbol_as_a_default_translates_the_symbol
- assert_equal 'bar', @backend.translate('en', nil, :scope => [:foo], :default => :bar)
- end
-
- def test_translate_given_an_array_as_default_uses_the_first_match
- assert_equal 'bar', @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :bar])
- end
-
- def test_translate_given_an_array_of_inexistent_keys_it_raises_missing_translation_data
- assert_raise I18n::MissingTranslationData do
- @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :does_not_exist_3])
- end
- end
-
- def test_translate_an_array_of_keys_translates_all_of_them
- assert_equal %w(bar baz), @backend.translate('en', [:bar, :baz], :scope => [:foo])
- end
-
- def test_translate_calls_pluralize
- @backend.expects(:pluralize).with 'en', 'bar', 1
- @backend.translate 'en', :bar, :scope => [:foo], :count => 1
- end
-
- def test_translate_calls_interpolate
- @backend.expects(:interpolate).with 'en', 'bar', {}
- @backend.translate 'en', :bar, :scope => [:foo]
- end
-
- def test_translate_calls_interpolate_including_count_as_a_value
- @backend.expects(:interpolate).with 'en', 'bar', {:count => 1}
- @backend.translate 'en', :bar, :scope => [:foo], :count => 1
- end
-
- def test_translate_given_nil_as_a_locale_raises_an_argument_error
- assert_raise(I18n::InvalidLocale){ @backend.translate nil, :bar }
- end
-
- def test_translate_with_a_bogus_key_and_no_default_raises_missing_translation_data
- assert_raise(I18n::MissingTranslationData){ @backend.translate 'de', :bogus }
- end
-end
-
-class I18nSimpleBackendLookupTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- # useful because this way we can use the backend with no key for interpolation/pluralization
- def test_lookup_given_nil_as_a_key_returns_nil
- assert_nil @backend.send(:lookup, 'en', nil)
- end
-
- def test_lookup_given_nested_keys_looks_up_a_nested_hash_value
- assert_equal 'bar', @backend.send(:lookup, 'en', :bar, [:foo])
- end
-end
-
-class I18nSimpleBackendPluralizeTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def test_pluralize_given_nil_returns_the_given_entry
- entry = {:one => 'bar', :other => 'bars'}
- assert_equal entry, @backend.send(:pluralize, nil, entry, nil)
- end
-
- def test_pluralize_given_0_returns_zero_string_if_zero_key_given
- assert_equal 'zero', @backend.send(:pluralize, nil, {:zero => 'zero', :one => 'bar', :other => 'bars'}, 0)
- end
-
- def test_pluralize_given_0_returns_plural_string_if_no_zero_key_given
- assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 0)
- end
-
- def test_pluralize_given_1_returns_singular_string
- assert_equal 'bar', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 1)
- end
-
- def test_pluralize_given_2_returns_plural_string
- assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 2)
- end
-
- def test_pluralize_given_3_returns_plural_string
- assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 3)
- end
-
- def test_interpolate_given_incomplete_pluralization_data_raises_invalid_pluralization_data
- assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, {:one => 'bar'}, 2) }
- end
-
- # def test_interpolate_given_a_string_raises_invalid_pluralization_data
- # assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, 'bar', 2) }
- # end
- #
- # def test_interpolate_given_an_array_raises_invalid_pluralization_data
- # assert_raise(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, ['bar'], 2) }
- # end
-end
-
-class I18nSimpleBackendInterpolateTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def test_interpolate_given_a_value_hash_interpolates_the_values_to_the_string
- assert_equal 'Hi David!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'David')
- end
-
- def test_interpolate_given_a_value_hash_interpolates_into_unicode_string
- assert_equal 'Häi David!', @backend.send(:interpolate, nil, 'Häi {{name}}!', :name => 'David')
- end
-
- def test_interpolate_given_an_unicode_value_hash_interpolates_to_the_string
- assert_equal 'Hi ゆきひろ!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'ゆきひろ')
- end
-
- def test_interpolate_given_an_unicode_value_hash_interpolates_into_unicode_string
- assert_equal 'こんにちは、ゆきひろさん!', @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => 'ゆきひろ')
- end
-
- if Kernel.const_defined?(:Encoding)
- def test_interpolate_given_a_non_unicode_multibyte_value_hash_interpolates_into_a_string_with_the_same_encoding
- assert_equal euc_jp('Hi ゆきひろ!'), @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => euc_jp('ゆきひろ'))
- end
-
- def test_interpolate_given_an_unicode_value_hash_into_a_non_unicode_multibyte_string_raises_encoding_compatibility_error
- assert_raise(Encoding::CompatibilityError) do
- @backend.send(:interpolate, nil, euc_jp('こんにちは、{{name}}さん!'), :name => 'ゆきひろ')
- end
- end
-
- def test_interpolate_given_a_non_unicode_multibyte_value_hash_into_an_unicode_string_raises_encoding_compatibility_error
- assert_raise(Encoding::CompatibilityError) do
- @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => euc_jp('ゆきひろ'))
- end
- end
- end
-
- def test_interpolate_given_nil_as_a_string_returns_nil
- assert_nil @backend.send(:interpolate, nil, nil, :name => 'David')
- end
-
- def test_interpolate_given_an_non_string_as_a_string_returns_nil
- assert_equal [], @backend.send(:interpolate, nil, [], :name => 'David')
- end
-
- def test_interpolate_given_a_values_hash_with_nil_values_interpolates_the_string
- assert_equal 'Hi !', @backend.send(:interpolate, nil, 'Hi {{name}}!', {:name => nil})
- end
-
- def test_interpolate_given_an_empty_values_hash_raises_missing_interpolation_argument
- assert_raise(I18n::MissingInterpolationArgument) { @backend.send(:interpolate, nil, 'Hi {{name}}!', {}) }
- end
-
- def test_interpolate_given_a_string_containing_a_reserved_key_raises_reserved_interpolation_key
- assert_raise(I18n::ReservedInterpolationKey) { @backend.send(:interpolate, nil, '{{default}}', {:default => nil}) }
- end
-
- private
-
- def euc_jp(string)
- string.encode!(Encoding::EUC_JP)
- end
-end
-
-class I18nSimpleBackendLocalizeDateTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def setup
- @backend = I18n::Backend::Simple.new
- add_datetime_translations
- @date = Date.new 2008, 1, 1
- end
-
- def test_translate_given_the_short_format_it_uses_it
- assert_equal '01. Jan', @backend.localize('de', @date, :short)
- end
-
- def test_translate_given_the_long_format_it_uses_it
- assert_equal '01. Januar 2008', @backend.localize('de', @date, :long)
- end
-
- def test_translate_given_the_default_format_it_uses_it
- assert_equal '01.01.2008', @backend.localize('de', @date, :default)
- end
-
- def test_translate_given_a_day_name_format_it_returns_a_day_name
- assert_equal 'Dienstag', @backend.localize('de', @date, '%A')
- end
-
- def test_translate_given_an_abbr_day_name_format_it_returns_an_abbrevated_day_name
- assert_equal 'Di', @backend.localize('de', @date, '%a')
- end
-
- def test_translate_given_a_month_name_format_it_returns_a_month_name
- assert_equal 'Januar', @backend.localize('de', @date, '%B')
- end
-
- def test_translate_given_an_abbr_month_name_format_it_returns_an_abbrevated_month_name
- assert_equal 'Jan', @backend.localize('de', @date, '%b')
- end
-
- def test_translate_given_no_format_it_does_not_fail
- assert_nothing_raised{ @backend.localize 'de', @date }
- end
-
- def test_translate_given_an_unknown_format_it_does_not_fail
- assert_nothing_raised{ @backend.localize 'de', @date, '%x' }
- end
-
- def test_localize_nil_raises_argument_error
- assert_raise(I18n::ArgumentError) { @backend.localize 'de', nil }
- end
-
- def test_localize_object_raises_argument_error
- assert_raise(I18n::ArgumentError) { @backend.localize 'de', Object.new }
- end
-end
-
-class I18nSimpleBackendLocalizeDateTimeTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def setup
- @backend = I18n::Backend::Simple.new
- add_datetime_translations
- @morning = DateTime.new 2008, 1, 1, 6
- @evening = DateTime.new 2008, 1, 1, 18
- end
-
- def test_translate_given_the_short_format_it_uses_it
- assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short)
- end
-
- def test_translate_given_the_long_format_it_uses_it
- assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long)
- end
-
- def test_translate_given_the_default_format_it_uses_it
- assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default)
- end
-
- def test_translate_given_a_day_name_format_it_returns_the_correct_day_name
- assert_equal 'Dienstag', @backend.localize('de', @morning, '%A')
- end
-
- def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name
- assert_equal 'Di', @backend.localize('de', @morning, '%a')
- end
-
- def test_translate_given_a_month_name_format_it_returns_the_correct_month_name
- assert_equal 'Januar', @backend.localize('de', @morning, '%B')
- end
-
- def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name
- assert_equal 'Jan', @backend.localize('de', @morning, '%b')
- end
-
- def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator
- assert_equal 'am', @backend.localize('de', @morning, '%p')
- assert_equal 'pm', @backend.localize('de', @evening, '%p')
- end
-
- def test_translate_given_no_format_it_does_not_fail
- assert_nothing_raised{ @backend.localize 'de', @morning }
- end
-
- def test_translate_given_an_unknown_format_it_does_not_fail
- assert_nothing_raised{ @backend.localize 'de', @morning, '%x' }
- end
-end
-
-class I18nSimpleBackendLocalizeTimeTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def setup
- @old_timezone, ENV['TZ'] = ENV['TZ'], 'UTC'
- @backend = I18n::Backend::Simple.new
- add_datetime_translations
- @morning = Time.parse '2008-01-01 6:00 UTC'
- @evening = Time.parse '2008-01-01 18:00 UTC'
- end
-
- def teardown
- @old_timezone ? ENV['TZ'] = @old_timezone : ENV.delete('TZ')
- end
-
- def test_translate_given_the_short_format_it_uses_it
- assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short)
- end
-
- def test_translate_given_the_long_format_it_uses_it
- assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long)
- end
-
- # TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this?
- # def test_translate_given_the_default_format_it_uses_it
- # assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default)
- # end
-
- def test_translate_given_a_day_name_format_it_returns_the_correct_day_name
- assert_equal 'Dienstag', @backend.localize('de', @morning, '%A')
- end
-
- def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name
- assert_equal 'Di', @backend.localize('de', @morning, '%a')
- end
-
- def test_translate_given_a_month_name_format_it_returns_the_correct_month_name
- assert_equal 'Januar', @backend.localize('de', @morning, '%B')
- end
-
- def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name
- assert_equal 'Jan', @backend.localize('de', @morning, '%b')
- end
-
- def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator
- assert_equal 'am', @backend.localize('de', @morning, '%p')
- assert_equal 'pm', @backend.localize('de', @evening, '%p')
- end
-
- def test_translate_given_no_format_it_does_not_fail
- assert_nothing_raised{ @backend.localize 'de', @morning }
- end
-
- def test_translate_given_an_unknown_format_it_does_not_fail
- assert_nothing_raised{ @backend.localize 'de', @morning, '%x' }
- end
-end
-
-class I18nSimpleBackendHelperMethodsTest < Test::Unit::TestCase
- def setup
- @backend = I18n::Backend::Simple.new
- end
-
- def test_deep_symbolize_keys_works
- result = @backend.send :deep_symbolize_keys, 'foo' => {'bar' => {'baz' => 'bar'}}
- expected = {:foo => {:bar => {:baz => 'bar'}}}
- assert_equal expected, result
- end
-end
-
-class I18nSimpleBackendLoadTranslationsTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def test_load_translations_with_unknown_file_type_raises_exception
- assert_raise(I18n::UnknownFileType) { @backend.load_translations "#{@locale_dir}/en.xml" }
- end
-
- def test_load_translations_with_ruby_file_type_does_not_raise_exception
- assert_nothing_raised { @backend.load_translations "#{@locale_dir}/en.rb" }
- end
-
- def test_load_rb_loads_data_from_ruby_file
- data = @backend.send :load_rb, "#{@locale_dir}/en.rb"
- assert_equal({:'en-Ruby' => {:foo => {:bar => "baz"}}}, data)
- end
-
- def test_load_rb_loads_data_from_yaml_file
- data = @backend.send :load_yml, "#{@locale_dir}/en.yml"
- assert_equal({'en-Yaml' => {'foo' => {'bar' => 'baz'}}}, data)
- end
-
- def test_load_translations_loads_from_different_file_formats
- @backend = I18n::Backend::Simple.new
- @backend.load_translations "#{@locale_dir}/en.rb", "#{@locale_dir}/en.yml"
- expected = {
- :'en-Ruby' => {:foo => {:bar => "baz"}},
- :'en-Yaml' => {:foo => {:bar => "baz"}}
- }
- assert_equal expected, backend_get_translations
- end
-end
-
-class I18nSimpleBackendLoadPathTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def teardown
- I18n.load_path = []
- end
-
- def test_nested_load_paths_do_not_break_locale_loading
- @backend = I18n::Backend::Simple.new
- I18n.load_path = [[File.dirname(__FILE__) + '/locale/en.yml']]
- assert_nil backend_get_translations
- assert_nothing_raised { @backend.send :init_translations }
- assert_not_nil backend_get_translations
- end
-
- def test_adding_arrays_of_filenames_to_load_path_do_not_break_locale_loading
- @backend = I18n::Backend::Simple.new
- I18n.load_path << Dir[File.dirname(__FILE__) + '/locale/*.{rb,yml}']
- assert_nil backend_get_translations
- assert_nothing_raised { @backend.send :init_translations }
- assert_not_nil backend_get_translations
- end
-end
-
-class I18nSimpleBackendReloadTranslationsTest < Test::Unit::TestCase
- include I18nSimpleBackendTestSetup
-
- def setup
- @backend = I18n::Backend::Simple.new
- I18n.load_path = [File.dirname(__FILE__) + '/locale/en.yml']
- assert_nil backend_get_translations
- @backend.send :init_translations
- end
-
- def teardown
- I18n.load_path = []
- end
-
- def test_setup
- assert_not_nil backend_get_translations
- end
-
- def test_reload_translations_unloads_translations
- @backend.reload!
- assert_nil backend_get_translations
- end
-
- def test_reload_translations_uninitializes_translations
- @backend.reload!
- assert_equal @backend.initialized?, false
- end
-end
diff --git a/activesupport/lib/active_support/whiny_nil.rb b/activesupport/lib/active_support/whiny_nil.rb
index c4aaba7ab3..4f6ff7d3b5 100644
--- a/activesupport/lib/active_support/whiny_nil.rb
+++ b/activesupport/lib/active_support/whiny_nil.rb
@@ -43,10 +43,7 @@ class NilClass
private
def method_missing(method, *args, &block)
- # Ruby 1.9.2: disallow explicit coercion via method_missing.
- if method == :to_ary || method == :to_str
- super
- elsif klass = METHOD_CLASS_MAP[method]
+ if klass = METHOD_CLASS_MAP[method]
raise_nil_warning_for klass, method, caller
else
super
diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb
index 5c3d93c4a1..48c1cb3fe9 100644
--- a/activesupport/lib/active_support/xml_mini/jdom.rb
+++ b/activesupport/lib/active_support/xml_mini/jdom.rb
@@ -3,6 +3,8 @@ raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFO
require 'jruby'
include Java
+require 'active_support/core_ext/object/blank'
+
import javax.xml.parsers.DocumentBuilder unless defined? DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory unless defined? DocumentBuilderFactory
import java.io.StringReader unless defined? StringReader
diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb
index 0f7ba1918b..9cf187302f 100644
--- a/activesupport/lib/active_support/xml_mini/libxml.rb
+++ b/activesupport/lib/active_support/xml_mini/libxml.rb
@@ -1,4 +1,6 @@
require 'libxml'
+require 'active_support/core_ext/object/returning'
+require 'active_support/core_ext/object/blank'
# = XmlMini LibXML implementation
module ActiveSupport
@@ -12,7 +14,7 @@ module ActiveSupport
if !data.respond_to?(:read)
data = StringIO.new(data || '')
end
-
+
char = data.getc
if char.nil?
{}
@@ -34,106 +36,42 @@ module LibXML #:nodoc:
end
module Node #:nodoc:
- CONTENT_ROOT = '__content__'
- LIB_XML_LIMIT = 30000000 # Hardcoded LibXML limit
+ CONTENT_ROOT = '__content__'.freeze
# Convert XML document to hash
#
# hash::
# Hash to merge the converted element into.
def to_hash(hash={})
- if text? || cdata?
- raise LibXML::XML::Error if hash[CONTENT_ROOT].to_s.length + content.length >= LIB_XML_LIMIT
- hash[CONTENT_ROOT] = hash[CONTENT_ROOT].to_s + content
- else
- sub_hash = insert_name_into_hash(hash, name)
- attributes_to_hash(sub_hash)
- if array?
- children_array_to_hash(sub_hash)
- elsif yaml?
- children_yaml_to_hash(sub_hash)
- else
- children_to_hash(sub_hash)
- end
- end
- hash
- end
+ node_hash = {}
- protected
-
- # Insert name into hash
- #
- # hash::
- # Hash to merge the converted element into.
- # name::
- # name to to merge into hash
- def insert_name_into_hash(hash, name)
- sub_hash = {}
- if hash[name]
- if !hash[name].kind_of? Array
- hash[name] = [hash[name]]
- end
- hash[name] << sub_hash
- else
- hash[name] = sub_hash
- end
- sub_hash
+ # Insert node hash into parent hash correctly.
+ case hash[name]
+ when Array then hash[name] << node_hash
+ when Hash then hash[name] = [hash[name], node_hash]
+ when nil then hash[name] = node_hash
end
- # Insert children into hash
- #
- # hash::
- # Hash to merge the children into.
- def children_to_hash(hash={})
- each { |child| child.to_hash(hash) }
-
- if hash.length > 1 && hash[CONTENT_ROOT].blank?
- hash.delete(CONTENT_ROOT)
+ # Handle child elements
+ each_child do |c|
+ if c.element?
+ c.to_hash(node_hash)
+ elsif c.text? || c.cdata?
+ node_hash[CONTENT_ROOT] ||= ''
+ node_hash[CONTENT_ROOT] << c.content
end
-
- attributes_to_hash(hash)
- hash
end
- # Convert xml attributes to hash
- #
- # hash::
- # Hash to merge the attributes into
- def attributes_to_hash(hash={})
- each_attr { |attr| hash[attr.name] = attr.value }
- hash
+ # Remove content node if it is blank
+ if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank?
+ node_hash.delete(CONTENT_ROOT)
end
- # Convert array into hash
- #
- # hash::
- # Hash to merge the array into
- def children_array_to_hash(hash={})
- hash[child.name] = map do |child|
- returning({}) { |sub_hash| child.children_to_hash(sub_hash) }
- end
- hash
- end
-
- # Convert yaml into hash
- #
- # hash::
- # Hash to merge the yaml into
- def children_yaml_to_hash(hash = {})
- hash[CONTENT_ROOT] = content unless content.blank?
- hash
- end
-
- # Check if child is of type array
- def array?
- child? && child.next? && child.name == child.next.name
- end
-
- # Check if child is of type yaml
- def yaml?
- attributes.collect{|x| x.value}.include?('yaml')
- end
+ # Handle attributes
+ each_attr { |a| node_hash[a.name] = a.value }
+ hash
+ end
end
end
end
diff --git a/activesupport/lib/active_support/xml_mini/libxmlsax.rb b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
new file mode 100644
index 0000000000..d7b2f4c5be
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
@@ -0,0 +1,84 @@
+require 'libxml'
+
+# = XmlMini LibXML implementation using a SAX-based parser
+module ActiveSupport
+ module XmlMini_LibXMLSAX
+ extend self
+
+ # Class that will build the hash while the XML document
+ # is being parsed using SAX events.
+ class HashBuilder
+
+ include LibXML::XML::SaxParser::Callbacks
+
+ CONTENT_KEY = '__content__'.freeze
+ HASH_SIZE_KEY = '__hash_size__'.freeze
+
+ attr_reader :hash
+
+ def current_hash
+ @hash_stack.last
+ end
+
+ def on_start_document
+ @hash = { CONTENT_KEY => '' }
+ @hash_stack = [@hash]
+ end
+
+ def on_end_document
+ @hash = @hash_stack.pop
+ @hash.delete(CONTENT_KEY)
+ end
+
+ def on_start_element(name, attrs = {})
+ new_hash = { CONTENT_KEY => '' }.merge(attrs)
+ new_hash[HASH_SIZE_KEY] = new_hash.size + 1
+
+ case current_hash[name]
+ when Array then current_hash[name] << new_hash
+ when Hash then current_hash[name] = [current_hash[name], new_hash]
+ when nil then current_hash[name] = new_hash
+ end
+
+ @hash_stack.push(new_hash)
+ end
+
+ def on_end_element(name)
+ if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ''
+ current_hash.delete(CONTENT_KEY)
+ end
+ @hash_stack.pop
+ end
+
+ def on_characters(string)
+ current_hash[CONTENT_KEY] << string
+ end
+
+ alias_method :on_cdata_block, :on_characters
+ end
+
+ attr_accessor :document_class
+ self.document_class = HashBuilder
+
+ def parse(data)
+ if !data.respond_to?(:read)
+ data = StringIO.new(data || '')
+ end
+
+ char = data.getc
+ if char.nil?
+ {}
+ else
+ data.ungetc(char)
+
+ LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER)
+ parser = LibXML::XML::SaxParser.io(data)
+ document = self.document_class.new
+
+ parser.callbacks = document
+ parser.parse
+ document.hash
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb
index 17bacd8441..eb61a7fc22 100644
--- a/activesupport/lib/active_support/xml_mini/nokogiri.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb
@@ -1,4 +1,5 @@
require 'nokogiri'
+require 'active_support/core_ext/object/blank'
# = XmlMini Nokogiri implementation
module ActiveSupport
@@ -12,13 +13,13 @@ module ActiveSupport
if !data.respond_to?(:read)
data = StringIO.new(data || '')
end
-
+
char = data.getc
if char.nil?
{}
else
data.ungetc(char)
- doc = Nokogiri::XML(data) { |cfg| cfg.noblanks }
+ doc = Nokogiri::XML(data)
raise doc.errors.first if doc.errors.length > 0
doc.to_hash
end
@@ -32,39 +33,41 @@ module ActiveSupport
end
module Node #:nodoc:
- CONTENT_ROOT = '__content__'
+ CONTENT_ROOT = '__content__'.freeze
# Convert XML document to hash
#
# hash::
# Hash to merge the converted element into.
- def to_hash(hash = {})
- attributes = attributes_as_hash
- if hash[name]
- hash[name] = [hash[name]].flatten
- hash[name] << attributes
- else
- hash[name] ||= attributes
- end
+ def to_hash(hash={})
+ node_hash = {}
- children.each { |child|
- next if child.blank? && 'file' != self['type']
+ # Insert node hash into parent hash correctly.
+ case hash[name]
+ when Array then hash[name] << node_hash
+ when Hash then hash[name] = [hash[name], node_hash]
+ when nil then hash[name] = node_hash
+ end
- if child.text? || child.cdata?
- (attributes[CONTENT_ROOT] ||= '') << child.content
- next
+ # Handle child elements
+ children.each do |c|
+ if c.element?
+ c.to_hash(node_hash)
+ elsif c.text? || c.cdata?
+ node_hash[CONTENT_ROOT] ||= ''
+ node_hash[CONTENT_ROOT] << c.content
end
+ end
- child.to_hash attributes
- }
+ # Remove content node if it is blank and there are child tags
+ if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank?
+ node_hash.delete(CONTENT_ROOT)
+ end
- hash
- end
+ # Handle attributes
+ attribute_nodes.each { |a| node_hash[a.node_name] = a.value }
- def attributes_as_hash
- Hash[*(attribute_nodes.map { |node|
- [node.node_name, node.value]
- }.flatten)]
+ hash
end
end
end
diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
new file mode 100644
index 0000000000..d538a9110f
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
@@ -0,0 +1,82 @@
+require 'nokogiri'
+
+# = XmlMini Nokogiri implementation using a SAX-based parser
+module ActiveSupport
+ module XmlMini_NokogiriSAX
+ extend self
+
+ # Class that will build the hash while the XML document
+ # is being parsed using SAX events.
+ class HashBuilder < Nokogiri::XML::SAX::Document
+
+ CONTENT_KEY = '__content__'.freeze
+ HASH_SIZE_KEY = '__hash_size__'.freeze
+
+ attr_reader :hash
+
+ def current_hash
+ @hash_stack.last
+ end
+
+ def start_document
+ @hash = {}
+ @hash_stack = [@hash]
+ end
+
+ def end_document
+ raise "Parse stack not empty!" if @hash_stack.size > 1
+ end
+
+ def error(error_message)
+ raise error_message
+ end
+
+ def start_element(name, attrs = [])
+ new_hash = { CONTENT_KEY => '' }
+ new_hash[attrs.shift] = attrs.shift while attrs.length > 0
+ new_hash[HASH_SIZE_KEY] = new_hash.size + 1
+
+ case current_hash[name]
+ when Array then current_hash[name] << new_hash
+ when Hash then current_hash[name] = [current_hash[name], new_hash]
+ when nil then current_hash[name] = new_hash
+ end
+
+ @hash_stack.push(new_hash)
+ end
+
+ def end_element(name)
+ if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ''
+ current_hash.delete(CONTENT_KEY)
+ end
+ @hash_stack.pop
+ end
+
+ def characters(string)
+ current_hash[CONTENT_KEY] << string
+ end
+
+ alias_method :cdata_block, :characters
+ end
+
+ attr_accessor :document_class
+ self.document_class = HashBuilder
+
+ def parse(data)
+ if !data.respond_to?(:read)
+ data = StringIO.new(data || '')
+ end
+
+ char = data.getc
+ if char.nil?
+ {}
+ else
+ data.ungetc(char)
+ document = self.document_class.new
+ parser = Nokogiri::XML::SAX::Parser.new(document)
+ parser.parse(data)
+ document.hash
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/activesupport/test/autoload.rb b/activesupport/test/autoload.rb
new file mode 100644
index 0000000000..5d8026a9ca
--- /dev/null
+++ b/activesupport/test/autoload.rb
@@ -0,0 +1,80 @@
+require 'abstract_unit'
+
+class TestAutoloadModule < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ module ::Fixtures
+ extend ActiveSupport::Autoload
+
+ module Autoload
+ extend ActiveSupport::Autoload
+ end
+ end
+
+ test "the autoload module works like normal autoload" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass, "fixtures/autoload/some_class"
+ end
+
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "when specifying an :eager constant it still works like normal autoload by default" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass, "fixtures/autoload/some_class"
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test ":eager constants can be triggered via ActiveSupport::Autoload.eager_autoload!" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass, "fixtures/autoload/some_class"
+ end
+ ActiveSupport::Autoload.eager_autoload!
+ assert $LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "the location of autoloaded constants defaults to :name.underscore" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "the location of :eager autoloaded constants defaults to :name.underscore" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass
+ end
+
+ ActiveSupport::Autoload.eager_autoload!
+ assert $LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "a directory for a block of autoloads can be specified" do
+ module ::Fixtures
+ autoload_under "autoload" do
+ autoload :AnotherClass
+ end
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/another_class.rb")
+ assert_nothing_raised { ::Fixtures::AnotherClass }
+ end
+
+ test "a path for a block of autoloads can be specified" do
+ module ::Fixtures
+ autoload_at "fixtures/autoload/another_class" do
+ autoload :AnotherClass
+ end
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/another_class.rb")
+ assert_nothing_raised { ::Fixtures::AnotherClass }
+ end
+end \ No newline at end of file
diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb
index 18721eab19..2e978f01be 100644
--- a/activesupport/test/callback_inheritance_test.rb
+++ b/activesupport/test/callback_inheritance_test.rb
@@ -56,6 +56,31 @@ class Child < GrandParent
end
end
+class EmptyParent
+ include ActiveSupport::Callbacks
+
+ def performed?
+ @performed ||= false
+ end
+
+ define_callbacks :dispatch
+
+ def perform!
+ @performed = true
+ end
+
+ def dispatch
+ _run_dispatch_callbacks
+ self
+ end
+end
+
+class EmptyChild < EmptyParent
+ set_callback :dispatch, :before, :do_nothing
+
+ def do_nothing
+ end
+end
class BasicCallbacksTest < Test::Unit::TestCase
def setup
@@ -113,3 +138,13 @@ class InheritedCallbacksTest2 < Test::Unit::TestCase
assert_equal %w(before1 before2 update after2 after1), @update2.log
end
end
+
+class DynamicInheritedCallbacks < Test::Unit::TestCase
+ def test_callbacks_looks_to_the_superclass_before_running
+ child = EmptyChild.new.dispatch
+ assert !child.performed?
+ EmptyParent.set_callback :dispatch, :before, :perform!
+ child = EmptyChild.new.dispatch
+ assert child.performed?
+ end
+end
diff --git a/activesupport/test/core_ext/blank_test.rb b/activesupport/test/core_ext/blank_test.rb
index 1dbbf3ff30..ed6c625a0a 100644
--- a/activesupport/test/core_ext/blank_test.rb
+++ b/activesupport/test/core_ext/blank_test.rb
@@ -14,12 +14,17 @@ class BlankTest < Test::Unit::TestCase
NOT = [ EmptyFalse.new, Object.new, true, 0, 1, 'a', [nil], { nil => 0 } ]
def test_blank
- BLANK.each { |v| assert v.blank?, "#{v.inspect} should be blank" }
+ BLANK.each { |v| assert v.blank?, "#{v.inspect} should be blank" }
NOT.each { |v| assert !v.blank?, "#{v.inspect} should not be blank" }
end
def test_present
BLANK.each { |v| assert !v.present?, "#{v.inspect} should not be present" }
- NOT.each { |v| assert v.present?, "#{v.inspect} should be present" }
+ NOT.each { |v| assert v.present?, "#{v.inspect} should be present" }
+ end
+
+ def test_presence
+ BLANK.each { |v| assert_equal nil, v.presence, "#{v.inspect}.presence should return nil" }
+ NOT.each { |v| assert_equal v, v.presence, "#{v.inspect}.presence should return self" }
end
end
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index 4341ead488..278c05797b 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -350,6 +350,10 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal 946684800.0, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_f
end
+ def test_to_i
+ assert_equal 946684800, DateTime.civil(2000).to_i
+ end
+
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index 66f5f9fbde..4650b796b6 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -89,4 +89,9 @@ 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)
+ end
end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 4642bb1330..5b1d53ac7b 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -902,9 +902,11 @@ class HashToXmlTest < Test::Unit::TestCase
def test_expansion_count_is_limited
expected = {
- 'ActiveSupport::XmlMini_REXML' => 'RuntimeError',
- 'ActiveSupport::XmlMini_Nokogiri' => 'Nokogiri::XML::SyntaxError',
- 'ActiveSupport::XmlMini_LibXML' => 'LibXML::XML::Error',
+ 'ActiveSupport::XmlMini_REXML' => 'RuntimeError',
+ 'ActiveSupport::XmlMini_Nokogiri' => 'Nokogiri::XML::SyntaxError',
+ 'ActiveSupport::XmlMini_NokogiriSAX' => 'RuntimeError',
+ 'ActiveSupport::XmlMini_LibXML' => 'LibXML::XML::Error',
+ 'ActiveSupport::XmlMini_LibXMLSAX' => 'LibXML::XML::Error',
}[ActiveSupport::XmlMini.backend.name].constantize
assert_raise expected do
diff --git a/activesupport/test/core_ext/integer_ext_test.rb b/activesupport/test/core_ext/integer_ext_test.rb
index e1591089f5..fe8c7eb224 100644
--- a/activesupport/test/core_ext/integer_ext_test.rb
+++ b/activesupport/test/core_ext/integer_ext_test.rb
@@ -5,6 +5,11 @@ class IntegerExtTest < Test::Unit::TestCase
def test_multiple_of
[ -7, 0, 7, 14 ].each { |i| assert i.multiple_of?(7) }
[ -7, 7, 14 ].each { |i| assert ! i.multiple_of?(6) }
+
+ # test the 0 edge case
+ assert 0.multiple_of?(0)
+ assert !5.multiple_of?(0)
+
# test with a prime
assert !22953686867719691230002707821868552601124472329079.multiple_of?(2)
assert !22953686867719691230002707821868552601124472329079.multiple_of?(3)
diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb
index 0fb15be654..4d655913cc 100644
--- a/activesupport/test/core_ext/object/to_query_test.rb
+++ b/activesupport/test/core_ext/object/to_query_test.rb
@@ -17,22 +17,22 @@ class ToQueryTest < Test::Unit::TestCase
end
def test_nested_conversion
- assert_query_equal 'person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas',
+ assert_query_equal 'person[login]=seckar&person[name]=Nicholas',
:person => {:name => 'Nicholas', :login => 'seckar'}
end
def test_multiple_nested
- assert_query_equal 'account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10',
+ assert_query_equal 'account[person][id]=20&person[id]=10',
:person => {:id => 10}, :account => {:person => {:id => 20}}
end
def test_array_values
- assert_query_equal 'person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20',
+ assert_query_equal 'person[id][]=10&person[id][]=20',
:person => {:id => [10, 20]}
end
def test_array_values_are_not_sorted
- assert_query_equal 'person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10',
+ assert_query_equal 'person[id][]=20&person[id][]=10',
:person => {:id => [20, 10]}
end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index 56ed296dac..9a805bc010 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -350,6 +350,24 @@ class OutputSafetyTest < ActiveSupport::TestCase
assert_equal @string, @string.html_safe!
end
+ test "A fixnum is safe by default" do
+ assert 5.html_safe?
+ end
+
+ test "An object is unsafe by default" do
+ klass = Class.new(Object) do
+ def to_str
+ "other"
+ end
+ end
+
+ @string.html_safe!
+ @string << klass.new
+
+ assert_equal "helloother", @string
+ assert !@string.html_safe?
+ end
+
test "Adding a safe string to another safe string returns a safe string" do
@other_string = "other".html_safe!
@string.html_safe!
@@ -416,4 +434,17 @@ class OutputSafetyTest < ActiveSupport::TestCase
@other_string << @string
assert @other_string.html_safe?
end
+
+ test "Concatting a fixnum to safe always yields safe" do
+ @string.html_safe!
+ @string.concat(13)
+ assert @string.html_safe?
+ end
+end
+
+class StringExcludeTest < ActiveSupport::TestCase
+ test 'inverse of #include' do
+ assert_equal false, 'foo'.exclude?('o')
+ assert_equal true, 'foo'.exclude?('p')
+ end
end
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index bb60968a4f..3a12100e86 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -284,6 +284,12 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal 946684800, result
assert result.is_a?(Integer)
end
+
+ def test_to_i_with_wrapped_datetime
+ datetime = DateTime.civil(2000, 1, 1, 0)
+ twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
+ assert_equal 946684800, twz.to_i
+ end
def test_to_time
assert_equal @twz, @twz.to_time
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index a3ae39d071..cf27357b32 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -62,7 +62,7 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_deprecate_class_method
- assert_deprecated(/none is deprecated.*test_deprecate_class_method at/) do
+ assert_deprecated(/none is deprecated.*test_deprecate_class_method/) do
assert_equal 1, @dtc.none
end
diff --git a/activesupport/test/fixtures/autoload/another_class.rb b/activesupport/test/fixtures/autoload/another_class.rb
new file mode 100644
index 0000000000..a240b3de41
--- /dev/null
+++ b/activesupport/test/fixtures/autoload/another_class.rb
@@ -0,0 +1,2 @@
+class Fixtures::AnotherClass
+end \ No newline at end of file
diff --git a/activesupport/test/fixtures/autoload/some_class.rb b/activesupport/test/fixtures/autoload/some_class.rb
new file mode 100644
index 0000000000..13b3c73ef5
--- /dev/null
+++ b/activesupport/test/fixtures/autoload/some_class.rb
@@ -0,0 +1,2 @@
+class Fixtures::Autoload::SomeClass
+end \ No newline at end of file
diff --git a/activesupport/test/isolation_test.rb b/activesupport/test/isolation_test.rb
index 20e11df1dd..a7af5e96f6 100644
--- a/activesupport/test/isolation_test.rb
+++ b/activesupport/test/isolation_test.rb
@@ -4,159 +4,179 @@ require 'rbconfig'
if defined?(MiniTest) || defined?(Test::Unit::TestResultFailureSupport)
$stderr.puts "Isolation tests can test test-unit 1 only"
-else
- # Does awesome
- if ENV['CHILD']
- class ChildIsolationTest < ActiveSupport::TestCase
- include ActiveSupport::Testing::Isolation
-
- def self.setup
- File.open(File.join(File.dirname(__FILE__), "fixtures", "isolation_test"), "a") do |f|
- f.puts "hello"
- end
- end
+elsif ENV['CHILD']
+ class ChildIsolationTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
- def setup
- @instance = "HELLO"
+ def self.setup
+ File.open(File.join(File.dirname(__FILE__), "fixtures", "isolation_test"), "a") do |f|
+ f.puts "hello"
end
+ end
- def teardown
- raise if @boom
- end
+ def setup
+ @instance = "HELLO"
+ end
- test "runs the test" do
- assert true
- end
+ def teardown
+ raise if @boom
+ end
- test "captures errors" do
- raise
- end
+ test "runs the test" do
+ assert true
+ end
- test "captures failures" do
- assert false
- end
+ test "captures errors" do
+ raise
+ end
- test "first runs in isolation" do
- assert_nil $x
- $x = 1
- end
+ test "captures failures" do
+ assert false
+ end
- test "second runs in isolation" do
- assert_nil $x
- $x = 2
- end
+ test "first runs in isolation" do
+ assert_nil $x
+ $x = 1
+ end
- test "runs with slow tests" do
- sleep 0.3
- assert true
- sleep 0.2
- end
+ test "second runs in isolation" do
+ assert_nil $x
+ $x = 2
+ end
- test "runs setup" do
- assert "HELLO", @instance
- end
+ test "runs with slow tests" do
+ sleep 0.3
+ assert true
+ sleep 0.2
+ end
- test "runs teardown" do
- @boom = true
- end
+ test "runs setup" do
+ assert "HELLO", @instance
+ end
- test "resets requires one" do
- assert !defined?(OmgOmg)
- assert_equal 0, $LOADED_FEATURES.grep(/fixtures\/omgomg/).size
- require File.expand_path(File.join(File.dirname(__FILE__), "fixtures", "omgomg"))
- end
+ test "runs teardown" do
+ @boom = true
+ end
- test "resets requires two" do
- assert !defined?(OmgOmg)
- assert_equal 0, $LOADED_FEATURES.grep(/fixtures\/omgomg/).size
- require File.expand_path(File.join(File.dirname(__FILE__), "fixtures", "omgomg"))
- end
+ test "resets requires one" do
+ assert !defined?(OmgOmg)
+ assert_equal 0, $LOADED_FEATURES.grep(/fixtures\/omgomg/).size
+ require File.expand_path(File.join(File.dirname(__FILE__), "fixtures", "omgomg"))
end
- else
- class ParentIsolationTest < ActiveSupport::TestCase
-
- File.open(File.join(File.dirname(__FILE__), "fixtures", "isolation_test"), "w") {}
-
- ENV["CHILD"] = "1"
- OUTPUT = `#{RbConfig::CONFIG["bindir"]}/#{RbConfig::CONFIG["ruby_install_name"]} -I#{File.dirname(__FILE__)} "#{File.expand_path(__FILE__)}" -v`
- ENV.delete("CHILD")
-
- def setup
- # Extract the results
- @results = {}
- OUTPUT[/Started\n\s*(.*)\s*\nFinished/mi, 1].to_s.split(/\s*\n\s*/).each do |result|
- result =~ %r'^(\w+)\(\w+\):\s*(\.|E|F)$'
- @results[$1] = { 'E' => :error, '.' => :success, 'F' => :failure }[$2]
- end
-
- # Extract the backtraces
- @backtraces = {}
- OUTPUT.scan(/^\s*\d+\).*?\n\n/m).each do |backtrace|
- # \n 1) Error:\ntest_captures_errors(ChildIsolationTest):
- backtrace =~ %r'\s*\d+\)\s*(Error|Failure):\n(\w+)'i
- @backtraces[$2] = { :type => $1, :output => backtrace }
- end
- end
- def assert_failing(name)
- assert_equal :failure, @results[name.to_s], "Test #{name} did not fail"
- end
+ test "resets requires two" do
+ assert !defined?(OmgOmg)
+ assert_equal 0, $LOADED_FEATURES.grep(/fixtures\/omgomg/).size
+ require File.expand_path(File.join(File.dirname(__FILE__), "fixtures", "omgomg"))
+ end
+ end
+else
+ class ParentIsolationTest < ActiveSupport::TestCase
- def assert_passing(name)
- assert_equal :success, @results[name.to_s], "Test #{name} did not pass"
- end
+ File.open(File.join(File.dirname(__FILE__), "fixtures", "isolation_test"), "w") {}
- def assert_erroring(name)
- assert_equal :error, @results[name.to_s], "Test #{name} did not error"
- end
+ ENV["CHILD"] = "1"
+ OUTPUT = `#{RbConfig::CONFIG["bindir"]}/#{RbConfig::CONFIG["ruby_install_name"]} -I#{File.dirname(__FILE__)} "#{File.expand_path(__FILE__)}" -v`
+ ENV.delete("CHILD")
- test "has all tests" do
- assert_equal 10, @results.length
- end
+ def setup
+ defined?(::MiniTest) ? parse_minitest : parse_testunit
+ end
- test "passing tests are still reported" do
- assert_passing :test_runs_the_test
- assert_passing :test_runs_with_slow_tests
+ def parse_testunit
+ @results = {}
+ OUTPUT[/Started\n\s*(.*)\s*\nFinished/mi, 1].to_s.split(/\s*\n\s*/).each do |result|
+ result =~ %r'^(\w+)\(\w+\):\s*(\.|E|F)$'
+ @results[$1] = { 'E' => :error, '.' => :success, 'F' => :failure }[$2]
end
- test "resets global variables" do
- assert_passing :test_first_runs_in_isolation
- assert_passing :test_second_runs_in_isolation
+ # Extract the backtraces
+ @backtraces = {}
+ OUTPUT.scan(/^\s*\d+\).*?\n\n/m).each do |backtrace|
+ # \n 1) Error:\ntest_captures_errors(ChildIsolationTest):
+ backtrace =~ %r'\s*\d+\)\s*(Error|Failure):\n(\w+)'i
+ @backtraces[$2] = { :type => $1, :output => backtrace }
end
+ end
- test "resets requires" do
- assert_passing :test_resets_requires_one
- assert_passing :test_resets_requires_two
- end
+ def parse_minitest
+ @results = {}
+ OUTPUT[/Started\n\s*(.*)\s*\nFinished/mi, 1].to_s.split(/\s*\n\s*/).each do |result|
+ result =~ %r'^\w+#(\w+):.*:\s*(.*Assertion.*|.*RuntimeError.*|\.\s*)$'
+ val = :success
+ val = :error if $2.include?('RuntimeError')
+ val = :failure if $2.include?('Assertion')
- test "erroring tests are still reported" do
- assert_erroring :test_captures_errors
+ @results[$1] = val
end
- test "runs setup and teardown methods" do
- assert_passing :test_runs_setup
- assert_erroring :test_runs_teardown
+ # Extract the backtraces
+ @backtraces = {}
+ OUTPUT.scan(/^\s*\d+\).*?\n\n/m).each do |backtrace|
+ # \n 1) Error:\ntest_captures_errors(ChildIsolationTest):
+ backtrace =~ %r'\s*\d+\)\s*(Error|Failure):\n(\w+)'i
+ @backtraces[$2] = { :type => $1, :output => backtrace }
end
+ end
- test "correct tests fail" do
- assert_failing :test_captures_failures
- end
+ def assert_failing(name)
+ assert_equal :failure, @results[name.to_s], "Test #{name} failed"
+ end
- test "backtrace is printed for errors" do
- assert_equal 'Error', @backtraces["test_captures_errors"][:type]
- assert_match %r{isolation_test.rb:\d+:in `test_captures_errors'}, @backtraces["test_captures_errors"][:output]
- end
+ def assert_passing(name)
+ assert_equal :success, @results[name.to_s], "Test #{name} passed"
+ end
- test "backtrace is printed for failures" do
- assert_equal 'Failure', @backtraces["test_captures_failures"][:type]
- assert_match %r{isolation_test.rb:\d+:in `test_captures_failures'}, @backtraces["test_captures_failures"][:output]
- end
+ def assert_erroring(name)
+ assert_equal :error, @results[name.to_s], "Test #{name} errored"
+ end
- test "self.setup is run only once" do
- text = File.read(File.join(File.dirname(__FILE__), "fixtures", "isolation_test"))
- assert_equal "hello\n", text
- end
+ test "has all tests" do
+ assert_equal 10, @results.length
+ end
+
+ test "passing tests are still reported" do
+ assert_passing :test_runs_the_test
+ assert_passing :test_runs_with_slow_tests
+ end
+ test "resets global variables" do
+ assert_passing :test_first_runs_in_isolation
+ assert_passing :test_second_runs_in_isolation
end
+
+ test "resets requires" do
+ assert_passing :test_resets_requires_one
+ assert_passing :test_resets_requires_two
+ end
+
+ test "erroring tests are still reported" do
+ assert_erroring :test_captures_errors
+ end
+
+ test "runs setup and teardown methods" do
+ assert_passing :test_runs_setup
+ assert_erroring :test_runs_teardown
+ end
+
+ test "correct tests fail" do
+ assert_failing :test_captures_failures
+ end
+
+ test "backtrace is printed for errors" do
+ assert_equal 'Error', @backtraces["test_captures_errors"][:type]
+ assert_match %r{isolation_test.rb:\d+}, @backtraces["test_captures_errors"][:output]
+ end
+
+ test "backtrace is printed for failures" do
+ assert_equal 'Failure', @backtraces["test_captures_failures"][:type]
+ assert_match %r{isolation_test.rb:\d+}, @backtraces["test_captures_failures"][:output]
+ end
+
+ test "self.setup is run only once" do
+ text = File.read(File.join(File.dirname(__FILE__), "fixtures", "isolation_test"))
+ assert_equal "hello\n", text
+ end
+
end
end
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 5d81d09f03..cf9a635b5f 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -23,7 +23,9 @@ class TestJSONEncoding < Test::Unit::TestCase
StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")],
[ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ],
- [ 'http://test.host/posts/1', %("http://test.host/posts/1")]]
+ [ 'http://test.host/posts/1', %("http://test.host/posts/1")],
+ [ "Control characters: \x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f",
+ %("Control characters: \\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000B\\f\\r\\u000E\\u000F\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F") ]]
ArrayTests = [[ ['a', 'b', 'c'], %([\"a\",\"b\",\"c\"]) ],
[ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]]
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
index 01106e83e9..3ba77ae135 100644
--- a/activesupport/test/notifications_test.rb
+++ b/activesupport/test/notifications_test.rb
@@ -1,206 +1,168 @@
require 'abstract_unit'
-# Allow LittleFanout to be cleaned.
-class ActiveSupport::Notifications::LittleFanout
- def clear
- @listeners.clear
- end
-end
+module Notifications
+ class TestCase < ActiveSupport::TestCase
+ def setup
+ Thread.abort_on_exception = true
+
+ @notifier = ActiveSupport::Notifications::Notifier.new
+ @events = []
+ @notifier.subscribe { |*args| @events << event(*args) }
+ end
-class NotificationsEventTest < Test::Unit::TestCase
- def test_events_are_initialized_with_details
- event = event(:foo, Time.now, Time.now + 1, 1, random_id, :payload => :bar)
- assert_equal :foo, event.name
- assert_equal Hash[:payload => :bar], event.payload
- end
+ def teardown
+ Thread.abort_on_exception = false
+ end
- def test_events_consumes_information_given_as_payload
- time = Time.now
- event = event(:foo, time, time + 0.01, 1, random_id, {})
+ private
+ def event(*args)
+ ActiveSupport::Notifications::Event.new(*args)
+ end
- assert_equal Hash.new, event.payload
- assert_equal time, event.time
- assert_equal 1, event.result
- assert_equal 10.0, event.duration
+ def drain
+ @notifier.wait
+ end
end
- def test_event_is_parent_based_on_time_frame
- time = Time.utc(2009, 01, 01, 0, 0, 1)
+ class PubSubTest < TestCase
+ def test_events_are_published_to_a_listener
+ @notifier.publish :foo
+ @notifier.wait
+ assert_equal [[:foo]], @events
+ end
- parent = event(:foo, Time.utc(2009), Time.utc(2009) + 100, nil, random_id, {})
- child = event(:foo, time, time + 10, nil, random_id, {})
- not_child = event(:foo, time, time + 100, nil, random_id, {})
+ def test_subscriber_with_pattern
+ events = []
+ @notifier.subscribe('1') { |*args| events << args }
- assert parent.parent_of?(child)
- assert !child.parent_of?(parent)
- assert !parent.parent_of?(not_child)
- assert !not_child.parent_of?(parent)
- end
+ @notifier.publish '1'
+ @notifier.publish '1.a'
+ @notifier.publish 'a.1'
+ @notifier.wait
-protected
+ assert_equal [['1'], ['1.a']], events
+ end
- def random_id
- @random_id ||= ActiveSupport::SecureRandom.hex(10)
- end
+ def test_subscriber_with_pattern_as_regexp
+ events = []
+ @notifier.subscribe(/\d/) { |*args| events << args }
- def event(*args)
- ActiveSupport::Notifications::Event.new(*args)
- end
-end
+ @notifier.publish '1'
+ @notifier.publish 'a.1'
+ @notifier.publish '1.a'
+ @notifier.wait
-class NotificationsMainTest < Test::Unit::TestCase
- def setup
- @events = []
- Thread.abort_on_exception = true
- ActiveSupport::Notifications.subscribe do |*args|
- @events << ActiveSupport::Notifications::Event.new(*args)
+ assert_equal [['1'], ['a.1'], ['1.a']], events
end
- end
- def teardown
- Thread.abort_on_exception = false
- ActiveSupport::Notifications.queue.clear
- end
+ def test_multiple_subscribers
+ @another = []
+ @notifier.subscribe { |*args| @another << args }
+ @notifier.publish :foo
+ @notifier.wait
- def test_notifications_returns_action_result
- result = ActiveSupport::Notifications.instrument(:awesome, :payload => "notifications") do
- 1 + 1
+ assert_equal [[:foo]], @events
+ assert_equal [[:foo]], @another
end
- assert_equal 2, result
+ private
+ def event(*args)
+ args
+ end
end
- def test_events_are_published_to_a_listener
- ActiveSupport::Notifications.instrument(:awesome, :payload => "notifications") do
- 1 + 1
- end
+ class SyncPubSubTest < PubSubTest
+ def setup
+ Thread.abort_on_exception = true
- drain
-
- assert_equal 1, @events.size
- assert_equal :awesome, @events.last.name
- assert_equal Hash[:payload => "notifications"], @events.last.payload
+ @notifier = ActiveSupport::Notifications::Notifier.new(ActiveSupport::Notifications::Fanout.new(true))
+ @events = []
+ @notifier.subscribe { |*args| @events << event(*args) }
+ end
end
- def test_nested_events_can_be_instrumented
- ActiveSupport::Notifications.instrument(:awesome, :payload => "notifications") do
- ActiveSupport::Notifications.instrument(:wot, :payload => "child") do
- 1 + 1
- end
-
- drain
-
- assert_equal 1, @events.size
- assert_equal :wot, @events.first.name
- assert_equal Hash[:payload => "child"], @events.first.payload
+ class InstrumentationTest < TestCase
+ def test_instrument_returns_block_result
+ assert_equal 2, @notifier.instrument(:awesome) { 1 + 1 }
end
- drain
-
- assert_equal 2, @events.size
- assert_equal :awesome, @events.last.name
- assert_equal Hash[:payload => "notifications"], @events.last.payload
- end
-
- def test_event_is_pushed_even_if_block_fails
- ActiveSupport::Notifications.instrument(:awesome, :payload => "notifications") do
- raise "OMG"
- end rescue RuntimeError
+ def test_nested_events_can_be_instrumented
+ @notifier.instrument(:awesome, :payload => "notifications") do
+ @notifier.instrument(:wot, :payload => "child") do
+ 1 + 1
+ end
- drain
+ drain
- assert_equal 1, @events.size
- assert_equal :awesome, @events.last.name
- assert_equal Hash[:payload => "notifications"], @events.last.payload
- end
+ assert_equal 1, @events.size
+ assert_equal :wot, @events.first.name
+ assert_equal Hash[:payload => "child"], @events.first.payload
+ end
- def test_event_is_pushed_even_without_block
- ActiveSupport::Notifications.instrument(:awesome, :payload => "notifications")
- drain
+ drain
- assert_equal 1, @events.size
- assert_equal :awesome, @events.last.name
- assert_equal Hash[:payload => "notifications"], @events.last.payload
- end
+ assert_equal 2, @events.size
+ assert_equal :awesome, @events.last.name
+ assert_equal Hash[:payload => "notifications"], @events.last.payload
+ end
- def test_subscribed_in_a_transaction
- @another = []
+ def test_instrument_publishes_when_exception_is_raised
+ begin
+ @notifier.instrument(:awesome, :payload => "notifications") do
+ raise "OMG"
+ end
+ flunk
+ rescue
+ end
- ActiveSupport::Notifications.subscribe("cache") do |*args|
- @another << ActiveSupport::Notifications::Event.new(*args)
- end
+ drain
- ActiveSupport::Notifications.instrument(:cache){ 1 }
- ActiveSupport::Notifications.transaction do
- ActiveSupport::Notifications.instrument(:cache){ 1 }
+ assert_equal 1, @events.size
+ assert_equal :awesome, @events.last.name
+ assert_equal Hash[:payload => "notifications"], @events.last.payload
end
- ActiveSupport::Notifications.instrument(:cache){ 1 }
- drain
+ def test_event_is_pushed_even_without_block
+ @notifier.instrument(:awesome, :payload => "notifications")
+ drain
- assert_equal 3, @another.size
- before, during, after = @another.map {|e| e.transaction_id }
- assert_equal before, after
- assert_not_equal before, during
+ assert_equal 1, @events.size
+ assert_equal :awesome, @events.last.name
+ assert_equal Hash[:payload => "notifications"], @events.last.payload
+ end
end
- def test_subscriber_with_pattern
- @another = []
+ class EventTest < TestCase
+ def test_events_are_initialized_with_details
+ time = Time.now
+ event = event(:foo, time, time + 0.01, random_id, {})
- ActiveSupport::Notifications.subscribe("cache") do |*args|
- @another << ActiveSupport::Notifications::Event.new(*args)
+ assert_equal :foo, event.name
+ assert_equal time, event.time
+ assert_equal 10.0, event.duration
end
- ActiveSupport::Notifications.instrument(:cache){ 1 }
-
- drain
-
- assert_equal 1, @another.size
- assert_equal :cache, @another.first.name
- assert_equal 1, @another.first.result
- end
-
- def test_subscriber_with_pattern_as_regexp
- @another = []
- ActiveSupport::Notifications.subscribe(/cache/) do |*args|
- @another << ActiveSupport::Notifications::Event.new(*args)
+ def test_events_consumes_information_given_as_payload
+ event = event(:foo, Time.now, Time.now + 1, random_id, :payload => :bar)
+ assert_equal Hash[:payload => :bar], event.payload
end
- ActiveSupport::Notifications.instrument(:something){ 0 }
- ActiveSupport::Notifications.instrument(:cache){ 1 }
+ def test_event_is_parent_based_on_time_frame
+ time = Time.utc(2009, 01, 01, 0, 0, 1)
- drain
+ parent = event(:foo, Time.utc(2009), Time.utc(2009) + 100, random_id, {})
+ child = event(:foo, time, time + 10, random_id, {})
+ not_child = event(:foo, time, time + 100, random_id, {})
- assert_equal 1, @another.size
- assert_equal :cache, @another.first.name
- assert_equal 1, @another.first.result
- end
-
- def test_with_several_consumers_and_several_events
- @another = []
- ActiveSupport::Notifications.subscribe do |*args|
- @another << ActiveSupport::Notifications::Event.new(*args)
+ assert parent.parent_of?(child)
+ assert !child.parent_of?(parent)
+ assert !parent.parent_of?(not_child)
+ assert !not_child.parent_of?(parent)
end
- 1.upto(100) do |i|
- ActiveSupport::Notifications.instrument(:value){ i }
- end
-
- drain
-
- assert_equal 100, @events.size
- assert_equal :value, @events.first.name
- assert_equal 1, @events.first.result
- assert_equal 100, @events.last.result
-
- assert_equal 100, @another.size
- assert_equal :value, @another.first.name
- assert_equal 1, @another.first.result
- assert_equal 100, @another.last.result
+ protected
+ def random_id
+ @random_id ||= ActiveSupport::SecureRandom.hex(10)
+ end
end
-
- private
- def drain
- sleep(0.1) until ActiveSupport::Notifications.queue.drained?
- end
end
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
index 5cbffb81fc..1928da51ca 100644
--- a/activesupport/test/test_test.rb
+++ b/activesupport/test/test_test.rb
@@ -102,9 +102,9 @@ class SetupAndTeardownTest < ActiveSupport::TestCase
teardown :foo, :sentinel, :foo
def test_inherited_setup_callbacks
- assert_equal [:reset_callback_record, :foo], self.class.setup_callback_chain.map(&:method)
+ assert_equal [:reset_callback_record, :foo], self.class._setup_callbacks.map(&:raw_filter)
assert_equal [:foo], @called_back
- assert_equal [:foo, :sentinel, :foo], self.class.teardown_callback_chain.map(&:method)
+ assert_equal [:foo, :sentinel, :foo], self.class._teardown_callbacks.map(&:raw_filter)
end
def setup
@@ -114,6 +114,7 @@ class SetupAndTeardownTest < ActiveSupport::TestCase
end
protected
+
def reset_callback_record
@called_back = []
end
@@ -133,9 +134,9 @@ class SubclassSetupAndTeardownTest < SetupAndTeardownTest
teardown :bar
def test_inherited_setup_callbacks
- assert_equal [:reset_callback_record, :foo, :bar], self.class.setup_callback_chain.map(&:method)
+ assert_equal [:reset_callback_record, :foo, :bar], self.class._setup_callbacks.map(&:raw_filter)
assert_equal [:foo, :bar], @called_back
- assert_equal [:foo, :sentinel, :foo, :bar], self.class.teardown_callback_chain.map(&:method)
+ assert_equal [:foo, :sentinel, :foo, :bar], self.class._teardown_callbacks.map(&:raw_filter)
end
protected
diff --git a/activesupport/test/whiny_nil_test.rb b/activesupport/test/whiny_nil_test.rb
index 009d97940f..1e4f8d854a 100644
--- a/activesupport/test/whiny_nil_test.rb
+++ b/activesupport/test/whiny_nil_test.rb
@@ -13,38 +13,39 @@ class WhinyNilTest < Test::Unit::TestCase
def test_unchanged
nil.method_thats_not_in_whiners
rescue NoMethodError => nme
- assert(nme.message =~ /nil:NilClass/)
+ assert_match(/nil:NilClass/, nme.message)
end
def test_active_record
nil.save!
rescue NoMethodError => nme
- assert(!(nme.message =~ /nil:NilClass/))
+ assert_no_match(/nil:NilClass/, nme.message)
assert_match(/nil\.save!/, nme.message)
end
def test_array
nil.each
rescue NoMethodError => nme
- assert(!(nme.message =~ /nil:NilClass/))
+ assert_no_match(/nil:NilClass/, nme.message)
assert_match(/nil\.each/, nme.message)
end
def test_id
nil.id
rescue RuntimeError => nme
- assert(!(nme.message =~ /nil:NilClass/))
+ assert_no_match(/nil:NilClass/, nme.message)
end
def test_no_to_ary_coercion
nil.to_ary
rescue NoMethodError => nme
- assert(nme.message =~ /nil:NilClass/)
+ assert_no_match(/nil:NilClass/, nme.message)
+ assert_match(/nil\.to_ary/, nme.message)
end
def test_no_to_str_coercion
nil.to_str
rescue NoMethodError => nme
- assert(nme.message =~ /nil:NilClass/)
+ assert_match(/nil:NilClass/, nme.message)
end
end
diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb
index 900c8052d6..83d03bccc6 100644
--- a/activesupport/test/xml_mini/libxml_engine_test.rb
+++ b/activesupport/test/xml_mini/libxml_engine_test.rb
@@ -184,6 +184,15 @@ class LibxmlEngineTest < Test::Unit::TestCase
eoxml
end
+ def test_children_with_blank_text_and_attribute
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products type="file"> </products>
+ </root>
+ eoxml
+ end
+
+
private
def assert_equal_rexml(xml)
hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
diff --git a/activesupport/test/xml_mini/libxmlsax_engine_test.rb b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
new file mode 100644
index 0000000000..864810099e
--- /dev/null
+++ b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
@@ -0,0 +1,194 @@
+require 'abstract_unit'
+require 'active_support/xml_mini'
+require 'active_support/core_ext/hash/conversions'
+
+begin
+ require 'libxml'
+rescue LoadError
+ # Skip libxml tests
+else
+
+class LibXMLSAXEngineTest < Test::Unit::TestCase
+ include ActiveSupport
+
+ def setup
+ @default_backend = XmlMini.backend
+ XmlMini.backend = 'LibXMLSAX'
+ end
+
+ def teardown
+ XmlMini.backend = @default_backend
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise LibXML::XML::Error do
+ attack_xml = <<-EOT
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ EOT
+
+ Hash.from_xml(attack_xml)
+ end
+ end
+
+ def test_setting_libxml_as_backend
+ XmlMini.backend = 'LibXMLSAX'
+ assert_equal XmlMini_LibXMLSAX, XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, XmlMini.parse(nil))
+ assert_equal({}, XmlMini.parse(''))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_parse_from_io
+ io = StringIO.new(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ XmlMini.parse(io)
+ end
+
+ def test_children_with_simple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
+ morning
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ private
+ def assert_equal_rexml(xml)
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
+ assert_equal(hash, XmlMini.parse(xml))
+ end
+end
+
+end
diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb
index e16f36acee..db0d7c5b02 100644
--- a/activesupport/test/xml_mini/nokogiri_engine_test.rb
+++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb
@@ -159,17 +159,53 @@ class NokogiriEngineTest < Test::Unit::TestCase
XmlMini.parse(io)
end
- def test_children_with_cdata
+ def test_children_with_simple_cdata
assert_equal_rexml(<<-eoxml)
<root>
<products>
- hello <![CDATA[everyone]]>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
morning
</products>
</root>
eoxml
end
+ def test_children_with_blank_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text_and_attribute
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products type="file"> </products>
+ </root>
+ eoxml
+ end
+
private
def assert_equal_rexml(xml)
hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
diff --git a/activesupport/test/xml_mini/nokogirisax_engine_test.rb b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
new file mode 100644
index 0000000000..1149d0fecc
--- /dev/null
+++ b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
@@ -0,0 +1,217 @@
+require 'abstract_unit'
+require 'active_support/xml_mini'
+require 'active_support/core_ext/hash/conversions'
+
+begin
+ require 'nokogiri'
+rescue LoadError
+ # Skip nokogiri tests
+else
+
+class NokogiriSAXEngineTest < Test::Unit::TestCase
+ include ActiveSupport
+
+ def setup
+ @default_backend = XmlMini.backend
+ XmlMini.backend = 'NokogiriSAX'
+ end
+
+ def teardown
+ XmlMini.backend = @default_backend
+ end
+
+ def test_file_from_xml
+ hash = Hash.from_xml(<<-eoxml)
+ <blog>
+ <logo type="file" name="logo.png" content_type="image/png">
+ </logo>
+ </blog>
+ eoxml
+ assert hash.has_key?('blog')
+ assert hash['blog'].has_key?('logo')
+
+ file = hash['blog']['logo']
+ assert_equal 'logo.png', file.original_filename
+ assert_equal 'image/png', file.content_type
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise RuntimeError do
+ attack_xml = <<-EOT
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ EOT
+
+ Hash.from_xml(attack_xml)
+ end
+ end
+
+ def test_setting_nokogiri_as_backend
+ XmlMini.backend = 'Nokogiri'
+ assert_equal XmlMini_Nokogiri, XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, XmlMini.parse(nil))
+ assert_equal({}, XmlMini.parse(''))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_parse_from_io
+ io = StringIO.new(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ XmlMini.parse(io)
+ end
+
+ def test_children_with_simple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
+ morning
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text_and_attribute
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products type="file"> </products>
+ </root>
+ eoxml
+ end
+
+ private
+ def assert_equal_rexml(xml)
+ hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
+ assert_equal(hash, XmlMini.parse(xml))
+ end
+end
+
+end
diff --git a/ci/geminstaller.yml b/ci/geminstaller.yml
index 776ae8d98d..3dc2000bf9 100644
--- a/ci/geminstaller.yml
+++ b/ci/geminstaller.yml
@@ -5,4 +5,4 @@ gems:
- name: rubygems-update
version: >= 1.3.5
- name: bundler
- version: >= 0.6.0
+ version: >= 0.7.1
diff --git a/rack b/rack
new file mode 160000
+Subproject c6805fb93da30e0056b38e0fa6015c3d1bca587
diff --git a/rack-mount b/rack-mount
deleted file mode 160000
-Subproject 3784e633b42f43a4131e02519be60080d179da2
diff --git a/railties/rails.gemspec b/rails.gemspec
index dc66e1efea..878a342903 100644
--- a/railties/rails.gemspec
+++ b/rails.gemspec
@@ -8,22 +8,16 @@ Gem::Specification.new do |s|
on top of either MySQL, PostgreSQL, SQLite, DB2, SQL Server, or Oracle with eRuby- or Builder-based templates.
EOF
- s.add_dependency('rake', '>= 0.8.3')
s.add_dependency('activesupport', '= 3.0.pre')
- s.add_dependency('activerecord', '= 3.0.pre')
s.add_dependency('actionpack', '= 3.0.pre')
- s.add_dependency('actionmailer', '= 3.0.pre')
+ s.add_dependency('activerecord', '= 3.0.pre')
s.add_dependency('activeresource', '= 3.0.pre')
+ s.add_dependency('actionmailer', '= 3.0.pre')
+ s.add_dependency('railties', '= 3.0.pre')
s.rdoc_options << '--exclude' << '.'
s.has_rdoc = false
- s.files = Dir['CHANGELOG', 'README', 'bin/**/*', 'builtin/**/*', 'guides/**/*', 'lib/**/{*,.[a-z]*}']
- s.require_path = 'lib'
- s.bindir = "bin"
- s.executables = ["rails"]
- s.default_executable = "rails"
-
s.author = "David Heinemeier Hansson"
s.email = "david@loudthinking.com"
s.homepage = "http://www.rubyonrails.org"
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index d6311f77a0..0bc1ea32bc 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,5 +1,27 @@
*Edge*
+* Added default .gitignore (this is just recognizing Git market share, don't throw a hissy if you use another SCM) [DHH]
+
+* Added cookies.permanent, cookies.signed, and cookies.permanent.signed accessor for common cookie actions [DHH]. Examples:
+
+ cookies.permanent[:prefers_open_id] = true
+ # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+
+ cookies.signed[:discount] = 45
+ # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
+
+ cookies.signed[:discount]
+ # => 45 (if the cookie was changed, you'll get a InvalidSignature exception)
+
+ cookies.permanent.signed[:remember_me] = current_user.id
+ # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+
+ ...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications).
+
+* Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed [DHH]
+
+* Fixed that the debugger wouldn't go into IRB mode because of left-over ARGVs [DHH]
+
* I18n support for plugins. #2325 [Antonio Tapiador, Sven Fuchs]
* Ruby 1.9: use UTF-8 for default internal and external encodings. [Jeremy Kemper]
diff --git a/railties/Rakefile b/railties/Rakefile
index e6f698fc74..eff59f1f40 100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -1,3 +1,8 @@
+begin
+ require File.expand_path('../../vendor/gems/environment', __FILE__)
+rescue LoadError
+end
+
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
@@ -10,7 +15,7 @@ $LOAD_PATH.unshift "#{File.dirname(__FILE__)}/lib"
require 'rails/version'
PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : ''
-PKG_NAME = ENV['PKG_NAME'] || 'rails'
+PKG_NAME = 'railties'
PKG_VERSION = Rails::VERSION::STRING + PKG_BUILD
PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
PKG_DESTINATION = ENV["RAILS_PKG_DESTINATION"] || "../#{PKG_NAME}"
@@ -20,7 +25,6 @@ RELEASE_NAME = "REL #{PKG_VERSION}"
RUBY_FORGE_PROJECT = "rails"
RUBY_FORGE_USER = "webster132"
-
task :default => :test
task :test => 'test:isolated'
@@ -45,33 +49,6 @@ Rake::TestTask.new('test:regular') do |t|
t.verbose = true
end
-VENDOR_LIBS = %w( actionpack activerecord actionmailer activesupport activeresource railties )
-
-desc "Generates a fresh Rails package with documentation"
-task :fresh_rails => [ :clean, :create_rails, :copy_vendor_libraries, :generate_documentation ]
-
-desc "Generates a fresh Rails package using GEMs with documentation"
-task :fresh_gem_rails => [ :clean, :create_rails ]
-
-desc "Generates a fresh Rails package without documentation (faster)"
-task :fresh_rails_without_docs => [ :clean, :create_rails, :copy_vendor_libraries ]
-
-desc "Generates a fresh Rails package without documentation using links (faster)"
-task :fresh_rails_without_docs_using_links => [ :clean, :create_rails, :link_vendor_libraries ]
-
-desc "Generates minimal Rails package using symlinks"
-task :dev => [ :clean, :create_rails, :link_vendor_libraries ]
-
-desc "Packages the fresh Rails package with documentation"
-task :package => [ :clean, :fresh_rails ] do
- system %{cd ..; tar -czvf #{PKG_NAME}-#{PKG_VERSION}.tgz #{PKG_NAME}}
- system %{cd ..; zip -r #{PKG_NAME}-#{PKG_VERSION}.zip #{PKG_NAME}}
-end
-
-task :clean do
- rm_rf PKG_DESTINATION
-end
-
# Update spinoffs -------------------------------------------------------------------
desc "Updates application README to the latest version Railties README"
@@ -81,51 +58,14 @@ task :update_readme do
cp "./README", readme
end
-# Run application generator -------------------------------------------------------------
-
-task :create_rails do
- require 'rails/generators'
- require 'rails/generators/rails/app/app_generator'
- Rails::Generators::AppGenerator.start [ File.basename(PKG_DESTINATION), "--quiet" ],
- :destination_root => File.expand_path(File.dirname(PKG_DESTINATION))
-end
-
-# Copy Vendors ----------------------------------------------------------------------------
-
-desc "Copy in all the Rails packages to vendor"
-task :copy_vendor_libraries do
- mkdir File.join(PKG_DESTINATION, 'vendor', 'rails')
- VENDOR_LIBS.each { |dir| cp_r File.join('..', dir), File.join(PKG_DESTINATION, 'vendor', 'rails', dir) }
- FileUtils.rm_r(Dir.glob(File.join(PKG_DESTINATION, 'vendor', 'rails', "**", ".git")))
-end
-
-desc "Link in all the Rails packages to vendor"
-task :link_vendor_libraries do
- mkdir File.join(PKG_DESTINATION, 'vendor', 'rails')
- VENDOR_LIBS.each { |dir| ln_s File.join('..', '..', '..', dir), File.join(PKG_DESTINATION, 'vendor', 'rails', dir) }
-end
-
-
desc 'Generate guides (for authors), use ONLY=foo to process just "foo.textile"'
task :generate_guides do
ENV["WARN_BROKEN_LINKS"] = "1" # authors can't disable this
ruby "guides/rails_guides.rb"
end
-
# Generate documentation ------------------------------------------------------------------
-desc "Generate documentation for the framework and for the empty application"
-task :generate_documentation => [ :generate_app_doc, :generate_rails_framework_doc ]
-
-task :generate_rails_framework_doc do
- system %{cd #{PKG_DESTINATION}; rake doc:rails}
-end
-
-task :generate_app_doc do
- system %{cd #{PKG_DESTINATION}; rake doc:app}
-end
-
Rake::RDocTask.new { |rdoc|
rdoc.rdoc_dir = 'doc'
rdoc.title = "Railties -- Gluing the Engine to the Rails"
@@ -141,14 +81,14 @@ Rake::RDocTask.new { |rdoc|
# Generate GEM ----------------------------------------------------------------------------
-spec = eval(File.read('rails.gemspec'))
+spec = eval(File.read('railties.gemspec'))
Rake::GemPackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
end
-
# Publishing -------------------------------------------------------
+
desc "Publish the rails gem"
task :pgem => [:gem] do
require 'rake/contrib/sshpublisher'
diff --git a/railties/bin/rails b/railties/bin/rails
index 808df97429..b8b2d6188f 100755
--- a/railties/bin/rails
+++ b/railties/bin/rails
@@ -4,9 +4,10 @@ rescue LoadError
# If people are not using gems, the load path must still
# be correct.
# TODO: Remove the begin / rescue block somehow
- $:.unshift File.dirname(__FILE__) + '/../lib'
- $:.unshift File.dirname(__FILE__) + '/../../activesupport/lib'
- retry
+ $:.unshift File.expand_path('../../lib', __FILE__)
+ $:.unshift File.expand_path('../../../activesupport/lib', __FILE__)
+ $:.unshift File.expand_path('../../../actionpack/lib', __FILE__)
+ require 'rails/ruby_version_check'
end
Signal.trap("INT") { puts; exit }
@@ -19,7 +20,7 @@ end
ARGV << "--help" if ARGV.empty?
-require 'rails'
+
require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
diff --git a/railties/builtin/routes.rb b/railties/builtin/routes.rb
new file mode 100644
index 0000000000..ef9d9e756d
--- /dev/null
+++ b/railties/builtin/routes.rb
@@ -0,0 +1,3 @@
+ActionController::Routing::Routes.draw do |map|
+ match '/rails/info/properties' => "rails/info#properties"
+end \ No newline at end of file
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
index c23b67e321..d69e3eea6a 100644
--- a/railties/lib/rails.rb
+++ b/railties/lib/rails.rb
@@ -1,13 +1,106 @@
require "pathname"
+require 'active_support'
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/logger'
+require 'action_dispatch'
+
require 'rails/initializable'
require 'rails/application'
+require 'rails/railtie'
+require 'rails/plugin'
require 'rails/railties_path'
require 'rails/version'
require 'rails/rack'
require 'rails/paths'
-require 'rails/core'
require 'rails/configuration'
require 'rails/deprecation'
-require 'rails/initializer'
-require 'rails/plugin' \ No newline at end of file
+require 'rails/ruby_version_check'
+
+# For Ruby 1.8, this initialization sets $KCODE to 'u' to enable the
+# multibyte safe operations. Plugin authors supporting other encodings
+# should override this behaviour and set the relevant +default_charset+
+# on ActionController::Base.
+#
+# For Ruby 1.9, UTF-8 is the default internal and external encoding.
+if RUBY_VERSION < '1.9'
+ $KCODE='u'
+else
+ Encoding.default_external = Encoding::UTF_8
+end
+
+RAILS_ENV = (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup unless defined?(RAILS_ENV)
+
+module Rails
+ # Needs to be duplicated from Active Support since its needed before Active
+ # Support is available. Here both Options and Hash are namespaced to prevent
+ # conflicts with other implementations AND with the classes residing in Active Support.
+ # ---
+ # TODO: w0t?
+ class << self
+ def application
+ @@application ||= nil
+ end
+
+ def application=(application)
+ @@application = application
+ end
+
+ # The Configuration instance used to configure the Rails environment
+ def configuration
+ application.configuration
+ end
+
+ def initialize!
+ application.initialize!
+ end
+
+ def initialized?
+ @initialized || false
+ end
+
+ def initialized=(initialized)
+ @initialized ||= initialized
+ end
+
+ def logger
+ if defined?(RAILS_DEFAULT_LOGGER)
+ RAILS_DEFAULT_LOGGER
+ else
+ nil
+ end
+ end
+
+ def backtrace_cleaner
+ @@backtrace_cleaner ||= begin
+ # Relies on ActiveSupport, so we have to lazy load to postpone definition until AS has been loaded
+ require 'rails/backtrace_cleaner'
+ Rails::BacktraceCleaner.new
+ end
+ end
+
+ def root
+ application && application.config.root
+ end
+
+ def env
+ @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
+ end
+
+ def cache
+ RAILS_CACHE
+ end
+
+ def version
+ VERSION::STRING
+ end
+
+ def public_path
+ @@public_path ||= self.root ? File.join(self.root, "public") : "public"
+ end
+
+ def public_path=(path)
+ @@public_path = path
+ end
+ end
+end
diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb
new file mode 100644
index 0000000000..7dfe2b8b63
--- /dev/null
+++ b/railties/lib/rails/all.rb
@@ -0,0 +1,15 @@
+require "rails"
+
+%w(
+ active_model
+ active_record
+ action_controller
+ action_view
+ action_mailer
+ active_resource
+).each do |framework|
+ begin
+ require "#{framework}/railtie"
+ rescue LoadError
+ end
+end \ No newline at end of file
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 7c2d8eab67..5401251397 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -1,58 +1,85 @@
+require "fileutils"
+require 'active_support/core_ext/module/delegation'
+
module Rails
class Application
include Initializable
class << self
- def inherited(klass)
- Rails.application ||= klass unless klass.name =~ /Rails/
- super
- end
+ attr_writer :config
+ alias configure class_eval
+ delegate :initialize!, :load_tasks, :root, :to => :instance
- # Stub out App initialize
- def initialize!
- new
- end
-
- def new
- @instance ||= super
+ private :new
+ def instance
+ @instance ||= new
end
def config
- @config ||= Configuration.new
+ @config ||= Configuration.new(Plugin::Configuration.default)
end
- # TODO: change the plugin loader to use config
- alias configuration config
-
- def config=(config)
- @config = config
+ def routes
+ ActionController::Routing::Routes
end
+ end
- def root
- config.root
- end
+ delegate :config, :routes, :to => :'self.class'
+ delegate :root, :middleware, :to => :config
+ attr_reader :route_configuration_files
- def call(env)
- new.call(env)
- end
+ def initialize
+ require_environment
+ Rails.application ||= self
+ @route_configuration_files = []
end
- def initialize
+ def initialize!
run_initializers(self)
+ self
end
- def config
- self.class.config
+ def require_environment
+ require config.environment_path
+ rescue LoadError
end
- alias configuration config
+ def routes_changed_at
+ routes_changed_at = nil
- def middleware
- config.middleware
+ route_configuration_files.each do |config|
+ config_changed_at = File.stat(config).mtime
+
+ if routes_changed_at.nil? || config_changed_at > routes_changed_at
+ routes_changed_at = config_changed_at
+ end
+ end
+
+ routes_changed_at
+ end
+
+ def reload_routes!
+ routes.disable_clear_and_finalize = true
+
+ routes.clear!
+ route_configuration_files.each { |config| load(config) }
+ routes.finalize!
+
+ nil
+ ensure
+ routes.disable_clear_and_finalize = false
end
- def routes
- ActionController::Routing::Routes
+ def load_tasks
+ require "rails/tasks"
+ plugins.each { |p| p.load_tasks }
+ # Load all application tasks
+ # TODO: extract out the path to the rake tasks
+ Dir["#{root}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
+ task :environment do
+ $rails_rake_task = true
+ initialize!
+ end
end
def initializers
@@ -61,9 +88,12 @@ module Rails
initializers
end
+ # TODO: Fix this method
def plugins
@plugins ||= begin
- Plugin::Vendored.all(config.plugins || [:all], config.paths.vendor.plugins)
+ plugin_names = config.plugins || [:all]
+ Railtie.plugins.select { |p| plugin_names.include?(:all) || plugin_names.include?(p.plugin_name) }.map { |p| p.new } +
+ Plugin.all(config.plugins || [:all], config.paths.vendor.plugins)
end
end
@@ -72,8 +102,8 @@ module Rails
@app.call(env)
end
- initializer :initialize_rails do
- Rails.run_initializers
+ initializer :load_all_active_support do
+ require "active_support/all" unless config.active_support.bare
end
# Set the <tt>$LOAD_PATH</tt> based on the value of
@@ -83,24 +113,6 @@ module Rails
$LOAD_PATH.uniq!
end
- # Requires all frameworks specified by the Configuration#frameworks
- # list. By default, all frameworks (Active Record, Active Support,
- # Action Pack, Action Mailer, and Active Resource) are loaded.
- initializer :require_frameworks do
- begin
- require 'active_support'
- require 'active_support/core_ext/kernel/reporting'
- require 'active_support/core_ext/logger'
-
- # TODO: This is here to make Sam Ruby's tests pass. Needs discussion.
- require 'active_support/core_ext/numeric/bytes'
- config.frameworks.each { |framework| require(framework.to_s) }
- rescue LoadError => e
- # Re-raise as RuntimeError because Mongrel would swallow LoadError.
- raise e.to_s
- end
- end
-
# Set the paths from which Rails will automatically load source files, and
# the load_once paths.
initializer :set_autoload_paths do
@@ -123,25 +135,7 @@ module Rails
# Create tmp directories
initializer :ensure_tmp_directories_exist do
%w(cache pids sessions sockets).each do |dir_to_make|
- FileUtils.mkdir_p(File.join(config.root, 'tmp', dir_to_make))
- end
- end
-
- # Loads the environment specified by Configuration#environment_path, which
- # is typically one of development, test, or production.
- initializer :load_environment do
- silence_warnings do
- next if @environment_loaded
- next unless File.file?(config.environment_path)
-
- @environment_loaded = true
- constants = self.class.constants
-
- eval(IO.read(config.environment_path), binding, config.environment_path)
-
- (self.class.constants - constants).each do |const|
- Object.const_set(const, self.class.const_get(const))
- end
+ FileUtils.mkdir_p(File.join(root, 'tmp', dir_to_make))
end
end
@@ -149,44 +143,7 @@ module Rails
# Used by Passenger to ensure everything's loaded before forking and
# to avoid autoload race conditions in JRuby.
initializer :preload_frameworks do
- if config.preload_frameworks
- config.frameworks.each do |framework|
- # String#classify and #constantize aren't available yet.
- toplevel = Object.const_get(framework.to_s.gsub(/(?:^|_)(.)/) { $1.upcase })
- toplevel.load_all! if toplevel.respond_to?(:load_all!)
- end
- end
- end
-
- # This initialization routine does nothing unless <tt>:active_record</tt>
- # is one of the frameworks to load (Configuration#frameworks). If it is,
- # this sets the database configuration from Configuration#database_configuration
- # and then establishes the connection.
- initializer :initialize_database do
- if config.frameworks.include?(:active_record)
- ActiveRecord::Base.configurations = config.database_configuration
- ActiveRecord::Base.establish_connection
- end
- end
-
- # Include middleware to serve up static assets
- initializer :initialize_static_server do
- if config.frameworks.include?(:action_controller) && config.serve_static_assets
- config.middleware.use(ActionDispatch::Static, Rails.public_path)
- end
- end
-
- initializer :initialize_middleware_stack do
- if config.frameworks.include?(:action_controller)
- config.middleware.use(::Rack::Lock) unless ActionController::Base.allow_concurrency
- config.middleware.use(ActionDispatch::ShowExceptions, ActionController::Base.consider_all_requests_local)
- config.middleware.use(ActionDispatch::Callbacks, ActionController::Dispatcher.prepare_each_request)
- config.middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
- config.middleware.use(ActionDispatch::ParamsParser)
- config.middleware.use(::Rack::MethodOverride)
- config.middleware.use(::Rack::Head)
- config.middleware.use(ActionDispatch::StringCoercion)
- end
+ ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
end
initializer :initialize_cache do
@@ -200,12 +157,6 @@ module Rails
end
end
- initializer :initialize_framework_caches do
- if config.frameworks.include?(:action_controller)
- ActionController::Base.cache_store ||= RAILS_CACHE
- end
- end
-
initializer :initialize_logger do
# if the environment has explicitly defined a logger, use it
next if Rails.logger
@@ -236,10 +187,6 @@ module Rails
# logger is already set, it is not changed, otherwise it is set to use
# RAILS_DEFAULT_LOGGER.
initializer :initialize_framework_logging do
- for framework in ([ :active_record, :action_controller, :action_mailer ] & config.frameworks)
- framework.to_s.camelize.constantize.const_get("Base").logger ||= Rails.logger
- end
-
ActiveSupport::Dependencies.logger ||= Rails.logger
Rails.cache.logger ||= Rails.logger
end
@@ -257,7 +204,7 @@ module Rails
require('active_support/whiny_nil') if config.whiny_nils
end
- # Sets the default value for Time.zone, and turns on ActiveRecord::Base#time_zone_aware_attributes.
+ # Sets the default value for Time.zone
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
initializer :initialize_time_zone do
if config.time_zone
@@ -271,11 +218,6 @@ module Rails
end
Time.zone_default = zone_default
-
- if config.frameworks.include?(:active_record)
- ActiveRecord::Base.time_zone_aware_attributes = true
- ActiveRecord::Base.default_timezone = :utc
- end
end
end
@@ -291,110 +233,28 @@ module Rails
end
end
- # Initializes framework-specific settings for each of the loaded frameworks
- # (Configuration#frameworks). The available settings map to the accessors
- # on each of the corresponding Base classes.
- initializer :initialize_framework_settings do
- config.frameworks.each do |framework|
- base_class = framework.to_s.camelize.constantize.const_get("Base")
-
- config.send(framework).each do |setting, value|
- base_class.send("#{setting}=", value)
- end
- end
- config.active_support.each do |setting, value|
- ActiveSupport.send("#{setting}=", value)
- end
- end
-
- # Sets +ActionController::Base#view_paths+ and +ActionMailer::Base#template_root+
- # (but only for those frameworks that are to be loaded). If the framework's
- # paths have already been set, it is not changed, otherwise it is
- # set to use Configuration#view_path.
- initializer :initialize_framework_views do
- if config.frameworks.include?(:action_view)
- view_path = ActionView::PathSet.type_cast(config.view_path, config.cache_classes)
- ActionMailer::Base.template_root = view_path if config.frameworks.include?(:action_mailer) && ActionMailer::Base.view_paths.blank?
- ActionController::Base.view_paths = view_path if config.frameworks.include?(:action_controller) && ActionController::Base.view_paths.blank?
- end
- end
-
- initializer :initialize_metal do
- # TODO: Make Rails and metal work without ActionController
- if config.frameworks.include?(:action_controller)
- Rails::Rack::Metal.requested_metals = config.metals
-
- config.middleware.insert_before(
- :"ActionDispatch::ParamsParser",
- Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?)
- end
- end
-
# # bail out if gems are missing - note that check_gem_dependencies will have
# # already called abort() unless $gems_rake_task is set
# return unless gems_dependencies_loaded
initializer :load_application_initializers do
- Dir["#{configuration.root}/config/initializers/**/*.rb"].sort.each do |initializer|
+ Dir["#{root}/config/initializers/**/*.rb"].sort.each do |initializer|
load(initializer)
end
end
# Fires the user-supplied after_initialize block (Configuration#after_initialize)
initializer :after_initialize do
- configuration.after_initialize_blocks.each do |block|
+ config.after_initialize_blocks.each do |block|
block.call
end
end
- # # Setup database middleware after initializers have run
- initializer :initialize_database_middleware do
- if configuration.frameworks.include?(:active_record)
- if configuration.frameworks.include?(:action_controller) && ActionController::Base.session_store &&
- ActionController::Base.session_store.name == 'ActiveRecord::SessionStore'
- configuration.middleware.insert_before :"ActiveRecord::SessionStore", ActiveRecord::ConnectionAdapters::ConnectionManagement
- configuration.middleware.insert_before :"ActiveRecord::SessionStore", ActiveRecord::QueryCache
- else
- configuration.middleware.use ActiveRecord::ConnectionAdapters::ConnectionManagement
- configuration.middleware.use ActiveRecord::QueryCache
- end
- end
- end
-
- # TODO: Make a DSL way to limit an initializer to a particular framework
-
- # # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer :prepare_dispatcher do
- next unless configuration.frameworks.include?(:action_controller)
- require 'rails/dispatcher' unless defined?(::Dispatcher)
- Dispatcher.define_dispatcher_callbacks(configuration.cache_classes)
- end
-
- # Routing must be initialized after plugins to allow the former to extend the routes
- # ---
- # If Action Controller is not one of the loaded frameworks (Configuration#frameworks)
- # this does nothing. Otherwise, it loads the routing definitions and sets up
- # loading module used to lazily load controllers (Configuration#controller_paths).
- initializer :initialize_routing do
- next unless configuration.frameworks.include?(:action_controller)
-
- ActionController::Routing.controller_paths += configuration.controller_paths
- ActionController::Routing::Routes.add_configuration_file(configuration.routes_configuration_file)
- ActionController::Routing::Routes.reload!
- end
- #
- # # Observers are loaded after plugins in case Observers or observed models are modified by plugins.
- initializer :load_observers do
- if configuration.frameworks.include?(:active_record)
- ActiveRecord::Base.instantiate_observers
- end
- end
-
# Eager load application classes
initializer :load_application_classes do
next if $rails_rake_task
- if configuration.cache_classes
- configuration.eager_load_paths.each do |load_path|
+ if config.cache_classes
+ config.eager_load_paths.each do |load_path|
matcher = /\A#{Regexp.escape(load_path)}(.*)\.rb\Z/
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
require_dependency file.sub(matcher, '\1')
@@ -405,20 +265,9 @@ module Rails
# Disable dependency loading during request cycle
initializer :disable_dependency_loading do
- if configuration.cache_classes && !configuration.dependency_loading
+ if config.cache_classes && !config.dependency_loading
ActiveSupport::Dependencies.unhook!
end
end
-
- # For each framework, search for instrument file with Notifications hooks.
- #
- initializer :load_notifications_hooks do
- config.frameworks.each do |framework|
- begin
- require "#{framework}/notifications"
- rescue LoadError => e
- end
- end
- end
end
end
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index b977b7162f..37eb6d40ea 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -1,45 +1,56 @@
-irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
-
require 'optparse'
+require 'irb'
+require "irb/completion"
-options = { :sandbox => false, :irb => irb }
-OptionParser.new do |opt|
- opt.banner = "Usage: console [environment] [options]"
- opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
- opt.on("--irb=[#{irb}]", 'Invoke a different irb.') { |v| options[:irb] = v }
- opt.on("--debugger", 'Enable ruby-debugging for the console.') { |v| options[:debugger] = v }
- opt.parse!(ARGV)
-end
+module Rails
+ class Console
+ ENVIRONMENTS = %w(production development test)
-libs = " -r irb/completion"
-libs << %( -r "#{Rails.root}/config/environment")
-libs << " -r rails/console_app"
-libs << " -r rails/console_sandbox" if options[:sandbox]
-libs << " -r rails/console_with_helpers"
-
-if options[:debugger]
- begin
- require 'ruby-debug'
- libs << " -r ruby-debug"
- puts "=> Debugger enabled"
- rescue Exception
- puts "You need to install ruby-debug to run the console in debugging mode. With gems, use 'gem install ruby-debug'"
- exit
- end
-end
+ def self.start(app)
+ new(app).start
+ end
-ENV['RAILS_ENV'] = case ARGV.first
- when "p"; "production"
- when "d"; "development"
- when "t"; "test"
- else
- ARGV.first || ENV['RAILS_ENV'] || 'development'
-end
+ def initialize(app)
+ @app = app
+ end
+
+ def start
+ options = {}
-if options[:sandbox]
- puts "Loading #{ENV['RAILS_ENV']} environment in sandbox (Rails #{Rails.version})"
- puts "Any modifications you make will be rolled back on exit"
-else
- puts "Loading #{ENV['RAILS_ENV']} environment (Rails #{Rails.version})"
+ OptionParser.new do |opt|
+ opt.banner = "Usage: console [environment] [options]"
+ opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
+ opt.on("--debugger", 'Enable ruby-debugging for the console.') { |v| options[:debugger] = v }
+ opt.on('--irb') { |v| abort '--irb option is no longer supported. Invoke `/your/choice/of/ruby script/console` instead' }
+ opt.parse!(ARGV)
+ end
+
+ if env = ARGV.first
+ ENV['RAILS_ENV'] = ENVIRONMENTS.find { |e| e.index(env) } || env
+ end
+
+ @app.initialize!
+ require "rails/console_app"
+ require "rails/console_sandbox" if options[:sandbox]
+ require "rails/console_with_helpers"
+
+ if options[:debugger]
+ begin
+ require 'ruby-debug'
+ puts "=> Debugger enabled"
+ rescue Exception
+ puts "You need to install ruby-debug to run the console in debugging mode. With gems, use 'gem install ruby-debug'"
+ exit
+ end
+ end
+
+ if options[:sandbox]
+ puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})"
+ puts "Any modifications you make will be rolled back on exit"
+ else
+ puts "Loading #{Rails.env} environment (Rails #{Rails.version})"
+ end
+ IRB.start
+ end
+ end
end
-exec "#{options[:irb]} #{libs} --simple-prompt"
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 4e699acf6b..77c3404343 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -2,86 +2,99 @@ require 'erb'
require 'yaml'
require 'optparse'
-include_password = false
-options = {}
-
-OptionParser.new do |opt|
- opt.banner = "Usage: dbconsole [options] [environment]"
- opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
- include_password = true
- end
-
- opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'],
- "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode|
- options['mode'] = mode
- end
-
- opt.on("-h", "--header") do |h|
- options['header'] = h
- end
-
- opt.parse!(ARGV)
- abort opt.to_s unless (0..1).include?(ARGV.size)
-end
-
-env = ARGV.first || ENV['RAILS_ENV'] || 'development'
-unless config = YAML::load(ERB.new(IO.read(Rails.root + "/config/database.yml")).result)[env]
- abort "No database is configured for the environment '#{env}'"
-end
-
+module Rails
+ class DBConsole
+ def self.start(app)
+ new(app).start
+ end
-def find_cmd(*commands)
- dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
- commands += commands.map{|cmd| "#{cmd}.exe"} if RUBY_PLATFORM =~ /win32/
+ def initialize(app)
+ @app = app
+ end
- full_path_command = nil
- found = commands.detect do |cmd|
- dir = dirs_on_path.detect do |path|
- full_path_command = File.join(path, cmd)
- File.executable? full_path_command
+ def start
+ include_password = false
+ options = {}
+ OptionParser.new do |opt|
+ opt.banner = "Usage: dbconsole [options] [environment]"
+ opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
+ include_password = true
+ end
+
+ opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'],
+ "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode|
+ options['mode'] = mode
+ end
+
+ opt.on("-h", "--header") do |h|
+ options['header'] = h
+ end
+
+ opt.parse!(ARGV)
+ abort opt.to_s unless (0..1).include?(ARGV.size)
+ end
+
+ env = ARGV.first || ENV['RAILS_ENV'] || 'development'
+ unless config = YAML::load(ERB.new(IO.read("#{@app.root}/config/database.yml")).result)[env]
+ abort "No database is configured for the environment '#{env}'"
+ end
+
+
+ def find_cmd(*commands)
+ dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
+ commands += commands.map{|cmd| "#{cmd}.exe"} if RUBY_PLATFORM =~ /win32/
+
+ full_path_command = nil
+ found = commands.detect do |cmd|
+ dir = dirs_on_path.detect do |path|
+ full_path_command = File.join(path, cmd)
+ File.executable? full_path_command
+ end
+ end
+ found ? full_path_command : abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
+ end
+
+ case config["adapter"]
+ when "mysql"
+ args = {
+ 'host' => '--host',
+ 'port' => '--port',
+ 'socket' => '--socket',
+ 'username' => '--user',
+ 'encoding' => '--default-character-set'
+ }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
+
+ if config['password'] && include_password
+ args << "--password=#{config['password']}"
+ elsif config['password'] && !config['password'].to_s.empty?
+ args << "-p"
+ end
+
+ args << config['database']
+
+ exec(find_cmd('mysql', 'mysql5'), *args)
+
+ when "postgresql"
+ ENV['PGUSER'] = config["username"] if config["username"]
+ ENV['PGHOST'] = config["host"] if config["host"]
+ ENV['PGPORT'] = config["port"].to_s if config["port"]
+ ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
+ exec(find_cmd('psql'), config["database"])
+
+ when "sqlite"
+ exec(find_cmd('sqlite'), config["database"])
+
+ when "sqlite3"
+ args = []
+
+ args << "-#{options['mode']}" if options['mode']
+ args << "-header" if options['header']
+ args << config['database']
+
+ exec(find_cmd('sqlite3'), *args)
+ else
+ abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
+ end
end
end
- found ? full_path_command : abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
-end
-
-case config["adapter"]
-when "mysql"
- args = {
- 'host' => '--host',
- 'port' => '--port',
- 'socket' => '--socket',
- 'username' => '--user',
- 'encoding' => '--default-character-set'
- }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
-
- if config['password'] && include_password
- args << "--password=#{config['password']}"
- elsif config['password'] && !config['password'].to_s.empty?
- args << "-p"
- end
-
- args << config['database']
-
- exec(find_cmd('mysql', 'mysql5'), *args)
-
-when "postgresql"
- ENV['PGUSER'] = config["username"] if config["username"]
- ENV['PGHOST'] = config["host"] if config["host"]
- ENV['PGPORT'] = config["port"].to_s if config["port"]
- ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
- exec(find_cmd('psql'), config["database"])
-
-when "sqlite"
- exec(find_cmd('sqlite'), config["database"])
-
-when "sqlite3"
- args = []
-
- args << "-#{options['mode']}" if options['mode']
- args << "-header" if options['header']
- args << config['database']
-
- exec(find_cmd('sqlite3'), *args)
-else
- abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
-end
+end \ No newline at end of file
diff --git a/railties/lib/rails/commands/ncgi/tracker b/railties/lib/rails/commands/ncgi/tracker
deleted file mode 100755
index 4ca12d779b..0000000000
--- a/railties/lib/rails/commands/ncgi/tracker
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/env ruby
-
-require 'drb'
-require 'thread'
-
-def message(s)
- $stderr.puts "tracker: #{s}" if ENV && ENV["DEBUG_GATEWAY"]
-end
-
-class Tracker
- include DRbUndumped
-
- def initialize(instances, socket_path)
- @instances = instances
- @socket = File.expand_path(socket_path)
- @active = false
-
- @listeners = []
- @instances.times { @listeners << Mutex.new }
-
- message "using #{@listeners.length} listeners"
- message "opening socket at #{@socket}"
-
- @service = DRb.start_service("drbunix://#{@socket}", self)
- end
-
- def with_listener
- message "listener requested"
-
- mutex = has_lock = index = nil
- 3.times do
- @listeners.each_with_index do |mutex, index|
- has_lock = mutex.try_lock
- break if has_lock
- end
- break if has_lock
- sleep 0.05
- end
-
- if has_lock
- message "obtained listener #{index}"
- @active = true
- begin yield index
- ensure
- mutex.unlock
- message "released listener #{index}"
- end
- else
- message "dropping request because no listeners are available!"
- end
- end
-
- def background(check_interval = nil)
- if check_interval
- loop do
- sleep check_interval
- message "Idle for #{check_interval}, shutting down" unless @active
- @active = false
- Kernel.exit 0
- end
- else DRb.thread.join
- end
- end
-end
-
-socket_path = ARGV.shift
-instances = ARGV.shift.to_i
-t = Tracker.new(instances, socket_path)
-t.background(ARGV.first ? ARGV.shift.to_i : 90)
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index 2c90851fb2..09d7207d51 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -1,73 +1,76 @@
-require 'action_dispatch'
-
require 'fileutils'
require 'optparse'
+require 'action_dispatch'
-options = {
- :Port => 3000,
- :Host => "0.0.0.0",
- :environment => (ENV['RAILS_ENV'] || "development").dup,
- :config => "#{Rails.root}/config.ru",
- :detach => false,
- :debugger => false
-}
-
-ARGV.clone.options do |opts|
- opts.on("-p", "--port=port", Integer,
- "Runs Rails on the specified port.", "Default: #{options[:Port]}") { |v| options[:Port] = v }
- opts.on("-b", "--binding=ip", String,
- "Binds Rails to the specified ip.", "Default: #{options[:Host]}") { |v| options[:Host] = v }
- opts.on("-c", "--config=file", String,
- "Use custom rackup configuration file") { |v| options[:config] = v }
- opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:detach] = true }
- opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { options[:debugger] = true }
- opts.on("-e", "--environment=name", String,
- "Specifies the environment to run this server under (test/development/production).",
- "Default: #{options[:environment]}") { |v| options[:environment] = v }
-
- opts.separator ""
+module Rails
+ class Server < ::Rack::Server
+ class Options
+ def parse!(args)
+ options = {}
+ args = args.dup
+ opt_parser = OptionParser.new do |opts|
+ opts.on("-p", "--port=port", Integer,
+ "Runs Rails on the specified port.", "Default: #{options[:Port]}") { |v| options[:Port] = v }
+ opts.on("-b", "--binding=ip", String,
+ "Binds Rails to the specified ip.", "Default: #{options[:Host]}") { |v| options[:Host] = v }
+ opts.on("-c", "--config=file", String,
+ "Use custom rackup configuration file") { |v| options[:config] = v }
+ opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:daemonize] = true }
+ opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { options[:debugger] = true }
+ opts.on("-e", "--environment=name", String,
+ "Specifies the environment to run this server under (test/development/production).",
+ "Default: #{options[:environment]}") { |v| options[:environment] = v }
- opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
+ opts.separator ""
- opts.parse!
-end
+ opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
+ end
-server = Rack::Handler.get(ARGV.first) rescue nil
-unless server
- begin
- server = Rack::Handler::Mongrel
- rescue LoadError => e
- server = Rack::Handler::WEBrick
- end
-end
+ opt_parser.parse! args
-puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
-puts "=> Rails #{Rails.version} application starting on http://#{options[:Host]}:#{options[:Port]}"
+ options[:server] = args.shift
+ options
+ end
+ end
-if options[:detach]
- Process.daemon
- pid = "#{Rails.root}/tmp/pids/server.pid"
- File.open(pid, 'w'){ |f| f.write(Process.pid) }
- at_exit { File.delete(pid) if File.exist?(pid) }
-end
+ def opt_parser
+ Options.new
+ end
-ENV["RAILS_ENV"] = options[:environment]
-RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV)
+ def start
+ puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
+ puts "=> Rails #{Rails.version} application starting 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]
-app = Rack::Builder.new {
- use Rails::Rack::LogTailer unless options[:detach]
- use Rails::Rack::Debugger if options[:debugger]
- run ActionDispatch::Utils.parse_config(options[:config])
-}.to_app
+ ENV["RAILS_ENV"] = options[:environment]
+ RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV)
-puts "=> Call with -d to detach"
+ super
+ ensure
+ puts 'Exiting' unless options[:daemonize]
+ end
-trap(:INT) { exit }
+ def middleware
+ middlewares = []
+ middlewares << [Rails::Rack::LogTailer, log_path] unless options[:daemonize]
+ middlewares << [Rails::Rack::Debugger] if options[:debugger]
+ Hash.new(middlewares)
+ end
-puts "=> Ctrl-C to shutdown server"
+ def log_path
+ "log/#{options[:environment]}.log"
+ end
-begin
- server.run(app, options.merge(:AccessLog => []))
-ensure
- puts 'Exiting'
+ def default_options
+ super.merge({
+ :Port => 3000,
+ :environment => (ENV['RAILS_ENV'] || "development").dup,
+ :daemonize => false,
+ :debugger => false,
+ :pid => "tmp/pids/server.pid"
+ })
+ end
+ end
end
diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb
index 102a0836dc..f0a0d5e55e 100644
--- a/railties/lib/rails/configuration.rb
+++ b/railties/lib/rails/configuration.rb
@@ -1,27 +1,74 @@
require 'active_support/ordered_options'
module Rails
- class Configuration
- attr_accessor :cache_classes, :load_paths, :load_once_paths, :after_initialize_blocks,
- :frameworks, :framework_root_path, :root, :gems, :plugins,
- :i18n, :gems, :whiny_nils, :consider_all_requests_local,
- :action_controller, :active_record, :action_view, :active_support,
- :action_mailer, :active_resource,
- :reload_plugins, :log_path, :log_level, :logger, :preload_frameworks,
- :database_configuration_file, :cache_store, :time_zone,
- :view_path, :metals, :controller_paths, :routes_configuration_file,
- :eager_load_paths, :dependency_loading, :paths, :serve_static_assets
-
- def initialize
+ # Temporarily separate the plugin configuration class from the main
+ # configuration class while this bit is being cleaned up.
+ class Railtie::Configuration
+
+ def self.default
+ @default ||= new
+ end
+
+ attr_reader :middleware
+
+ 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 = ActionDispatch::MiddlewareStack.new
+ end
+ end
+
+ def respond_to?(name)
+ super || name.to_s =~ config_key_regexp
+ end
+
+ protected
+
+ attr_reader :options
+
+ private
+
+ def method_missing(name, *args, &blk)
+ if name.to_s =~ config_key_regexp
+ return $2 == '=' ? @options[$1] = args.first : @options[$1]
+ end
+
+ super
+ end
+
+ def config_key_regexp
+ bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
+ /^(#{bits})(?:=)?$/
+ end
+
+ def config_keys
+ ([ :active_support, :action_view ] +
+ Railtie.plugin_names).map { |n| n.to_s }.uniq
+ end
+ end
+
+ class Configuration < Railtie::Configuration
+ attr_accessor :after_initialize_blocks, :cache_classes,
+ :consider_all_requests_local, :dependency_loading, :gems,
+ :load_once_paths, :logger, :metals, :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
+
+ def initialize(base = nil)
+ super
@load_once_paths = []
@after_initialize_blocks = []
@dependency_loading = true
@serve_static_assets = true
-
- for framework in frameworks
- self.send("#{framework}=", ActiveSupport::OrderedOptions.new)
- end
- self.active_support = ActiveSupport::OrderedOptions.new
end
def after_initialize(&blk)
@@ -31,7 +78,7 @@ module Rails
def root
@root ||= begin
call_stack = caller.map { |p| p.split(':').first }
- root_path = call_stack.detect { |p| p !~ %r[railties/lib/rails] }
+ root_path = call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] }
root_path = File.dirname(root_path)
while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/config.ru")
@@ -72,6 +119,13 @@ module Rails
end
end
+ 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
+
# Enable threaded mode. Allows concurrent requests to controller actions and
# multiple database connections. Also disables automatic dependency loading
# after boot, and disables reloading code on every request, as these are
@@ -80,28 +134,11 @@ module Rails
self.preload_frameworks = true
self.cache_classes = true
self.dependency_loading = false
- self.action_controller.allow_concurrency = true
- self
- end
- def framework_paths
- paths = %w(railties railties/lib activesupport/lib)
- paths << 'actionpack/lib' if frameworks.include?(:action_controller) || frameworks.include?(:action_view)
-
- [:active_record, :action_mailer, :active_resource, :action_web_service].each do |framework|
- paths << "#{framework.to_s.gsub('_', '')}/lib" if frameworks.include?(framework)
+ if respond_to?(:action_controller)
+ action_controller.allow_concurrency = true
end
-
- paths.map { |dir| "#{framework_root_path}/#{dir}" }.select { |dir| File.directory?(dir) }
- end
-
- def framework_root_path
- defined?(::RAILS_FRAMEWORK_ROOT) ? ::RAILS_FRAMEWORK_ROOT : "#{root}/vendor/rails"
- end
-
- def middleware
- require 'action_dispatch'
- @middleware ||= ActionDispatch::MiddlewareStack.new
+ self
end
# Loads and returns the contents of the #database_configuration_file. The
@@ -116,6 +153,10 @@ module Rails
@routes_configuration_file ||= File.join(root, 'config', 'routes.rb')
end
+ def builtin_routes_configuration_file
+ @builtin_routes_configuration_file ||= File.join(RAILTIES_PATH, 'builtin', 'routes.rb')
+ end
+
def controller_paths
@controller_paths ||= begin
paths = [File.join(root, 'app', 'controllers')]
@@ -190,10 +231,6 @@ module Rails
@log_level ||= RAILS_ENV == 'production' ? :info : :debug
end
- def frameworks
- @frameworks ||= [ :active_record, :action_controller, :action_view, :action_mailer, :active_resource ]
- end
-
def i18n
@i18n ||= begin
i18n = ActiveSupport::OrderedOptions.new
diff --git a/railties/lib/rails/console_app.rb b/railties/lib/rails/console_app.rb
index 1ad62e5058..2c4a7a51e8 100644
--- a/railties/lib/rails/console_app.rb
+++ b/railties/lib/rails/console_app.rb
@@ -27,6 +27,6 @@ end
def reload!
puts "Reloading..."
ActionDispatch::Callbacks.new(lambda {}, true)
- ActionController::Routing::Routes.reload
+ Rails.application.reload_routes!
true
end
diff --git a/railties/lib/rails/core.rb b/railties/lib/rails/core.rb
deleted file mode 100644
index a5e51ad04a..0000000000
--- a/railties/lib/rails/core.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-module Rails
- # Needs to be duplicated from Active Support since its needed before Active
- # Support is available. Here both Options and Hash are namespaced to prevent
- # conflicts with other implementations AND with the classes residing in Active Support.
- # ---
- # TODO: w0t?
- class << self
- def application
- @@application ||= nil
- end
-
- def application=(application)
- @@application = application
- end
-
- # The Configuration instance used to configure the Rails environment
- def configuration
- application.configuration
- end
-
- def initialize!
- application.initialize!
- end
-
- def initialized?
- @initialized || false
- end
-
- def initialized=(initialized)
- @initialized ||= initialized
- end
-
- def logger
- if defined?(RAILS_DEFAULT_LOGGER)
- RAILS_DEFAULT_LOGGER
- else
- nil
- end
- end
-
- def backtrace_cleaner
- @@backtrace_cleaner ||= begin
- # Relies on ActiveSupport, so we have to lazy load to postpone definition until AS has been loaded
- require 'rails/backtrace_cleaner'
- Rails::BacktraceCleaner.new
- end
- end
-
- def root
- application && application.config.root
- end
-
- def env
- @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
- end
-
- def cache
- RAILS_CACHE
- end
-
- def version
- VERSION::STRING
- end
-
- def public_path
- @@public_path ||= self.root ? File.join(self.root, "public") : "public"
- end
-
- def public_path=(path)
- @@public_path = path
- end
- end
-end \ No newline at end of file
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 19412c259e..3713a38b33 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -1,15 +1,16 @@
-activesupport_path = "#{File.dirname(__FILE__)}/../../../activesupport/lib"
-$LOAD_PATH.unshift(activesupport_path) if File.directory?(activesupport_path)
+activesupport_path = File.expand_path('../../../../activesupport/lib', __FILE__)
+$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
+
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/metaclass'
-require 'active_support/core_ext/array'
-require 'active_support/core_ext/hash'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/hash/deep_merge'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/string/inflections'
# TODO: Do not always push on vendored thor
-$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/vendor/thor-0.12.0/lib")
+$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/vendor/thor-0.12.3/lib")
require 'rails/generators/base'
require 'rails/generators/named_base'
@@ -86,28 +87,16 @@ module Rails
@options ||= DEFAULT_OPTIONS.dup
end
- # We have two scenarios here: when rubygems is loaded and when bundler is
- # being used. If rubygems is loaded, we get all generators paths from loaded
- # specs. Otherwise we just have to look into vendor/gems/gems.
- #
- def self.gems_generators_paths
- paths = []
-
- if defined?(Gem) && Gem.respond_to?(:loaded_specs)
- Gem.loaded_specs.each do |name, spec|
- generator_path = File.join(spec.full_gem_path, "lib/generators")
- paths << generator_path if File.exist?(generator_path)
- end
+ def self.gems_generators_paths #:nodoc:
+ return [] unless defined?(Gem) && Gem.respond_to?(:loaded_specs)
+ Gem.loaded_specs.inject([]) do |paths, (name, spec)|
+ paths += Dir[File.join(spec.full_gem_path, "lib/{generators,rails_generators}")]
end
-
- paths
end
- # Load paths from plugin.
- #
- def self.plugins_generators_paths
- return [] unless Rails.root
- Dir[File.join(Rails.root, "vendor", "plugins", "*", "lib", "generators")]
+ def self.plugins_generators_paths #:nodoc:
+ return [] unless defined?(Rails.root) && Rails.root
+ Dir[File.join(Rails.root, "vendor", "plugins", "*", "lib", "{generators,rails_generators}")]
end
# Hold configured generators fallbacks. If a plugin developer wants a
@@ -128,11 +117,15 @@ module Rails
end
# Remove the color from output.
- #
def self.no_color!
Thor::Base.shell = Thor::Shell::Basic
end
+ # Track all generators subclasses.
+ def self.subclasses
+ @subclasses ||= []
+ end
+
# Generators load paths used on lookup. The lookup happens as:
#
# 1) lib generators
@@ -147,8 +140,8 @@ module Rails
def self.load_paths
@load_paths ||= begin
paths = []
- paths << File.join(Rails.root, "lib", "generators") if Rails.root
- paths << File.join(Thor::Util.user_home, ".rails", "generators")
+ paths += Dir[File.join(Rails.root, "lib", "{generators,rails_generators}")] if defined?(Rails.root) && Rails.root
+ paths += Dir[File.join(Thor::Util.user_home, ".rails", "{generators,rails_generators}")]
paths += self.plugins_generators_paths
paths += self.gems_generators_paths
paths << File.expand_path(File.join(File.dirname(__FILE__), "generators"))
@@ -158,18 +151,10 @@ module Rails
end
load_paths # Cache load paths. Needed to avoid __FILE__ pointing to wrong paths.
- # Rails finds namespaces exactly as thor, with three conveniences:
+ # Rails finds namespaces similar to thor, it only adds one rule:
#
- # 1) If your generator name ends with generator, as WebratGenerator, it sets
- # its namespace to "webrat", so it can be invoked as "webrat" and not
- # "webrat_generator";
- #
- # 2) If your generator has a generators namespace, as Rails::Generators::WebratGenerator,
- # the namespace is set to "rails:generators:webrat", but Rails allows it
- # to be invoked simply as "rails:webrat". The "generators" is added
- # automatically when doing the lookup;
- #
- # 3) Rails looks in load paths and loads the generator just before it's going to be used.
+ # Generators names must end with "_generator.rb". This is required because Rails
+ # looks in load paths and loads the generator just before it's going to be used.
#
# ==== Examples
#
@@ -177,114 +162,82 @@ module Rails
#
# Will search for the following generators:
#
- # "rails:generators:webrat", "webrat:generators:integration", "webrat"
- #
- # On the other hand, if "rails:webrat" is given, it will search for:
+ # "rails:webrat", "webrat:integration", "webrat"
#
- # "rails:generators:webrat", "rails:webrat"
- #
- # Notice that the "generators" namespace is handled automatically by Rails,
- # so you don't need to type it when you want to invoke a generator in specific.
+ # Notice that "rails:generators:webrat" could be loaded as well, what
+ # Rails looks for is the first and last parts of the namespace.
#
def self.find_by_namespace(name, base=nil, context=nil) #:nodoc:
- name, attempts = name.to_s, [ ]
-
- case name.count(':')
- when 1
- base, name = name.split(':')
- return find_by_namespace(name, base)
- when 0
- attempts += generator_names(base, name) if base
- attempts += generator_names(name, context) if context
- end
-
- attempts << name
- attempts += generator_names(name, name) unless name.include?(?:)
- attempts.uniq!
-
- unloaded = attempts - namespaces
- lookup(unloaded)
+ # Mount regexps to lookup
+ regexps = []
+ regexps << /^#{base}:[\w:]*#{name}$/ if base
+ regexps << /^#{name}:[\w:]*#{context}$/ if context
+ regexps << /^[(#{name}):]+$/
+ regexps.uniq!
+
+ # Check if generator happens to be loaded
+ checked = subclasses.dup
+ klass = find_by_regexps(regexps, checked)
+ return klass if klass
+
+ # Try to require other generators by looking in load_paths
+ lookup(name, context)
+ unchecked = subclasses - checked
+ klass = find_by_regexps(regexps, unchecked)
+ return klass if klass
+
+ # Invoke fallbacks
+ invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name)
+ end
- attempts.each do |namespace|
- klass = Thor::Util.find_by_namespace(namespace)
- return klass if klass
+ # Tries to find a generator which the namespace match the regexp.
+ def self.find_by_regexps(regexps, klasses)
+ klasses.find do |klass|
+ namespace = klass.namespace
+ regexps.find { |r| namespace =~ r }
end
-
- invoke_fallbacks_for(name, base)
end
# Receives a namespace, arguments and the behavior to invoke the generator.
# It's used as the default entry point for generate, destroy and update
# commands.
- #
def self.invoke(namespace, args=ARGV, config={})
- if klass = find_by_namespace(namespace, "rails")
+ names = namespace.to_s.split(':')
+
+ if klass = find_by_namespace(names.pop, names.shift || "rails")
args << "--help" if klass.arguments.any? { |a| a.required? } && args.empty?
- klass.start args, config
+ klass.start(args, config)
else
puts "Could not find generator #{namespace}."
end
end
# Show help message with available generators.
- #
def self.help
- rails = Rails::Generators.builtin.map do |group, name|
- name if group == "rails"
- end
- rails.compact!
- rails.sort!
-
- puts "Please select a generator."
- puts "Builtin: #{rails.join(', ')}."
-
- # Load paths and remove builtin
- paths, others = load_paths.dup, []
- paths.pop
-
- paths.each do |path|
- tail = [ "*", "*", "*_generator.rb" ]
-
- until tail.empty?
- others += Dir[File.join(path, *tail)].collect do |file|
- name = file.split('/')[-tail.size, 2]
- name.last.sub!(/_generator\.rb$/, '')
- name.uniq!
- name.join(':')
- end
- tail.shift
- end
- end
+ builtin = Rails::Generators.builtin.each { |n| n.sub!(/^rails:/, '') }
+ builtin.sort!
+ lookup("*")
+ others = subclasses.map{ |k| k.namespace.gsub(':generators:', ':') }
+ others -= Rails::Generators.builtin
others.sort!
+
+ puts "Please select a generator."
+ puts "Builtin: #{builtin.join(', ')}."
puts "Others: #{others.join(', ')}." unless others.empty?
end
protected
- # Return all defined namespaces.
- #
- def self.namespaces #:nodoc:
- Thor::Base.subclasses.map { |klass| klass.namespace }
- end
-
- # Keep builtin generators in an Array[Array[group, name]].
- #
+ # Keep builtin generators in an Array.
def self.builtin #:nodoc:
Dir[File.dirname(__FILE__) + '/generators/*/*'].collect do |file|
- file.split('/')[-2, 2]
+ file.split('/')[-2, 2].join(':')
end
end
- # By default, Rails strips the generator namespace to make invocations
- # easier. This method generaters the both possibilities names.
- def self.generator_names(first, second)
- [ "#{first}:generators:#{second}", "#{first}:#{second}" ]
- end
-
- # Try callbacks for the given base.
- #
- def self.invoke_fallbacks_for(name, base)
+ # Try fallbacks for the given base.
+ def self.invoke_fallbacks_for(name, base) #:nodoc:
return nil unless base && fallbacks[base.to_sym]
invoked_fallbacks = []
@@ -301,10 +254,10 @@ module Rails
# Receives namespaces in an array and tries to find matching generators
# in the load path.
- #
- def self.lookup(attempts) #:nodoc:
- attempts = attempts.map { |a| "#{a.split(":").last}_generator" }.uniq
- attempts = "{#{attempts.join(',')}}.rb"
+ def self.lookup(*attempts) #:nodoc:
+ attempts.compact!
+ attempts.uniq!
+ attempts = "{#{attempts.join(',')}}_generator.rb"
self.load_paths.each do |path|
Dir[File.join(path, '**', attempts)].each do |file|
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index 8677bf283b..f95b15acce 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -104,7 +104,7 @@ module Rails
# file in config/environments.
#
def environment(data=nil, options={}, &block)
- sentinel = "Rails::Initializer.run do |config|"
+ sentinel = /class [a-z_:]+ < Rails::Application/i
data = block.call if !data && block_given?
in_root do
@@ -269,11 +269,11 @@ module Rails
#
# === Example
#
- # route "map.root :controller => :welcome"
+ # route "root :to => 'welcome'"
#
def route(routing_code)
log :route, routing_code
- sentinel = "ActionController::Routing::Routes.draw do |map|"
+ sentinel = "routes.draw do |map|"
in_root do
inject_into_file 'config/routes.rb', "\n #{routing_code}\n", { :after => sentinel, :verbose => false }
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index 226ae63963..5e8c2730fd 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -76,17 +76,18 @@ module Rails
#
# The controller generator will then try to invoke the following generators:
#
- # "rails:generators:test_unit", "test_unit:generators:controller", "test_unit"
+ # "rails:test_unit", "test_unit:controller", "test_unit"
#
- # In this case, the "test_unit:generators:controller" is available and is
- # invoked. This allows any test framework to hook into Rails as long as it
- # provides any of the hooks above.
+ # Notice that "rails:generators:test_unit" could be loaded as well, what
+ # Rails looks for is the first and last parts of the namespace. This is what
+ # allows any test framework to hook into Rails as long as it provides any
+ # of the hooks above.
#
# ==== Options
#
- # This lookup can be customized with two options: :base and :as. The first
- # is the root module value and in the example above defaults to "rails".
- # The later defaults to the generator name, without the "Generator" ending.
+ # The first and last part used to find the generator to be invoked are
+ # guessed based on class invokes hook_for, as noticed in the example above.
+ # This can be customized with two options: :base and :as.
#
# Let's suppose you are creating a generator that needs to invoke the
# controller generator from test unit. Your first attempt is:
@@ -97,7 +98,7 @@ module Rails
#
# The lookup in this case for test_unit as input is:
#
- # "test_unit:generators:awesome", "test_unit"
+ # "test_unit:awesome", "test_unit"
#
# Which is not the desired the lookup. You can change it by providing the
# :as option:
@@ -108,18 +109,18 @@ module Rails
#
# And now it will lookup at:
#
- # "test_unit:generators:awesome", "test_unit"
+ # "test_unit:controller", "test_unit"
#
# Similarly, if you want it to also lookup in the rails namespace, you just
# need to provide the :base value:
#
# class AwesomeGenerator < Rails::Generators::Base
- # hook_for :test_framework, :base => :rails, :as => :controller
+ # hook_for :test_framework, :in => :rails, :as => :controller
# end
#
# And the lookup is exactly the same as previously:
#
- # "rails:generators:test_unit", "test_unit:generators:controller", "test_unit"
+ # "rails:test_unit", "test_unit:controller", "test_unit"
#
# ==== Switches
#
@@ -151,11 +152,11 @@ module Rails
# ==== Custom invocations
#
# You can also supply a block to hook_for to customize how the hook is
- # going to be invoked. The block receives two parameters, an instance
+ # going to be invoked. The block receives two arguments, an instance
# of the current class and the klass to be invoked.
#
# For example, in the resource generator, the controller should be invoked
- # with a pluralized class name. By default, it is invoked with the same
+ # with a pluralized class name. But by default it is invoked with the same
# name as the resource generator, which is singular. To change this, we
# can give a block to customize how the controller can be invoked.
#
@@ -178,11 +179,11 @@ module Rails
end
unless class_options.key?(name)
- class_option name, defaults.merge!(options)
+ class_option(name, defaults.merge!(options))
end
hooks[name] = [ in_base, as_hook ]
- invoke_from_option name, options, &block
+ invoke_from_option(name, options, &block)
end
end
@@ -193,7 +194,7 @@ module Rails
# remove_hook_for :orm
#
def self.remove_hook_for(*names)
- remove_invocation *names
+ remove_invocation(*names)
names.each do |name|
hooks.delete(name)
@@ -219,12 +220,16 @@ module Rails
# and can point to wrong directions when inside an specified directory.
base.source_root
- if base.name && base.name !~ /Base$/ && base.base_name && base.generator_name && defined?(Rails.root) && Rails.root
- path = File.expand_path(File.join(Rails.root, 'lib', 'templates'))
- if base.name.include?('::')
- base.source_paths << File.join(path, base.base_name, base.generator_name)
- else
- base.source_paths << File.join(path, base.generator_name)
+ if base.name && base.name !~ /Base$/
+ Rails::Generators.subclasses << base
+
+ if defined?(Rails.root) && Rails.root
+ path = File.expand_path(File.join(Rails.root, 'lib', 'templates'))
+ if base.name.include?('::')
+ base.source_paths << File.join(path, base.base_name, base.generator_name)
+ else
+ base.source_paths << File.join(path, base.generator_name)
+ end
end
end
end
@@ -267,7 +272,7 @@ module Rails
# parameters.
#
def invoked?(args)
- args.last.is_a?(Hash) && args.last.key?(:invocations)
+ args.last.is_a?(Hash) && (args.last.key?(:invocations) || args.last.key?(:destination_root))
end
# Use Rails default banner.
@@ -290,12 +295,10 @@ module Rails
# Rails::Generators::MetalGenerator will return "metal" as generator name.
#
def self.generator_name
- if name
- @generator_name ||= begin
- if klass_name = name.to_s.split('::').last
- klass_name.sub!(/Generator$/, '')
- klass_name.underscore
- end
+ @generator_name ||= begin
+ if generator = name.to_s.split('::').last
+ generator.sub!(/Generator$/, '')
+ generator.underscore
end
end
end
@@ -339,6 +342,7 @@ module Rails
#
def self.prepare_for_invocation(name, value) #:nodoc:
if value && constants = self.hooks[name]
+ value = name if TrueClass === value
Rails::Generators.find_by_namespace(value, *constants)
else
super
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb
index 6460e5b599..51c4ad0e2e 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/layout.html.erb
@@ -7,7 +7,7 @@
</head>
<body>
-<p class="notice"><%%= flash[:notice] %></p>
+<p class="notice"><%%= notice %></p>
<%%= yield %>
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 2bcea4bc8f..fc6a3cdee8 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -3,6 +3,10 @@ require 'active_support/secure_random'
require 'rails/version' unless defined?(Rails::VERSION)
module Rails::Generators
+ # We need to store the RAILS_DEV_PATH in a constant, otherwise the path
+ # can change in Ruby 1.8.7 when we FileUtils.cd.
+ RAILS_DEV_PATH = File.expand_path("../../../../../..", File.dirname(__FILE__))
+
class AppGenerator < Base
DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
add_shebang_option!
@@ -15,17 +19,25 @@ module Rails::Generators
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_activerecord, :type => :boolean, :aliases => "-O", :default => false,
- :desc => "Skip ActiveRecord files"
+ :desc => "Skip ActiveRecord files"
class_option :skip_testunit, :type => :boolean, :aliases => "-T", :default => false,
- :desc => "Skip TestUnit files"
+ :desc => "Skip TestUnit files"
class_option :skip_prototype, :type => :boolean, :aliases => "-J", :default => false,
- :desc => "Skip Prototype files"
+ :desc => "Skip Prototype files"
+
+ class_option :skip_git, :type => :boolean, :aliases => "-G", :default => false,
+ :desc => "Skip Git ignores and keeps"
- # Add Rails options
- #
+ # Add bin/rails options
class_option :version, :type => :boolean, :aliases => "-v", :group => :rails,
:desc => "Show Rails version number and quit"
@@ -34,23 +46,25 @@ module Rails::Generators
def initialize(*args)
super
- if !options[:no_activerecord] && !DATABASES.include?(options[:database])
+ if !options[:skip_activerecord] && !DATABASES.include?(options[:database])
raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}."
end
end
def create_root
self.destination_root = File.expand_path(app_path, destination_root)
- empty_directory '.'
+ valid_app_const?
+ empty_directory '.'
set_default_accessors!
FileUtils.cd(destination_root)
end
def create_root_files
- copy_file "Rakefile"
copy_file "README"
- copy_file "config.ru"
+ copy_file "gitignore", ".gitignore" unless options[:skip_git]
+ template "Rakefile"
+ template "config.ru"
template "Gemfile"
end
@@ -62,9 +76,9 @@ module Rails::Generators
empty_directory "config"
inside "config" do
- copy_file "routes.rb"
- template "application.rb"
- template "environment.rb"
+ template "routes.rb"
+ template "application.rb"
+ template "environment.rb"
directory "environments"
directory "initializers"
@@ -91,7 +105,7 @@ module Rails::Generators
def create_lib_files
empty_directory "lib"
- empty_directory "lib/tasks"
+ empty_directory_with_gitkeep "lib/tasks"
end
def create_log_files
@@ -114,7 +128,7 @@ module Rails::Generators
end
def create_public_stylesheets_files
- directory "public/stylesheets"
+ empty_directory_with_gitkeep "public/stylesheets"
end
def create_prototype_files
@@ -123,10 +137,10 @@ module Rails::Generators
end
def create_script_files
- directory "script" do |file|
- prepend_file file, "#{shebang}\n", :verbose => false
- chmod file, 0755, :verbose => false
+ directory "script" do |content|
+ "#{shebang}\n" + content
end
+ chmod "script", 0755, :verbose => false
end
def create_test_files
@@ -139,13 +153,13 @@ module Rails::Generators
inside "tmp" do
%w(sessions sockets cache pids).each do |dir|
- empty_directory dir
+ empty_directory(dir)
end
end
end
def create_vendor_files
- empty_directory "vendor/plugins"
+ empty_directory_with_gitkeep "vendor/plugins"
end
def apply_rails_template
@@ -155,7 +169,6 @@ module Rails::Generators
end
protected
-
attr_accessor :rails_template
def set_default_accessors!
@@ -172,7 +185,6 @@ module Rails::Generators
end
# Define file as an alias to create_file for backwards compatibility.
- #
def file(*args, &block)
create_file(*args, &block)
end
@@ -181,10 +193,25 @@ module Rails::Generators
@app_name ||= File.basename(destination_root)
end
+ def app_const
+ @app_const ||= "#{app_name.gsub(/\W/, '_').squeeze('_').classify}::Application"
+ end
+
+ def valid_app_const?
+ case app_const
+ when /^\d/
+ raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers."
+ end
+ end
+
def app_secret
ActiveSupport::SecureRandom.hex(64)
end
+ def dev_or_edge?
+ options.dev? || options.edge?
+ end
+
def self.banner
"#{$0} #{self.arguments.map(&:usage).join(' ')} [options]"
end
@@ -202,5 +229,10 @@ module Rails::Generators
"/opt/lampp/var/mysql/mysql.sock" # xampp for linux
].find { |f| File.exist?(f) } unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
end
+
+ def empty_directory_with_gitkeep(destination, config = {})
+ empty_directory(destination, config)
+ create_file("#{destination}/.gitkeep") unless options[:skip_git]
+ end
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 8e851a64e7..59c6d333e2 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -1,9 +1,14 @@
# Edit this Gemfile to bundle your application's dependencies.
-
+<% if !dev_or_edge? %>
gem "rails", "<%= Rails::VERSION::STRING %>"
+<% end -%>
## Bundle edge rails:
-# gem "rails", :git => "git://github.com/rails/rails.git"
+<%- if options.dev? -%>
+gem "rails", :path => "<%= Rails::Generators::RAILS_DEV_PATH %>"
+<%- else -%>
+<%= "# " unless options.edge? %>gem "rails", :git => "git://github.com/rails/rails.git"
+<%- end -%>
## Bundle the gems you use:
# gem "bj"
diff --git a/railties/lib/rails/generators/rails/app/templates/Rakefile b/railties/lib/rails/generators/rails/app/templates/Rakefile
index 6b6d07e8cc..c19ad0e945 100755
--- a/railties/lib/rails/generators/rails/app/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/app/templates/Rakefile
@@ -7,4 +7,4 @@ require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
-require 'rails/tasks'
+<%= app_const %>.load_tasks
diff --git a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb
index 6635a3f487..9889b52893 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb
+++ b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb
@@ -2,9 +2,7 @@
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
- helper :all # include all helpers, all the time
- protect_from_forgery # See ActionController::RequestForgeryProtection for details
-
- # Scrub sensitive parameters from your log
- # filter_parameter_logging :password
+ helper :all
+ protect_from_forgery
+ filter_parameter_logging :password
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru
index 509a0da5b7..acb8435446 100644
--- a/railties/lib/rails/generators/rails/app/templates/config.ru
+++ b/railties/lib/rails/generators/rails/app/templates/config.ru
@@ -2,4 +2,4 @@
require ::File.expand_path('../config/environment', __FILE__)
# Dispatch the request
-run Rails.application
+run <%= app_const %>.instance
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 8008c6ba07..4097f766a6 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -1,41 +1,35 @@
require File.expand_path('../boot', __FILE__)
-Rails::Initializer.run do |config|
- # 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( #{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 ]
-
- # Skip frameworks you're not going to use. To use Rails without a database,
- # you must remove the Active Record framework.
-<% if options[:skip_activerecord] -%>
- config.frameworks -= [ :active_record ]
-<% else -%>
- # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
-
- # Activate observers that should always be running
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-<% end -%>
-
- # 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.
- config.time_zone = 'UTC'
-
- # 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
+module <%= app_name.classify %>
+ 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.
+ config.time_zone = 'UTC'
+
+ # 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
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 5aa49ca5e6..6de1725260 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/boot.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
@@ -13,4 +13,13 @@ else
require 'rubygems'
end
-require 'rails'
+require 'rails/all'
+# To pick the frameworks you want, remove 'require "rails/all"'
+# and list the framework railties that you want:
+#
+# require "active_model/railtie"
+# require "active_record/railtie"
+# require "action_controller/railtie"
+# require "action_view/railtie"
+# require "action_mailer/railtie"
+# require "active_resource/railtie" \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environment.rb b/railties/lib/rails/generators/rails/app/templates/config/environment.rb
index 0bb191f205..1684986a59 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environment.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/environment.rb
@@ -2,4 +2,4 @@
require File.expand_path('../application', __FILE__)
# Initialize the rails application
-Rails.initialize!
+<%= app_const %>.initialize!
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb
deleted file mode 100644
index 85c9a6080e..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-# 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
-
-# Don't care if the mailer can't send
-config.action_mailer.raise_delivery_errors = false \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
new file mode 100644
index 0000000000..b10103b436
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -0,0 +1,19 @@
+<%= app_const %>.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
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+end \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb
deleted file mode 100644
index 377b9207c7..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-# Settings specified here will take precedence over those in config/environment.rb
-
-# The production environment is meant for finished, "live" apps.
-# Code is not reloaded between requests
-config.cache_classes = true
-
-# Full error reports are disabled and caching is turned on
-config.action_controller.consider_all_requests_local = false
-config.action_controller.perform_caching = true
-
-# See everything in the log (default is :info)
-# config.log_level = :debug
-
-# Use a different logger for distributed setups
-# config.logger = SyslogLogger.new
-
-# Use a different cache store in production
-# config.cache_store = :mem_cache_store
-
-# Disable Rails's static asset server
-# In production, Apache or nginx will already do this
-config.serve_static_assets = false
-
-# Enable serving of images, stylesheets, and javascripts from an asset server
-# config.action_controller.asset_host = "http://assets.example.com"
-
-# Disable delivery errors, bad email addresses will be ignored
-# config.action_mailer.raise_delivery_errors = false
-
-# Enable threaded mode
-# config.threadsafe!
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
new file mode 100644
index 0000000000..543a40108c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -0,0 +1,33 @@
+<%= app_const %>.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.action_controller.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+end \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb
deleted file mode 100644
index 496eb9572b..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-# Settings specified here will take precedence over those in config/environment.rb
-
-# The test environment is used exclusively to run your application's
-# test suite. You never need to work with it otherwise. Remember that
-# your test database is "scratch space" for the test suite and is wiped
-# and recreated between test runs. Don't rely on the data there!
-config.cache_classes = true
-
-# 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_controller.perform_caching = false
-
-# Disable request forgery protection in test environment
-config.action_controller.allow_forgery_protection = false
-
-# Tell Action Mailer not to deliver emails to the real world.
-# The :test delivery method accumulates sent emails in the
-# ActionMailer::Base.deliveries array.
-config.action_mailer.delivery_method = :test
-
-# Use SQL instead of Active Record's schema dumper when creating the test database.
-# This is necessary if your schema can't be completely dumped by the schema dumper,
-# like if you have constraints or database-specific column types
-# config.active_record.schema_format = :sql \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
new file mode 100644
index 0000000000..428fa35633
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -0,0 +1,29 @@
+<%= app_const %>.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # 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_controller.perform_caching = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+end \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt
new file mode 100644
index 0000000000..9f05cd5a31
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+ActionController::Base.cookie_verifier_secret = '<%= app_secret %>';
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 ea14ce1bfc..d6c0365c04 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
@@ -1,43 +1,58 @@
-ActionController::Routing::Routes.draw do |map|
- # The priority is based upon order of creation: first created -> highest priority.
+<%= app_const %>.routes.draw do |map|
+ # The priority is based upon order of creation:
+ # first created -> highest priority.
# Sample of regular route:
- # map.connect 'products/:id', :controller => 'catalog', :action => 'view'
+ # match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
- # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
- # map.resources :products
+ # resources :products
# Sample resource route with options:
- # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
+ # resources :products do
+ # member do
+ # get :short
+ # post :toggle
+ # end
+ #
+ # collection do
+ # get :sold
+ # end
+ # end
# Sample resource route with sub-resources:
- # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
-
+ # resources :products do
+ # resources :comments, :sales
+ # resource :seller
+ # end
+
# Sample resource route with more complex sub-resources
- # map.resources :products do |products|
- # products.resources :comments
- # products.resources :sales, :collection => { :recent => :get }
+ # resources :products do
+ # resources :comments
+ # resources :sales do
+ # get :recent, :on => :collection
+ # end
# end
# Sample resource route within a namespace:
- # map.namespace :admin do |admin|
- # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
- # admin.resources :products
+ # namespace :admin do
+ # # Directs /admin/products/* to Admin::ProductsController
+ # # (app/controllers/admin/products_controller.rb)
+ # resources :products
# end
- # You can have the root of your site routed with map.root -- just remember to delete public/index.html.
- # map.root :controller => "welcome"
+ # You can have the root of your site routed with "root"
+ # just remember to delete public/index.html.
+ # root :to => "welcome#index"
# See how all your routes lay out with "rake routes"
- # Install the default routes as the lowest priority.
- # Note: These default routes make all actions in every controller accessible via GET requests. You should
- # consider removing or commenting them out if you're using named routes and resources.
- map.connect ':controller/:action/:id'
- map.connect ':controller/:action/:id.:format'
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
+ # Note: This route will make all actions in every controller accessible via GET requests.
+ # match ':controller(/:action(/:id(.:format)))'
end
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
new file mode 100644
index 0000000000..a4f05d101d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -0,0 +1,3 @@
+db/*.sqlite3
+log/*.log
+tmp/**/*
diff --git a/railties/lib/rails/generators/rails/app/templates/script/console b/railties/lib/rails/generators/rails/app/templates/script/console.tt
index 20aa799d2f..9ddd4cfe62 100755
--- a/railties/lib/rails/generators/rails/app/templates/script/console
+++ b/railties/lib/rails/generators/rails/app/templates/script/console.tt
@@ -1,2 +1,3 @@
require File.expand_path('../../config/application', __FILE__)
require 'rails/commands/console'
+Rails::Console.start(<%= app_const %>.instance)
diff --git a/railties/lib/rails/generators/rails/app/templates/script/dbconsole b/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt
index e6a1c59394..96e0bc191b 100755
--- a/railties/lib/rails/generators/rails/app/templates/script/dbconsole
+++ b/railties/lib/rails/generators/rails/app/templates/script/dbconsole.tt
@@ -1,2 +1,3 @@
require File.expand_path('../../config/application', __FILE__)
require 'rails/commands/dbconsole'
+Rails::DBConsole.start(<%= app_const %>.instance)
diff --git a/railties/lib/rails/generators/rails/app/templates/script/server b/railties/lib/rails/generators/rails/app/templates/script/server
deleted file mode 100755
index a7aaee2953..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/script/server
+++ /dev/null
@@ -1,2 +0,0 @@
-require File.expand_path('../../config/application', __FILE__)
-require 'rails/commands/server'
diff --git a/railties/lib/rails/generators/rails/app/templates/script/server.tt b/railties/lib/rails/generators/rails/app/templates/script/server.tt
new file mode 100755
index 0000000000..4fd0cc7832
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/script/server.tt
@@ -0,0 +1,5 @@
+require File.expand_path('../../config/boot', __FILE__)
+require 'rails/commands/server'
+
+Dir.chdir(File.expand_path('../..', __FILE__))
+Rails::Server.start
diff --git a/railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt b/railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt
index 675f00043f..d8757460e4 100644
--- a/railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt
+++ b/railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt
@@ -1,5 +1,5 @@
class <%= class_name %>Generator < Rails::Generators::NamedBase
def self.source_root
- @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
+ @source_root ||= File.expand_path('../templates', __FILE__)
end
end
diff --git a/railties/lib/rails/generators/rails/plugin/templates/Rakefile b/railties/lib/rails/generators/rails/plugin/templates/Rakefile
index 85e8ff1834..23c2245a41 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/plugin/templates/Rakefile
@@ -10,7 +10,6 @@ Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
- t.verbose = true
end
desc 'Generate documentation for the <%= file_name %> plugin.'
diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb
index e49f9aea1b..a89ce7faed 100644
--- a/railties/lib/rails/generators/rails/resource/resource_generator.rb
+++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb
@@ -16,7 +16,7 @@ module Rails
class_option :singleton, :type => :boolean, :desc => "Supply to create a singleton controller"
def add_resource_route
- route "map.resource#{:s unless options[:singleton]} :#{pluralize?(file_name)}"
+ route "resource#{:s unless options[:singleton]} :#{pluralize?(file_name)}"
end
protected
diff --git a/railties/lib/rails/generators/rails/scaffold/USAGE b/railties/lib/rails/generators/rails/scaffold/USAGE
index 71edd2f469..530ccdaf0a 100644
--- a/railties/lib/rails/generators/rails/scaffold/USAGE
+++ b/railties/lib/rails/generators/rails/scaffold/USAGE
@@ -17,7 +17,7 @@ Description:
For example, 'scaffold post title:string body:text published:boolean'
gives you a model with those three attributes, a controller that handles
the create/show/update/destroy, forms to create and edit your posts, and
- an index that lists them all, as well as a map.resources :posts
+ an index that lists them all, as well as a resources :posts
declaration in config/routes.rb.
If you want to remove all the generated files, run
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 3cc8bbf8e7..874e96a2b4 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -46,8 +46,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
if @<%= orm_instance.save %>
- flash[:notice] = '<%= class_name %> was successfully created.'
- format.html { redirect_to(@<%= file_name %>) }
+ format.html { redirect_to(@<%= file_name %>, :notice => '<%= class_name %> was successfully created.') }
format.xml { render :xml => @<%= file_name %>, :status => :created, :location => @<%= file_name %> }
else
format.html { render :action => "new" }
@@ -63,8 +62,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
if @<%= orm_instance.update_attributes("params[:#{file_name}]") %>
- flash[:notice] = '<%= class_name %> was successfully updated.'
- format.html { redirect_to(@<%= file_name %>) }
+ format.html { redirect_to(@<%= file_name %>, :notice => '<%= class_name %> was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
new file mode 100644
index 0000000000..643d7856c5
--- /dev/null
+++ b/railties/lib/rails/generators/test_case.rb
@@ -0,0 +1,239 @@
+require 'active_support/test_case'
+require 'active_support/core_ext/class/inheritable_attributes'
+require 'active_support/core_ext/hash/reverse_merge'
+require 'rails/generators'
+require 'fileutils'
+
+module Rails
+ module Generators
+ # Disable color in output. Easier to debug.
+ no_color!
+
+ # This class provides a TestCase for testing generators. To setup, you need
+ # just to configure the destination and set which generator is being tested:
+ #
+ # class AppGeneratorTest < Rails::Generators::TestCase
+ # tests AppGenerator
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ # end
+ #
+ # If you want to ensure your destination root is clean before running each test,
+ # you can set a setup callback:
+ #
+ # class AppGeneratorTest < Rails::Generators::TestCase
+ # tests AppGenerator
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ # setup :prepare_destination
+ # end
+ #
+ class TestCase < ActiveSupport::TestCase
+ include FileUtils
+
+ extlib_inheritable_accessor :destination_root, :current_path, :generator_class,
+ :default_arguments, :instance_writer => false
+
+ # Generators frequently change the current path using +FileUtils.cd+.
+ # So we need to store the path at file load and revert back to it after each test.
+ self.current_path = File.expand_path(Dir.pwd)
+ self.default_arguments = []
+
+ setup :destination_root_is_set?, :ensure_current_path
+ teardown :ensure_current_path
+
+ # Sets which generator should be tested:
+ #
+ # tests AppGenerator
+ #
+ def self.tests(klass)
+ self.generator_class = klass
+ end
+
+ # Sets default arguments on generator invocation. This can be overwritten when
+ # invoking it.
+ #
+ # arguments %w(app_name --skip-activerecord)
+ #
+ def self.arguments(array)
+ self.default_arguments = array
+ end
+
+ # Sets the destination of generator files:
+ #
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ #
+ def self.destination(path)
+ 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:
+ #
+ # assert_file "config/environment.rb"
+ #
+ # You can also give extra arguments. If the argument is a regexp, it will check if the
+ # regular expression matches the given file content. If it's a string, it compares the
+ # file with the given string:
+ #
+ # assert_file "config/environment.rb", /initialize/
+ #
+ # Finally, when a block is given, it yields the file content:
+ #
+ # assert_file "app/controller/products_controller.rb" do |controller|
+ # assert_instance_method :index, content do |index|
+ # assert_match /Product\.all/, index
+ # end
+ # end
+ #
+ def assert_file(relative, *contents)
+ absolute = File.expand_path(relative, destination_root)
+ assert File.exists?(absolute), "Expected file #{relative.inspect} to exist, but does not"
+
+ read = File.read(absolute) if block_given? || !contents.empty?
+ yield read if block_given?
+
+ contents.each do |content|
+ case content
+ when String
+ assert_equal content, read
+ when Regexp
+ assert_match content, read
+ end
+ end
+ end
+ alias :assert_directory :assert_file
+
+ # Asserts a given file does not exist. You need to supply an absolute path or a
+ # path relative to the configured destination:
+ #
+ # assert_no_file "config/random.rb"
+ #
+ def assert_no_file(relative)
+ absolute = File.expand_path(relative, destination_root)
+ assert !File.exists?(absolute), "Expected file #{relative.inspect} to not exist, but does"
+ end
+ alias :assert_no_directory :assert_no_file
+
+ # Asserts a given file does not exist. You need to supply an absolute path or a
+ # path relative to the configured destination:
+ #
+ # assert_migration "db/migrate/create_products.rb"
+ #
+ # This method manipulates the given path and tries to find any migration which
+ # matches the migration name. For example, the call above is converted to:
+ #
+ # assert_file "db/migrate/003_create_products.rb"
+ #
+ # Consequently, assert_migration accepts the same arguments has assert_file.
+ #
+ def assert_migration(relative, *contents, &block)
+ file_name = migration_file_name(relative)
+ assert file_name, "Expected migration #{relative} to exist, but was not found"
+ assert_file file_name, *contents, &block
+ end
+
+ # Asserts a given migration does not exist. You need to supply an absolute path or a
+ # path relative to the configured destination:
+ #
+ # assert_no_file "config/random.rb"
+ #
+ def assert_no_migration(relative)
+ file_name = migration_file_name(relative)
+ assert_nil file_name, "Expected migration #{relative} to not exist, but found #{file_name}"
+ end
+
+ # Asserts the given class method exists in the given content. This method does not detect
+ # class methods inside (class << self), only class methods which starts with "self.".
+ # When a block is given, it yields the content of the method.
+ #
+ # assert_migration "db/migrate/create_products.rb" do |migration|
+ # assert_class_method :up, migration do |up|
+ # assert_match /create_table/, up
+ # end
+ # end
+ #
+ def assert_class_method(method, content, &block)
+ assert_instance_method "self.#{method}", content, &block
+ end
+
+ # Asserts the given method exists in the given content. When a block is given,
+ # it yields the content of the method.
+ #
+ # assert_file "app/controller/products_controller.rb" do |controller|
+ # assert_instance_method :index, content do |index|
+ # assert_match /Product\.all/, index
+ # end
+ # end
+ #
+ def assert_instance_method(method, content)
+ assert content =~ /def #{method}(\(.+\))?(.*?)\n end/m, "Expected to have method #{method}"
+ yield $2.strip if block_given?
+ end
+ alias :assert_method :assert_instance_method
+
+ # Runs the generator configured for this class. The first argument is an array like
+ # command line arguments:
+ #
+ # class AppGeneratorTest < Rails::Generators::TestCase
+ # tests AppGenerator
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ # teardown :cleanup_destination_root
+ #
+ # test "database.yml is not created when skipping activerecord" do
+ # run_generator %w(myapp --skip-activerecord)
+ # assert_no_file "config/database.yml"
+ # end
+ # end
+ #
+ # You can provide a configuration hash as second argument. This method returns the output
+ # printed by the generator.
+ def run_generator(args=self.default_arguments, config={})
+ capture(:stdout) { self.generator_class.start(args, config.reverse_merge(:destination_root => destination_root)) }
+ end
+
+ # Instantiate the generator.
+ def generator(args=self.default_arguments, options={}, config={})
+ @generator ||= self.generator_class.new(args, options, config.reverse_merge(:destination_root => destination_root))
+ end
+
+ protected
+
+ def destination_root_is_set? #:nodoc:
+ raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root
+ end
+
+ def ensure_current_path #:nodoc:
+ cd current_path
+ end
+
+ def prepare_destination
+ rm_rf(destination_root)
+ mkdir_p(destination_root)
+ end
+
+ def migration_file_name(relative) #:nodoc:
+ absolute = File.expand_path(relative, destination_root)
+ dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '')
+ Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first
+ end
+ end
+ end
+end \ No newline at end of file
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 c21035113e..a30132bc99 100644
--- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
+++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
@@ -11,9 +11,13 @@ two:
<%= attribute.name %>: <%= attribute.default %>
<% end -%>
<% else -%>
-# one:
-# column: value
+# This model initially had no columns defined. If you add columns to the
+# model remove the '{}' from the fixture names and add the columns immediately
+# below each fixture, per the syntax in the comments below
#
-# two:
-# column: value
-<% end -%>
+one: {}
+# column: value
+#
+two: {}
+# column: value
+<% end -%> \ No newline at end of file
diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb
index 3866b856b2..8fcb254590 100644
--- a/railties/lib/rails/initializable.rb
+++ b/railties/lib/rails/initializable.rb
@@ -5,7 +5,7 @@ module Rails
end
class Initializer
- attr_reader :name, :before, :after, :global, :block
+ attr_reader :name, :block
def initialize(name, context, options, &block)
@name, @context, @options, @block = name, context, options, block
@@ -62,7 +62,7 @@ module Rails
end
def run_initializers(*args)
- return if @ran
+ return if instance_variable_defined?(:@ran)
initializers.each do |initializer|
initializer.run(*args)
end
@@ -93,6 +93,7 @@ module Rails
end
def initializer(name, opts = {}, &blk)
+ raise ArgumentError, "A block must be passed when defining an initializer" unless blk
@initializers ||= []
@initializers << Initializer.new(name, nil, opts, &blk)
end
@@ -106,26 +107,4 @@ module Rails
end
end
end
-
- include Initializable
-
- # Check for valid Ruby version (1.8.2 or 1.8.4 or higher). This is done in an
- # external file, so we can use it from the `rails` program as well without duplication.
- initializer :check_ruby_version, :global => true do
- require 'rails/ruby_version_check'
- end
-
- # For Ruby 1.8, this initialization sets $KCODE to 'u' to enable the
- # multibyte safe operations. Plugin authors supporting other encodings
- # should override this behaviour and set the relevant +default_charset+
- # on ActionController::Base.
- #
- # For Ruby 1.9, UTF-8 is the default internal and external encoding.
- initializer :initialize_encoding, :global => true do
- if RUBY_VERSION < '1.9'
- $KCODE='u'
- else
- Encoding.default_external = Encoding::UTF_8
- end
- end
end \ No newline at end of file
diff --git a/railties/lib/rails/initializer.rb b/railties/lib/rails/initializer.rb
deleted file mode 100644
index 44d04688c8..0000000000
--- a/railties/lib/rails/initializer.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-require "rails" # In case people require this file directly
-
-RAILS_ENV = (ENV['RAILS_ENV'] || 'development').dup unless defined?(RAILS_ENV)
-
-module Rails
- class Initializer
- class Error < StandardError ; end
- def self.run(initializer = nil, config = nil)
- if initializer
- # Deprecated
- else
- Rails.application = Class.new(Application)
- yield Rails.application.config if block_given?
- end
- end
- end
-end \ No newline at end of file
diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb
index 86bf032641..9cc6b9c35b 100644
--- a/railties/lib/rails/plugin.rb
+++ b/railties/lib/rails/plugin.rb
@@ -1,63 +1,63 @@
module Rails
- class Plugin
- include Initializable
-
- class Vendored < Plugin
- 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
+ class Plugin < Railtie
+ 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
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
+ plugins.sort_by do |p|
+ [list.index(p.name) || list.index(:all), p.name.to_s]
end
+ end
- attr_reader :name, :path
+ attr_reader :name, :path
- def initialize(path)
- @name = File.basename(path).to_sym
- @path = path
- end
+ def initialize(path)
+ @name = File.basename(path).to_sym
+ @path = path
+ end
- def load_paths
- Dir["#{path}/{lib}", "#{path}/app/{models,controllers,helpers}"]
- end
+ def load_paths
+ Dir["#{path}/{lib}", "#{path}/app/{models,controllers,helpers}"]
+ end
- initializer :add_to_load_path, :after => :set_autoload_paths do |app|
- load_paths.each do |path|
- $LOAD_PATH << path
- require "active_support/dependencies"
+ def load_tasks
+ Dir["#{path}/**/tasks/**/*.rake"].sort.each { |ext| load ext }
+ end
+
+ initializer :add_to_load_path, :after => :set_autoload_paths do |app|
+ load_paths.each do |path|
+ $LOAD_PATH << path
+ require "active_support/dependencies"
- ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_paths << path
- unless app.config.reload_plugins
- ActiveSupport::Dependencies.load_once_paths << path
- end
+ unless app.config.reload_plugins
+ ActiveSupport::Dependencies.load_once_paths << path
end
end
+ end
- initializer :load_init_rb, :before => :load_application_initializers do |app|
- file = "#{@path}/init.rb"
- config = app.config
- eval File.read(file), binding, file if File.file?(file)
- end
+ initializer :load_init_rb, :before => :load_application_initializers do |app|
+ file = "#{@path}/init.rb"
+ config = app.config
+ eval File.read(file), binding, file if File.file?(file)
+ end
- initializer :add_view_paths, :after => :initialize_framework_views do
- ActionController::Base.view_paths.concat ["#{path}/app/views"] if File.directory?("#{path}/app/views")
- end
+ initializer :add_view_paths, :after => :initialize_framework_views do
+ ActionController::Base.view_paths.concat ["#{path}/app/views"] if File.directory?("#{path}/app/views")
+ end
- initializer :add_routing_file, :after => :initialize_routing do |app|
- routing_file = "#{path}/config/routes.rb"
- if File.exist?(routing_file)
- app.routes.add_configuration_file(routing_file)
- app.routes.reload!
- end
+ initializer :add_routing_file, :after => :initialize_routing do |app|
+ routing_file = "#{path}/config/routes.rb"
+ if File.exist?(routing_file)
+ app.route_configuration_files << routing_file
+ app.reload_routes!
end
end
end
diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb
index aa2711c616..0a7b405553 100644
--- a/railties/lib/rails/rack/debugger.rb
+++ b/railties/lib/rails/rack/debugger.rb
@@ -4,6 +4,8 @@ module Rails
def initialize(app)
@app = app
+ ARGV.clear # clear ARGV so that script/server options aren't passed to IRB
+
require_library_or_gem 'ruby-debug'
::Debugger.start
::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings)
diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb
index a237cee6bc..077311be3c 100644
--- a/railties/lib/rails/rack/log_tailer.rb
+++ b/railties/lib/rails/rack/log_tailer.rb
@@ -1,12 +1,10 @@
module Rails
module Rack
class LogTailer
- EnvironmentLog = "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log"
-
def initialize(app, log = nil)
@app = app
- path = Pathname.new(log || EnvironmentLog).cleanpath
+ path = Pathname.new(log || "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log").cleanpath
@cursor = ::File.size(path)
@last_checked = Time.now.to_f
diff --git a/railties/lib/rails/rack/static.rb b/railties/lib/rails/rack/static.rb
index d6b8face27..ebe8b9e103 100644
--- a/railties/lib/rails/rack/static.rb
+++ b/railties/lib/rails/rack/static.rb
@@ -1,5 +1,5 @@
require 'action_dispatch'
module Rails::Rack
- Static = Deprecation::DeprecatedConstantProxy.new('Rails::Rack::Static', ActionDispatch::Static)
+ Static = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Rails::Rack::Static', ActionDispatch::Static)
end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
new file mode 100644
index 0000000000..ff28ade35d
--- /dev/null
+++ b/railties/lib/rails/railtie.rb
@@ -0,0 +1,43 @@
+module Rails
+ class Railtie
+ include Initializable
+
+ def self.plugin_name(plugin_name = nil)
+ @plugin_name ||= name.demodulize.underscore
+ @plugin_name = plugin_name if plugin_name
+ @plugin_name
+ end
+
+ 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
+
+ def self.config
+ Configuration.default
+ end
+
+ def self.rake_tasks(&blk)
+ @rake_tasks ||= []
+ @rake_tasks << blk if blk
+ @rake_tasks
+ end
+
+ def rake_tasks
+ self.class.rake_tasks
+ end
+
+ def load_tasks
+ return unless rake_tasks
+ rake_tasks.each { |blk| blk.call }
+ end
+ end
+end
diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb
index 82113a297c..44c014efe8 100644
--- a/railties/lib/rails/tasks.rb
+++ b/railties/lib/rails/tasks.rb
@@ -3,7 +3,6 @@ $VERBOSE = nil
# Load Rails rakefile extensions
%w(
annotations
- databases
documentation
framework
log
@@ -16,8 +15,3 @@ $VERBOSE = nil
).each do |task|
load "rails/tasks/#{task}.rake"
end
-
-# Load any custom rakefile extensions
-# TODO: Don't hardcode these paths.
-Dir["#{Rails.root}/vendor/plugins/*/**/tasks/**/*.rake"].sort.each { |ext| load ext }
-Dir["#{Rails.root}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake
index 1611d1d94d..f7b53885c8 100644
--- a/railties/lib/rails/tasks/framework.rake
+++ b/railties/lib/rails/tasks/framework.rake
@@ -92,7 +92,7 @@ namespace :rails do
namespace :update do
def invoke_from_app_generator(method)
- require 'generators'
+ require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
generator = Rails::Generators::AppGenerator.new ["rails"], { :with_dispatchers => true },
@@ -100,6 +100,12 @@ namespace :rails do
generator.invoke(method)
end
+ desc "Update config/boot.rb from your current rails install"
+ task :configs do
+ invoke_from_app_generator :create_boot_file
+ invoke_from_app_generator :create_config_files
+ end
+
desc "Update Prototype javascripts from your current rails install"
task :javascripts do
invoke_from_app_generator :create_prototype_files
diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake
index 7f244ebaed..9433b3556a 100644
--- a/railties/lib/rails/tasks/misc.rake
+++ b/railties/lib/rails/tasks/misc.rake
@@ -1,8 +1,4 @@
task :default => :test
-task :environment do
- $rails_rake_task = true
- require(File.join(Rails.root, 'config', 'environment'))
-end
task :rails_env do
unless defined? RAILS_ENV
diff --git a/railties/lib/rails/tasks/testing.rake b/railties/lib/rails/tasks/testing.rake
index fd5e52a05b..57857fb911 100644
--- a/railties/lib/rails/tasks/testing.rake
+++ b/railties/lib/rails/tasks/testing.rake
@@ -48,7 +48,7 @@ task :test do
task
end
end.compact
- abort "Errors running #{errors.to_sentence(:locale => :en)}!" if errors.any?
+ abort "Errors running #{errors * ', '}!" if errors.any?
end
namespace :test do
@@ -59,7 +59,6 @@ namespace :test do
recent_tests('app/controllers/**/*.rb', 'test/functional', since)
t.libs << 'test'
- t.verbose = true
t.test_files = touched.uniq
end
Rake::Task['test:recent'].comment = "Test recent changes"
@@ -84,35 +83,30 @@ namespace :test do
end
t.libs << 'test'
- t.verbose = true
end
Rake::Task['test:uncommitted'].comment = "Test changes since last checkin (only Subversion and Git)"
Rake::TestTask.new(:units => "db:test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/unit/**/*_test.rb'
- t.verbose = true
end
Rake::Task['test:units'].comment = "Run the unit tests in test/unit"
Rake::TestTask.new(:functionals => "db:test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/functional/**/*_test.rb'
- t.verbose = true
end
Rake::Task['test:functionals'].comment = "Run the functional tests in test/functional"
Rake::TestTask.new(:integration => "db:test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/integration/**/*_test.rb'
- t.verbose = true
end
Rake::Task['test:integration'].comment = "Run the integration tests in test/integration"
Rake::TestTask.new(:benchmark => 'db:test:prepare') do |t|
t.libs << 'test'
t.pattern = 'test/performance/**/*_test.rb'
- t.verbose = true
t.options = '-- --benchmark'
end
Rake::Task['test:benchmark'].comment = 'Benchmark the performance tests'
@@ -120,7 +114,6 @@ namespace :test do
Rake::TestTask.new(:profile => 'db:test:prepare') do |t|
t.libs << 'test'
t.pattern = 'test/performance/**/*_test.rb'
- t.verbose = true
end
Rake::Task['test:profile'].comment = 'Profile the performance tests'
@@ -132,8 +125,6 @@ namespace :test do
else
t.pattern = 'vendor/plugins/*/**/test/**/*_test.rb'
end
-
- t.verbose = true
end
Rake::Task['test:plugins'].comment = "Run the plugin tests in vendor/plugins/*/**/test (or specify with PLUGIN=name)"
end
diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb
index 9f6c42945f..2601765065 100644
--- a/railties/lib/rails/test_help.rb
+++ b/railties/lib/rails/test_help.rb
@@ -2,14 +2,18 @@
# so fixtures are loaded to the right database
silence_warnings { RAILS_ENV = "test" }
-require 'rubygems'
-gem "rack", "~> 1.0.0"
-gem "rack-test", "~> 0.5.0"
+require 'rack'
+require 'rack/test'
require 'test/unit'
require 'active_support/core_ext/kernel/requires'
+
+# AP is always present
+require 'action_controller/test_case'
require 'action_view/test_case'
+
require 'action_mailer/test_case' if defined?(ActionMailer)
+require 'active_model/test_case' if defined?(ActiveModel)
if defined?(ActiveRecord)
require 'active_record/test_case'
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb b/railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb
deleted file mode 100644
index 885230fac4..0000000000
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/version.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-class Thor
- VERSION = "0.11.8".freeze
-end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc b/railties/lib/rails/vendor/thor-0.12.3/CHANGELOG.rdoc
index adedfeca9d..d02fc43e84 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/CHANGELOG.rdoc
+++ b/railties/lib/rails/vendor/thor-0.12.3/CHANGELOG.rdoc
@@ -1,9 +1,7 @@
-== TODO
-
-* Improve spec coverage for Thor::Runner
-
-== 0.12, released 2009-11-06
+== 0.12, released 2010-01-02
+* Removed rr in favor to rspec mock framework
+* Improved output for thor -T
* [#7] Do not force white color on status
* [#8] Yield a block with the filename on directory
diff --git a/railties/lib/rails/vendor/thor-0.12.0/LICENSE b/railties/lib/rails/vendor/thor-0.12.3/LICENSE
index 98722da459..98722da459 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/LICENSE
+++ b/railties/lib/rails/vendor/thor-0.12.3/LICENSE
diff --git a/railties/lib/rails/vendor/thor-0.12.0/README.rdoc b/railties/lib/rails/vendor/thor-0.12.3/README.rdoc
index f1106f02b6..ee545f3d97 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/README.rdoc
+++ b/railties/lib/rails/vendor/thor-0.12.3/README.rdoc
@@ -7,7 +7,7 @@ Example:
class App < Thor # [1]
map "-L" => :list # [2]
-
+
desc "install APP_NAME", "install one of the available apps" # [3]
method_options :force => :boolean, :alias => :string # [4]
def install(name)
@@ -17,7 +17,7 @@ Example:
end
# other code
end
-
+
desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
def list(search="")
# list everything
@@ -126,13 +126,13 @@ invoked only once. For example:
invoke :two
invoke :three
end
-
+
desc "two", "Prints 2, 3"
def two
puts 2
invoke :three
end
-
+
desc "three", "Prints 3"
def three
puts 3
@@ -155,15 +155,15 @@ Thor::Group as this:
class Counter < Thor::Group
desc "Prints 1, 2, 3"
-
+
def one
puts 1
end
-
+
def two
puts 2
end
-
+
def three
puts 3
end
@@ -184,15 +184,15 @@ Besides, Thor::Group can parse arguments and options as Thor tasks:
# number will be available as attr_accessor
argument :number, :type => :numeric, :desc => "The number to start counting"
desc "Prints the 'number' given upto 'number+2'"
-
+
def one
puts number + 0
end
-
+
def two
puts number + 1
end
-
+
def three
puts number + 2
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/Thorfile b/railties/lib/rails/vendor/thor-0.12.3/Thorfile
index f71a1e57e2..ff1cb4498a 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/Thorfile
+++ b/railties/lib/rails/vendor/thor-0.12.3/Thorfile
@@ -56,7 +56,7 @@ class Default < Thor
s.test_files.exclude 'spec/sandbox/**/*'
end
- Jeweler::RubyforgeTasks.new
+ Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler, or one of its dependencies, is not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor.rb
index 68944f140d..d4d8fbd64d 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor.rb
@@ -78,14 +78,14 @@ class Thor
@method_options
end
- # Adds an option to the set of class options. If :for is given as option,
+ # Adds an option to the set of method options. If :for is given as option,
# it allows you to change the options from a previous defined task.
#
# def previous_task
# # magic
# end
#
- # method_options :foo => :bar, :for => :previous_task
+ # method_option :foo => :bar, :for => :previous_task
#
# def next_task
# # magic
@@ -101,7 +101,6 @@ class Thor
# :default - Default value for this argument. It cannot be required and have default values.
# :aliases - Aliases for this option.
# :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
- # :group - The group for this options. Use by class options to output options in different levels.
# :banner - String to show on usage notes.
#
def method_option(name, options={})
@@ -140,49 +139,48 @@ class Thor
end
end
- # Prints help information. If a task name is given, it shows information
- # only about the specific task.
+ # Prints help information for the given task.
#
# ==== Parameters
- # meth<String>:: An optional task name to print usage information about.
+ # shell<Thor::Shell>
+ # task_name<String>
+ #
+ def task_help(shell, task_name)
+ task = all_tasks[task_name]
+ raise UndefinedTaskError, "task '#{task_name}' could not be found in namespace '#{self.namespace}'" unless task
+
+ shell.say "Usage:"
+ shell.say " #{banner(task)}"
+ shell.say
+ class_options_help(shell, nil => task.options.map { |_, o| o })
+ shell.say task.description
+ end
+
+ # Prints help information for this class.
#
- # ==== Options
- # namespace:: When true, shows the namespace in the output before the usage.
- # skip_inherited:: When true, does not show tasks from superclass.
+ # ==== Parameters
+ # shell<Thor::Shell>
#
- def help(shell, meth=nil, options={})
- meth, options = nil, meth if meth.is_a?(Hash)
-
- if meth
- task = all_tasks[meth]
- raise UndefinedTaskError, "task '#{meth}' could not be found in namespace '#{self.namespace}'" unless task
-
- shell.say "Usage:"
- shell.say " #{banner(task, options[:namespace], false)}"
- shell.say
- class_options_help(shell, "Class", :Method => task.options.map { |_, o| o })
- shell.say task.description
- else
- list = (options[:short] ? tasks : all_tasks).map do |_, task|
- item = [ banner(task, options[:namespace]) ]
- item << "# #{task.short_description}" if task.short_description
- item << " "
- end
-
- options[:ident] ||= 2
- if options[:short]
- shell.print_list(list, :ident => options[:ident])
- else
- shell.say "Tasks:"
- shell.print_list(list, :ident => options[:ident])
- end
+ def help(shell)
+ list = printable_tasks
+ Thor::Util.thor_classes_in(self).each do |klass|
+ list += klass.printable_tasks(false)
+ end
+ list.sort!{ |a,b| a[0] <=> b[0] }
- Thor::Util.thor_classes_in(self).each do |subclass|
- namespace = options[:namespace] == true || subclass.namespace.gsub(/^#{self.namespace}:/, '')
- subclass.help(shell, options.merge(:short => true, :namespace => namespace))
- end
+ shell.say "Tasks:"
+ shell.print_table(list, :ident => 2, :truncate => true)
+ shell.say
+ class_options_help(shell)
+ end
- class_options_help(shell, "Class") unless options[:short]
+ # Returns tasks ready to be printed.
+ def printable_tasks(all=true)
+ (all ? all_tasks : tasks).map do |_, task|
+ item = []
+ item << banner(task)
+ item << (task.description ? "# #{task.description.gsub(/\s+/m,' ')}" : "")
+ item
end
end
@@ -193,8 +191,8 @@ class Thor
# the task that is going to be invoked and a boolean which indicates if
# the namespace should be displayed as arguments.
#
- def banner(task, namespace=true, show_options=true)
- task.formatted_usage(self, namespace, show_options)
+ def banner(task)
+ "thor " + task.formatted_usage(self)
end
def baseclass #:nodoc:
@@ -237,6 +235,6 @@ class Thor
desc "help [TASK]", "Describe available tasks or one specific task"
def help(task=nil)
- self.class.help(shell, task, :namespace => task && task.include?(?:))
+ task ? self.class.task_help(shell, task) : self.class.help(shell)
end
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions.rb
index d561ccb2aa..da98444bf2 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions.rb
@@ -1,4 +1,5 @@
require 'fileutils'
+require 'thor/core_ext/file_binary_read'
Dir[File.join(File.dirname(__FILE__), "actions", "*.rb")].each do |action|
require action
@@ -38,17 +39,17 @@ class Thor
# Add runtime options that help actions execution.
#
def add_runtime_options!
- class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime,
- :desc => "Run but do not make any changes"
-
class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime,
:desc => "Overwrite files that already exist"
- class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime,
- :desc => "Skip files that already exist"
+ class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime,
+ :desc => "Run but do not make any changes"
class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime,
:desc => "Supress status output"
+
+ class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime,
+ :desc => "Skip files that already exist"
end
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/create_file.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/create_file.rb
index a3d9296823..6e0eeb43e2 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/create_file.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/create_file.rb
@@ -42,7 +42,7 @@ class Thor
# Boolean:: true if it is identical, false otherwise.
#
def identical?
- exists? && File.read(destination) == render
+ exists? && File.binread(destination) == render
end
# Holds the content to be added to the file.
@@ -58,7 +58,7 @@ class Thor
def invoke!
invoke_with_conflict_check do
FileUtils.mkdir_p(File.dirname(destination))
- File.open(destination, 'w'){ |f| f.write render }
+ File.open(destination, 'wb') { |f| f.write render }
end
given_destination
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/directory.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/directory.rb
index 467e63732a..2e0b459fa3 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/directory.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/directory.rb
@@ -79,11 +79,9 @@ class Thor
next if dirname == given_destination
base.empty_directory(dirname, config)
when /\.tt$/
- destination = base.template(file_source, file_destination[0..-4], config)
- @block.call(destination) if @block
+ destination = base.template(file_source, file_destination[0..-4], config, &@block)
else
- destination = base.copy_file(file_source, file_destination, config)
- @block.call(destination) if @block
+ destination = base.copy_file(file_source, file_destination, config, &@block)
end
end
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/empty_directory.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/empty_directory.rb
index 484cb820f8..484cb820f8 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/empty_directory.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/empty_directory.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/file_manipulation.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/file_manipulation.rb
index d77d90d448..44d6836c10 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/file_manipulation.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/file_manipulation.rb
@@ -18,12 +18,14 @@ class Thor
#
# copy_file "doc/README"
#
- def copy_file(source, destination=nil, config={})
+ def copy_file(source, destination=nil, config={}, &block)
destination ||= source
source = File.expand_path(find_in_source_paths(source.to_s))
create_file destination, nil, config do
- File.read(source)
+ content = File.binread(source)
+ content = block.call(content) if block
+ content
end
end
@@ -46,7 +48,7 @@ class Thor
#
def get(source, destination=nil, config={}, &block)
source = File.expand_path(find_in_source_paths(source.to_s)) unless source =~ /^http\:\/\//
- render = open(source).read
+ render = File.binread(source)
destination ||= if block_given?
block.arity == 1 ? block.call(render) : block.call
@@ -72,13 +74,15 @@ class Thor
#
# template "doc/README"
#
- def template(source, destination=nil, config={})
+ def template(source, destination=nil, config={}, &block)
destination ||= source
source = File.expand_path(find_in_source_paths(source.to_s))
context = instance_eval('binding')
create_file destination, nil, config do
- ERB.new(::File.read(source), nil, '-').result(context)
+ content = ERB.new(::File.binread(source), nil, '-').result(context)
+ content = block.call(content) if block
+ content
end
end
@@ -189,7 +193,7 @@ class Thor
say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true)
unless options[:pretend]
- content = File.read(path)
+ content = File.binread(path)
content.gsub!(flag, *args, &block)
File.open(path, 'wb') { |file| file.write(content) }
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/inject_into_file.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/inject_into_file.rb
index 0636ec6591..350ab73862 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/actions/inject_into_file.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/actions/inject_into_file.rb
@@ -90,7 +90,7 @@ class Thor
#
def replace!(regexp, string)
unless base.options[:pretend]
- content = File.read(destination)
+ content = File.binread(destination)
content.gsub!(regexp, string)
File.open(destination, 'wb') { |file| file.write(content) }
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/base.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/base.rb
index 700d794123..aae4cdb89c 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/base.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/base.rb
@@ -92,6 +92,8 @@ class Thor
end
module ClassMethods
+ attr_accessor :debugging
+
# Adds an argument to the class and creates an attr_accessor for it.
#
# Arguments are different from options in several aspects. The first one
@@ -347,10 +349,11 @@ class Thor
# Default way to start generators from the command line.
#
def start(given_args=ARGV, config={})
+ self.debugging = given_args.include?("--debug")
config[:shell] ||= Thor::Base.shell.new
yield
rescue Thor::Error => e
- if given_args.include?("--debug")
+ if debugging
raise e
else
config[:shell].error e.message
@@ -361,48 +364,43 @@ class Thor
protected
# Prints the class options per group. If an option does not belong to
- # any group, it uses the ungrouped name value. This method provide to
- # hooks to add extra options, one of them if the third argument called
- # extra_group that should be a hash in the format :group => Array[Options].
- #
- # The second is by returning a lambda used to print values. The lambda
- # requires two options: the group name and the array of options.
+ # any group, it's printed as Class option.
#
- def class_options_help(shell, ungrouped_name=nil, extra_group=nil) #:nodoc:
- groups = {}
-
+ def class_options_help(shell, groups={}) #:nodoc:
+ # Group options by group
class_options.each do |_, value|
groups[value.group] ||= []
groups[value.group] << value
end
- printer = proc do |group_name, options|
- list = []
- padding = options.collect{ |o| o.aliases.size }.max.to_i * 4
+ # Deal with default group
+ global_options = groups.delete(nil) || []
+ print_options(shell, global_options)
+
+ # Print all others
+ groups.each do |group_name, options|
+ print_options(shell, options, group_name)
+ end
+ end
+
+ # Receives a set of options and print them.
+ def print_options(shell, options, group_name=nil)
+ return if options.empty?
- options.each do |option|
- item = [ option.usage(padding) ]
- item.push(option.description ? "# #{option.description}" : "")
+ list = []
+ padding = options.collect{ |o| o.aliases.size }.max.to_i * 4
- list << item
- list << [ "", "# Default: #{option.default}" ] if option.show_default?
- end
+ options.each do |option|
+ item = [ option.usage(padding) ]
+ item.push(option.description ? "# #{option.description}" : "")
- unless list.empty?
- shell.say(group_name ? "#{group_name} options:" : "Options:")
- shell.print_table(list, :ident => 2)
- shell.say ""
- end
+ list << item
+ list << [ "", "# Default: #{option.default}" ] if option.show_default?
end
- # Deal with default group
- global_options = groups.delete(nil) || []
- printer.call(ungrouped_name, global_options) if global_options
-
- # Print all others
- groups = extra_group.merge(groups) if extra_group
- groups.each(&printer)
- printer
+ shell.say(group_name ? "#{group_name} options:" : "Options:")
+ shell.print_table(list, :ident => 2)
+ shell.say ""
end
# Raises an error if the word given is a Thor reserved word.
diff --git a/railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/file_binary_read.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/file_binary_read.rb
new file mode 100644
index 0000000000..d6af7e44b0
--- /dev/null
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/file_binary_read.rb
@@ -0,0 +1,9 @@
+class File #:nodoc:
+
+ unless File.respond_to?(:binread)
+ def self.binread(file)
+ File.open(file, 'rb') { |f| f.read }
+ end
+ end
+
+end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/hash_with_indifferent_access.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/hash_with_indifferent_access.rb
index 78bc5cf4bf..78bc5cf4bf 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/hash_with_indifferent_access.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/hash_with_indifferent_access.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/ordered_hash.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/ordered_hash.rb
index 27fea5bb35..27fea5bb35 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/core_ext/ordered_hash.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/core_ext/ordered_hash.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/error.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/error.rb
index f9b31a35d1..f9b31a35d1 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/error.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/error.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/group.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/group.rb
index 0964a9667a..a585b37b73 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/group.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/group.rb
@@ -41,16 +41,12 @@ class Thor::Group
# ==== Options
# short:: When true, shows only usage.
#
- def help(shell, options={})
- if options[:short]
- shell.say banner
- else
- shell.say "Usage:"
- shell.say " #{banner}"
- shell.say
- class_options_help(shell)
- shell.say self.desc if self.desc
- end
+ def help(shell)
+ shell.say "Usage:"
+ shell.say " #{banner}\n"
+ shell.say
+ class_options_help(shell)
+ shell.say self.desc if self.desc
end
# Stores invocations for this class merging with superclass values.
@@ -177,15 +173,11 @@ class Thor::Group
# Overwrite class options help to allow invoked generators options to be
# shown recursively when invoking a generator.
#
- def class_options_help(shell, ungrouped_name=nil, extra_group=nil) #:nodoc:
- group_options = {}
-
- get_options_from_invocations(group_options, class_options) do |klass|
- klass.send(:get_options_from_invocations, group_options, class_options)
+ def class_options_help(shell, groups={}) #:nodoc:
+ get_options_from_invocations(groups, class_options) do |klass|
+ klass.send(:get_options_from_invocations, groups, class_options)
end
-
- group_options.merge!(extra_group) if extra_group
- super(shell, ungrouped_name, group_options)
+ super(shell, groups)
end
# Get invocations array and merge options from invocations. Those
@@ -218,13 +210,26 @@ class Thor::Group
end
end
+ # Returns tasks ready to be printed.
+ def printable_tasks(*)
+ item = []
+ item << banner
+ item << (desc ? "# #{desc.gsub(/\s+/m,' ')}" : "")
+ [item]
+ end
+
protected
# The banner for this class. You can customize it if you are invoking the
# thor class by another ways which is not the Thor::Runner.
#
def banner
- "#{self.namespace} #{self.arguments.map {|a| a.usage }.join(' ')}"
+ "thor #{self_task.formatted_usage(self, false)}"
+ end
+
+ # Represents the whole class as a task.
+ def self_task #:nodoc:
+ Thor::Task::Dynamic.new(self.namespace, class_options)
end
def baseclass #:nodoc:
@@ -243,7 +248,6 @@ class Thor::Group
# Shortcut to invoke with padding and block handling. Use internally by
# invoke and invoke_from_option class methods.
- #
def _invoke_for_class_method(klass, task=nil, *args, &block) #:nodoc:
shell.padding += 1
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/invocation.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/invocation.rb
index 32e6a72454..32e6a72454 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/invocation.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/invocation.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser.rb
index 57a3f6e1a5..57a3f6e1a5 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/argument.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/argument.rb
index aa8ace4719..aa8ace4719 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/argument.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/argument.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/arguments.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/arguments.rb
index fb5d965e06..fb5d965e06 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/arguments.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/arguments.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/option.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/option.rb
index 9e40ec73fa..9e40ec73fa 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/option.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/option.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/options.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/options.rb
index 75092308b5..75092308b5 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/parser/options.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/parser/options.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/rake_compat.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/rake_compat.rb
index 0d0757fdda..0d0757fdda 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/rake_compat.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/rake_compat.rb
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/runner.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/runner.rb
index 9dc70ea069..f197081e3f 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/runner.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/runner.rb
@@ -124,11 +124,7 @@ class Thor::Runner < Thor #:nodoc:
method_options :internal => :boolean
def installed
initialize_thorfiles(nil, true)
-
- klasses = Thor::Base.subclasses
- klasses -= [Thor, Thor::Runner] unless options["internal"]
-
- display_klasses(true, klasses)
+ display_klasses(true, options["internal"])
end
desc "list [SEARCH]", "List the available thor tasks (--substring means .*SEARCH)"
@@ -144,11 +140,15 @@ class Thor::Runner < Thor #:nodoc:
(options[:all] || k.group == group) && k.namespace =~ search
end
- display_klasses(false, klasses)
+ display_klasses(false, false, klasses)
end
private
+ def self.banner(task)
+ "thor " + task.formatted_usage(self, false)
+ end
+
def thor_root
Thor::Util.thor_root
end
@@ -156,7 +156,7 @@ class Thor::Runner < Thor #:nodoc:
def thor_yaml
@thor_yaml ||= begin
yaml_file = File.join(thor_root, "thor.yml")
- yaml = YAML.load_file(yaml_file) if File.exists?(yaml_file)
+ yaml = YAML.load_file(yaml_file) if File.exists?(yaml_file)
yaml || {}
end
end
@@ -215,9 +215,6 @@ class Thor::Runner < Thor #:nodoc:
# 5. c:\ <-- no Thorfiles found!
#
def thorfiles(relevant_to=nil, skip_lookup=false)
- # TODO Remove this dealing with deprecated thor when :namespaces: is available as constants
- save_yaml(thor_yaml) if Thor::Util.convert_constants_to_namespaces(thor_yaml)
-
thorfiles = []
unless skip_lookup
@@ -253,47 +250,54 @@ class Thor::Runner < Thor #:nodoc:
# Display information about the given klasses. If with_module is given,
# it shows a table with information extracted from the yaml file.
#
- def display_klasses(with_modules=false, klasses=Thor.subclasses)
- klasses -= [Thor, Thor::Runner] unless with_modules
+ def display_klasses(with_modules=false, show_internal=false, klasses=Thor::Base.subclasses)
+ klasses -= [Thor, Thor::Runner, Thor::Group] unless show_internal
+
raise Error, "No Thor tasks available" if klasses.empty?
+ show_modules if with_modules && !thor_yaml.empty?
- if with_modules && !thor_yaml.empty?
- info = []
- labels = ["Modules", "Namespaces"]
+ # Remove subclasses
+ klasses.dup.each do |klass|
+ klasses -= Thor::Util.thor_classes_in(klass)
+ end
- info << labels
- info << [ "-" * labels[0].size, "-" * labels[1].size ]
+ list = Hash.new { |h,k| h[k] = [] }
+ groups = klasses.select { |k| k.ancestors.include?(Thor::Group) }
- thor_yaml.each do |name, hash|
- info << [ name, hash[:namespaces].join(", ") ]
- end
+ # Get classes which inherit from Thor
+ (klasses - groups).each { |k| list[k.namespace] += k.printable_tasks(false) }
- print_table info
- say ""
- end
+ # Get classes which inherit from Thor::Base
+ groups.map! { |k| k.printable_tasks(false).first }
+ list["root"] = groups
- unless klasses.empty?
- klasses.dup.each do |klass|
- klasses -= Thor::Util.thor_classes_in(klass)
- end
+ # Order namespaces with default coming first
+ list = list.sort{ |a,b| a[0].sub(/^default/, '') <=> b[0].sub(/^default/, '') }
+ list.each { |n, tasks| display_tasks(n, tasks) unless tasks.empty? }
+ end
- klasses.each { |k| display_tasks(k) }
- else
- say "\033[1;34mNo Thor tasks available\033[0m"
- end
+ def display_tasks(namespace, list) #:nodoc:
+ list.sort!{ |a,b| a[0] <=> b[0] }
+
+ say shell.set_color(namespace, :blue, true)
+ say "-" * namespace.size
+
+ print_table(list, :truncate => true)
+ say
end
- # Display tasks from the given Thor class.
- #
- def display_tasks(klass)
- unless klass.tasks.empty?
- base = klass.namespace
+ def show_modules #:nodoc:
+ info = []
+ labels = ["Modules", "Namespaces"]
- color = base == "default" ? :magenta : :blue
- say shell.set_color(base, color, true)
- say "-" * base.length
+ info << labels
+ info << [ "-" * labels[0].size, "-" * labels[1].size ]
- klass.help(shell, :short => true, :ident => 0, :namespace => true)
+ thor_yaml.each do |name, hash|
+ info << [ name, hash[:namespaces].join(", ") ]
end
+
+ print_table info
+ say ""
end
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell.rb
index 1dc8f0e5b4..64a173de83 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell.rb
@@ -22,7 +22,7 @@ class Thor
end
module Shell
- SHELL_DELEGATED_METHODS = [:ask, :yes?, :no?, :say, :say_status, :print_list, :print_table]
+ SHELL_DELEGATED_METHODS = [:ask, :yes?, :no?, :say, :say_status, :print_table]
# Add shell to initialize config values.
#
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/basic.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell/basic.rb
index ea9665380b..a11f45b4e9 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/basic.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell/basic.rb
@@ -75,30 +75,6 @@ class Thor
!yes?(statement, color)
end
- # Prints a list of items.
- #
- # ==== Parameters
- # list<Array[String, String, ...]>
- #
- # ==== Options
- # mode:: Can be :rows or :inline. Defaults to :rows.
- # ident:: Ident each item with the value given.
- #
- def print_list(list, options={})
- return if list.empty?
-
- ident = " " * (options[:ident] || 0)
- content = case options[:mode]
- when :inline
- last = list.pop
- "#{list.join(", ")}, and #{last}"
- else # rows
- ident + list.join("\n#{ident}")
- end
-
- $stdout.puts content
- end
-
# Prints a table.
#
# ==== Parameters
@@ -110,20 +86,26 @@ class Thor
def print_table(table, options={})
return if table.empty?
- formats = []
+ formats, ident = [], options[:ident].to_i
+ options[:truncate] = terminal_width if options[:truncate] == true
+
0.upto(table.first.length - 2) do |i|
maxima = table.max{ |a,b| a[i].size <=> b[i].size }[i].size
formats << "%-#{maxima + 2}s"
end
- formats[0] = formats[0].insert(0, " " * options[:ident]) if options[:ident]
+ formats[0] = formats[0].insert(0, " " * ident)
formats << "%s"
table.each do |row|
+ sentence = ""
+
row.each_with_index do |column, i|
- $stdout.print formats[i] % column.to_s
+ sentence << formats[i] % column.to_s
end
- $stdout.puts
+
+ sentence = truncate(sentence, options[:truncate]) if options[:truncate]
+ $stdout.puts sentence
end
end
@@ -143,7 +125,7 @@ class Thor
answer = ask %[Overwrite #{destination}? (enter "h" for help) #{options}]
case answer
- when is?(:yes), is?(:force)
+ when is?(:yes), is?(:force), ""
return true
when is?(:no), is?(:skip)
return false
@@ -214,6 +196,44 @@ HELP
base && base.options[:quiet]
end
+ # This code was copied from Rake, available under MIT-LICENSE
+ # Copyright (c) 2003, 2004 Jim Weirich
+ def terminal_width
+ if ENV['THOR_COLUMNS']
+ result = ENV['THOR_COLUMNS'].to_i
+ else
+ result = unix? ? dynamic_width : 80
+ end
+ (result < 10) ? 80 : result
+ rescue
+ 80
+ end
+
+ # Calculate the dynamic width of the terminal
+ def dynamic_width
+ @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
+ end
+
+ def dynamic_width_stty
+ %x{stty size 2>/dev/null}.split[1].to_i
+ end
+
+ def dynamic_width_tput
+ %x{tput cols 2>/dev/null}.to_i
+ end
+
+ def unix?
+ RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
+ end
+
+ def truncate(string, width)
+ if string.length <= width
+ string
+ else
+ ( string[0, width-3] || "" ) + "..."
+ end
+ end
+
end
end
end
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/color.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell/color.rb
index 24704f7885..b2bc66dfba 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/shell/color.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/shell/color.rb
@@ -63,7 +63,7 @@ class Thor
#
def show_diff(destination, content) #:nodoc:
if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil?
- actual = File.read(destination).to_s.split("\n")
+ actual = File.binread(destination).to_s.split("\n")
content = content.to_s.split("\n")
Diff::LCS.sdiff(actual, content).each do |diff|
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/task.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/task.rb
index 91c7564d3f..5c8877591b 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/task.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/task.rb
@@ -1,11 +1,11 @@
class Thor
class Task < Struct.new(:name, :description, :usage, :options)
+ FILE_REGEXP = /^#{Regexp.escape(File.expand_path(__FILE__))}:[\w:]+ `run'$/
# A dynamic task that handles method missing scenarios.
- #
class Dynamic < Task
- def initialize(name)
- super(name.to_s, "A dynamically-generated task", name.to_s)
+ def initialize(name, options=nil)
+ super(name.to_s, "A dynamically-generated task", name.to_s, options)
end
def run(instance, args=[])
@@ -25,84 +25,73 @@ class Thor
self.options = other.options.dup if other.options
end
- def short_description
- description.split("\n").first if description
- end
-
# By default, a task invokes a method in the thor class. You can change this
# implementation to create custom tasks.
- #
def run(instance, args=[])
raise UndefinedTaskError, "the '#{name}' task of #{instance.class} is private" unless public_method?(instance)
instance.send(name, *args)
rescue ArgumentError => e
+ raise e if instance.class.respond_to?(:debugging) && instance.class.debugging
parse_argument_error(instance, e, caller)
rescue NoMethodError => e
+ raise e if instance.class.respond_to?(:debugging) && instance.class.debugging
parse_no_method_error(instance, e)
end
- # Returns the formatted usage. If a class is given, the class arguments are
- # injected in the usage.
- #
- def formatted_usage(klass=nil, namespace=false, show_options=true)
- formatted = if namespace.is_a?(String)
- "#{namespace}:"
- elsif klass && namespace
- "#{klass.namespace.gsub(/^default/,'')}:"
+ # Returns the formatted usage by injecting given required arguments
+ # and required options into the given usage.
+ def formatted_usage(klass, namespace=nil)
+ namespace = klass.namespace if namespace.nil?
+
+ # Add namespace
+ formatted = if namespace
+ "#{namespace.gsub(/^(default|thor:runner:)/,'')}:"
else
""
end
- formatted << formatted_arguments(klass)
- formatted << " #{formatted_options}" if show_options
- formatted.strip!
- formatted
- end
-
- # Injects the class arguments into the task usage.
- #
- def formatted_arguments(klass)
- if klass && !klass.arguments.empty?
+ # Add usage with required arguments
+ formatted << if klass && !klass.arguments.empty?
usage.to_s.gsub(/^#{name}/) do |match|
- match << " " << klass.arguments.map{ |a| a.usage }.join(' ')
+ match << " " << klass.arguments.map{ |a| a.usage }.compact.join(' ')
end
else
usage.to_s
end
- end
- # Returns the options usage for this task.
- #
- def formatted_options
- @formatted_options ||= options.map{ |_, o| o.usage }.sort.join(" ")
+ # Add required options
+ formatted << " #{required_options}"
+
+ # Strip and go!
+ formatted.strip
end
protected
+ def required_options
+ @required_options ||= options.map{ |_, o| o.usage if o.required? }.compact.sort.join(" ")
+ end
+
# Given a target, checks if this class name is not a private/protected method.
- #
def public_method?(instance) #:nodoc:
collection = instance.private_methods + instance.protected_methods
(collection & [name.to_s, name.to_sym]).empty?
end
- # Clean everything that comes from the Thor gempath and remove the caller.
- #
- def sans_backtrace(backtrace, caller) #:nodoc:
- dirname = /^#{Regexp.escape(File.dirname(__FILE__))}/
- saned = backtrace.reject { |frame| frame =~ dirname }
- saned -= caller
+ # For Ruby <= 1.8.7, we have to match the method name that we are trying to call.
+ # In Ruby >= 1.9.1, we have to match the method run in this file.
+ def backtrace_match?(backtrace) #:nodoc:
+ method_name = /`#{Regexp.escape(name.split(':').last)}'/
+ backtrace =~ method_name || backtrace =~ FILE_REGEXP
end
def parse_argument_error(instance, e, caller) #:nodoc:
- backtrace = sans_backtrace(e.backtrace, caller)
-
- if backtrace.empty? && e.message =~ /wrong number of arguments/
+ if e.message =~ /wrong number of arguments/ && backtrace_match?(e.backtrace.first.to_s)
if instance.is_a?(Thor::Group)
raise e, "'#{name}' was called incorrectly. Are you sure it has arity equals to 0?"
else
raise InvocationError, "'#{name}' was called incorrectly. Call as " <<
- "'#{formatted_usage(instance.class, true)}'"
+ "'#{formatted_usage(instance.class)}'"
end
else
raise e
diff --git a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/util.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/util.rb
index ebae0a3193..c2aed89ccf 100644
--- a/railties/lib/rails/vendor/thor-0.12.0/lib/thor/util.rb
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/util.rb
@@ -76,8 +76,10 @@ class Thor
# Returns the thor classes declared inside the given class.
#
def self.thor_classes_in(klass)
+ stringfied_constants = klass.constants.map { |c| c.to_s }
Thor::Base.subclasses.select do |subclass|
- klass.constants.include?(subclass.name.gsub("#{klass.name}::", ''))
+ next unless subclass.name
+ stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", ''))
end
end
@@ -155,7 +157,7 @@ class Thor
# inside the sandbox to avoid namespacing conflicts.
#
def self.load_thorfile(path, content=nil)
- content ||= File.read(path)
+ content ||= File.binread(path)
begin
Thor::Sandbox.class_eval(content, path)
@@ -164,26 +166,6 @@ class Thor
end
end
- # Receives a yaml (hash) and updates all constants entries to namespace.
- # This was added to deal with deprecated versions of Thor.
- #
- # TODO Deprecate this method in the future.
- #
- # ==== Returns
- # TrueClass|FalseClass:: Returns true if any change to the yaml file was made.
- #
- def self.convert_constants_to_namespaces(yaml)
- yaml_changed = false
-
- yaml.each do |k, v|
- next unless v[:constants] && v[:namespaces].nil?
- yaml_changed = true
- yaml[k][:namespaces] = v[:constants].map{|c| Thor::Util.namespace_from_thor_class(c)}
- end
-
- yaml_changed
- end
-
def self.user_home
@@user_home ||= if ENV["HOME"]
ENV["HOME"]
diff --git a/railties/lib/rails/vendor/thor-0.12.3/lib/thor/version.rb b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/version.rb
new file mode 100644
index 0000000000..3c9dd6f808
--- /dev/null
+++ b/railties/lib/rails/vendor/thor-0.12.3/lib/thor/version.rb
@@ -0,0 +1,3 @@
+class Thor
+ VERSION = "0.12.3".freeze
+end
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
new file mode 100644
index 0000000000..a060c3c301
--- /dev/null
+++ b/railties/railties.gemspec
@@ -0,0 +1,28 @@
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'railties'
+ s.version = '3.0.pre'
+ s.summary = "Controls boot-up, rake tasks and generators for the Rails framework."
+ s.description = <<-EOF
+ Rails is a framework for building web-application using CGI, FCGI, mod_ruby, or WEBrick
+ on top of either MySQL, PostgreSQL, SQLite, DB2, SQL Server, or Oracle with eRuby- or Builder-based templates.
+ EOF
+
+ s.add_dependency('rake', '>= 0.8.3')
+ s.add_dependency('activesupport', '= 3.0.pre')
+ s.add_dependency('actionpack', '= 3.0.pre')
+
+ s.rdoc_options << '--exclude' << '.'
+ s.has_rdoc = false
+
+ s.files = Dir['CHANGELOG', 'README', 'bin/**/*', 'builtin/**/*', 'guides/**/*', 'lib/**/{*,.[a-z]*}']
+ s.require_path = 'lib'
+ s.bindir = "bin"
+ s.executables = ["rails"]
+ s.default_executable = "rails"
+
+ s.author = "David Heinemeier Hansson"
+ s.email = "david@loudthinking.com"
+ s.homepage = "http://www.rubyonrails.org"
+ s.rubyforge_project = "rails"
+end
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index 47013d7797..2d6983076a 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -20,8 +20,10 @@ require 'active_support/core_ext/logger'
require 'active_support/test_case'
require 'action_controller'
-require 'rails'
+require 'rails/all'
-Rails::Initializer.run do |config|
+# TODO: Remove these hacks
+class TestApp < Rails::Application
config.root = File.dirname(__FILE__)
end
+Rails.application = TestApp
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index a3e1916494..79dfacdcdb 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -4,9 +4,19 @@ module ApplicationTests
class InitializerTest < Test::Unit::TestCase
include ActiveSupport::Testing::Isolation
+ def new_app
+ File.expand_path("#{app_path}/../new_app")
+ end
+
+ def copy_app
+ FileUtils.cp_r(app_path, new_app)
+ end
+
def setup
+ FileUtils.rm_rf(new_app) if File.directory?(new_app)
build_app
boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
end
test "the application root is set correctly" do
@@ -14,35 +24,103 @@ module ApplicationTests
assert_equal Pathname.new(app_path), Rails.application.root
end
+ test "the application root can be seen from the application singleton" do
+ require "#{app_path}/config/environment"
+ assert_equal Pathname.new(app_path), AppTemplate::Application.root
+ end
+
test "the application root can be set" do
- FileUtils.mkdir_p("#{app_path}/hello")
+ copy_app
add_to_config <<-RUBY
- config.frameworks = []
- config.root = '#{app_path}/hello'
+ config.root = '#{new_app}'
RUBY
+
+ use_frameworks []
+
+ require "#{app_path}/config/environment"
+ assert_equal Pathname.new(new_app), Rails.application.root
+ end
+
+ test "the application root is Dir.pwd if there is no config.ru" do
+ File.delete("#{app_path}/config.ru")
+
+ use_frameworks []
+
+ Dir.chdir("#{app_path}") do
+ require "#{app_path}/config/environment"
+ assert_equal Pathname.new("#{app_path}"), Rails.application.root
+ end
+ end
+
+ test "if there's no config.active_support.bare, all of ActiveSupport is required" do
+ use_frameworks []
require "#{app_path}/config/environment"
- assert_equal Pathname.new("#{app_path}/hello"), Rails.application.root
+ assert_nothing_raised { [1,2,3].rand }
end
- test "the application root is detected as where config.ru is located" do
+ test "config.active_support.bare does not require all of ActiveSupport" do
+ add_to_config "config.active_support.bare = true"
+
+ use_frameworks []
+
+ Dir.chdir("#{app_path}/app") do
+ require "#{app_path}/config/environment"
+ assert_raises(NoMethodError) { [1,2,3].rand }
+ end
+ end
+
+ test "marking the application as threadsafe sets the correct config variables" do
add_to_config <<-RUBY
- config.frameworks = []
+ config.threadsafe!
RUBY
- FileUtils.mv "#{app_path}/config.ru", "#{app_path}/config/config.ru"
+
+ require "#{app_path}/config/application"
+ assert AppTemplate::Application.config.action_controller.allow_concurrency
+ 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
+ config.threadsafe!
+ RUBY
+
+ use_frameworks []
+
+ assert_nothing_raised do
+ require "#{app_path}/config/application"
+ end
+ end
+
+ test "Frameworks are not preloaded by default" do
require "#{app_path}/config/environment"
- assert_equal Pathname.new("#{app_path}/config"), Rails.application.root
+
+ assert ActionController.autoload?(:RecordIdentifier)
end
- test "the application root is Dir.pwd if there is no config.ru" do
- File.delete("#{app_path}/config.ru")
+ test "frameworks are preloaded with config.preload_frameworks is set" do
add_to_config <<-RUBY
- config.frameworks = []
+ config.preload_frameworks = true
RUBY
- Dir.chdir("#{app_path}/app") do
+ require "#{app_path}/config/environment"
+
+ 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"
- assert_equal Pathname.new("#{app_path}/app"), Rails.application.root
end
end
end
-end \ No newline at end of file
+end
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
index ccbcd84176..0c858d6394 100644
--- a/railties/test/application/generators_test.rb
+++ b/railties/test/application/generators_test.rb
@@ -7,12 +7,20 @@ module ApplicationTests
def setup
build_app
boot_rails
- require "rails"
+ end
+
+ def app_const
+ @app_const ||= Class.new(Rails::Application)
+ end
+
+ def with_config
+ require "rails/all"
require "rails/generators"
+ yield app_const.config
end
test "generators default values" do
- Rails::Initializer.run do |c|
+ with_config do |c|
assert_equal(true, c.generators.colorize_logging)
assert_equal({}, c.generators.aliases)
assert_equal({}, c.generators.options)
@@ -20,7 +28,7 @@ module ApplicationTests
end
test "generators set rails options" do
- Rails::Initializer.run do |c|
+ with_config do |c|
c.generators.orm = :datamapper
c.generators.test_framework = :rspec
c.generators.helper = false
@@ -30,7 +38,7 @@ module ApplicationTests
end
test "generators set rails aliases" do
- Rails::Initializer.run do |c|
+ with_config do |c|
c.generators.aliases = { :rails => { :test_framework => "-w" } }
expected = { :rails => { :test_framework => "-w" } }
assert_equal expected, c.generators.aliases
@@ -38,14 +46,15 @@ module ApplicationTests
end
test "generators aliases and options on initialization" do
- Rails::Initializer.run do |c|
- c.frameworks = []
- c.generators.rails :aliases => { :test_framework => "-w" }
- c.generators.orm :datamapper
- c.generators.test_framework :rspec
- end
+ add_to_config <<-RUBY
+ config.generators.rails :aliases => { :test_framework => "-w" }
+ config.generators.orm :datamapper
+ config.generators.test_framework :rspec
+ RUBY
+
+ require "#{app_path}/config/environment"
# Initialize the application
- Rails.initialize!
+ require "rails/generators"
Rails::Generators.configure!
assert_equal :rspec, Rails::Generators.options[:rails][:test_framework]
@@ -53,19 +62,20 @@ module ApplicationTests
end
test "generators no color on initialization" do
- Rails::Initializer.run do |c|
- c.frameworks = []
- c.generators.colorize_logging = false
- end
+ add_to_config <<-RUBY
+ config.generators.colorize_logging = false
+ RUBY
+
# Initialize the application
- Rails.initialize!
+ require "#{app_path}/config/environment"
+ require "rails/generators"
Rails::Generators.configure!
assert_equal Thor::Base.shell, Thor::Shell::Basic
end
test "generators with hashes for options and aliases" do
- Rails::Initializer.run do |c|
+ with_config do |c|
c.generators do |g|
g.orm :datamapper, :migration => false
g.plugin :aliases => { :generator => "-g" },
@@ -84,7 +94,7 @@ module ApplicationTests
end
test "generators with hashes are deep merged" do
- Rails::Initializer.run do |c|
+ with_config do |c|
c.generators do |g|
g.orm :datamapper, :migration => false
g.plugin :aliases => { :generator => "-g" },
diff --git a/railties/test/application/initializer_test.rb b/railties/test/application/initializer_test.rb
index 719520bf68..3fd0b0e5df 100644
--- a/railties/test/application/initializer_test.rb
+++ b/railties/test/application/initializer_test.rb
@@ -7,45 +7,18 @@ module ApplicationTests
def setup
build_app
boot_rails
- require "rails"
- end
-
- test "initializing an application initializes rails" do
- Rails::Initializer.run do |config|
- config.root = app_path
- end
-
- if RUBY_VERSION < '1.9'
- $KCODE = ''
- Rails.initialize!
- assert_equal 'UTF8', $KCODE
- else
- Encoding.default_external = Encoding::US_ASCII
- Rails.initialize!
- assert_equal Encoding::UTF_8, Encoding.default_external
- end
+ FileUtils.rm_rf "#{app_path}/config/environments"
end
test "initializing an application adds the application paths to the load path" do
- Rails::Initializer.run do |config|
- config.root = app_path
- end
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
- Rails.initialize!
+ require "#{app_path}/config/environment"
assert $:.include?("#{app_path}/app/models")
end
- test "adding an unknown framework raises an error" do
- Rails::Initializer.run do |config|
- config.root = app_path
- config.frameworks << :action_foo
- end
-
- assert_raises RuntimeError do
- Rails.initialize!
- end
- end
-
test "eager loading loads parent classes before children" do
app_file "lib/zoo.rb", <<-ZOO
class Zoo ; include ReptileHouse ; end
@@ -54,12 +27,12 @@ module ApplicationTests
module Zoo::ReptileHouse ; end
ZOO
- Rails::Initializer.run do |config|
- config.root = app_path
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
config.eager_load_paths = "#{app_path}/lib"
- end
+ RUBY
- Rails.initialize!
+ require "#{app_path}/config/environment"
assert Zoo
end
@@ -67,41 +40,44 @@ module ApplicationTests
test "load environment with global" do
app_file "config/environments/development.rb", "$initialize_test_set_from_env = 'success'"
assert_nil $initialize_test_set_from_env
- Rails::Initializer.run { |config| config.root = app_path }
- Rails.initialize!
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+ require "#{app_path}/config/environment"
assert_equal "success", $initialize_test_set_from_env
end
test "action_controller load paths set only if action controller in use" do
assert_nothing_raised NameError do
- Rails::Initializer.run do |config|
- config.root = app_path
- config.frameworks = []
- end
- Rails.initialize!
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+
+ use_frameworks []
+ require "#{app_path}/config/environment"
end
end
test "after_initialize block works correctly" do
- Rails::Initializer.run do |config|
- config.root = app_path
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
config.after_initialize { $test_after_initialize_block1 = "success" }
config.after_initialize { $test_after_initialize_block2 = "congratulations" }
- end
- Rails.initialize!
+ RUBY
+ require "#{app_path}/config/environment"
assert_equal "success", $test_after_initialize_block1
assert_equal "congratulations", $test_after_initialize_block2
end
test "after_initialize block works correctly when no block is passed" do
- Rails::Initializer.run do |config|
- config.root = app_path
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
config.after_initialize { $test_after_initialize_block1 = "success" }
config.after_initialize # don't pass a block, this is what we're testing!
config.after_initialize { $test_after_initialize_block2 = "congratulations" }
- end
- Rails.initialize!
+ RUBY
+ require "#{app_path}/config/environment"
assert_equal "success", $test_after_initialize_block1
assert_equal "congratulations", $test_after_initialize_block2
@@ -109,35 +85,40 @@ module ApplicationTests
# i18n
test "setting another default locale" do
- Rails::Initializer.run do |config|
- config.root = app_path
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
config.i18n.default_locale = :de
- end
- Rails.initialize!
+ RUBY
+ require "#{app_path}/config/environment"
assert_equal :de, I18n.default_locale
end
test "no config locales dir present should return empty load path" do
FileUtils.rm_rf "#{app_path}/config/locales"
- Rails::Initializer.run do |c|
- c.root = app_path
- assert_equal [], c.i18n.load_path
- end
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+ require "#{app_path}/config/environment"
+
+ assert_equal [], Rails.application.config.i18n.load_path
end
test "config locales dir present should be added to load path" do
- Rails::Initializer.run do |c|
- c.root = app_path
- assert_equal ["#{app_path}/config/locales/en.yml"], c.i18n.load_path
- end
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert_equal ["#{app_path}/config/locales/en.yml"], Rails.application.config.i18n.load_path
end
test "config defaults should be added with config settings" do
- Rails::Initializer.run do |c|
- c.root = app_path
- c.i18n.load_path << "my/other/locale.yml"
- end
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.i18n.load_path << "my/other/locale.yml"
+ RUBY
+ require "#{app_path}/config/environment"
assert_equal [
"#{app_path}/config/locales/en.yml", "my/other/locale.yml"
@@ -146,64 +127,48 @@ module ApplicationTests
# DB middleware
test "database middleware doesn't initialize when session store is not active_record" do
- Rails::Initializer.run do |config|
- config.root = app_path
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
config.action_controller.session_store = :cookie_store
- end
- Rails.initialize!
+ RUBY
+ require "#{app_path}/config/environment"
assert !Rails.application.config.middleware.include?(ActiveRecord::SessionStore)
end
- test "database middleware doesn't initialize when activerecord is not in frameworks" do
- Rails::Initializer.run do |c|
- c.root = app_path
- c.frameworks = []
- end
- assert_equal [], Rails.application.config.middleware
- end
-
test "database middleware initializes when session store is active record" do
- Rails::Initializer.run do |c|
- c.root = app_path
- c.action_controller.session_store = :active_record_store
- end
- Rails.initialize!
+ add_to_config "config.action_controller.session_store = :active_record_store"
+
+ require "#{app_path}/config/environment"
expects = [ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActiveRecord::SessionStore]
middleware = Rails.application.config.middleware.map { |m| m.klass }
assert_equal expects, middleware & expects
end
- test "ensure database middleware doesn't use action_controller on initializing" do
- Rails::Initializer.run do |c|
- c.root = app_path
- c.frameworks -= [:action_controller]
- c.action_controller.session_store = :active_record_store
- end
- Rails.initialize!
-
- assert !Rails.application.config.middleware.include?(ActiveRecord::SessionStore)
+ test "Rails.root should be a Pathname" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+ require "#{app_path}/config/environment"
+ assert_instance_of Pathname, Rails.root
end
+ end
- # Pathview test
- test "load view paths doesn't perform anything when action_view not in frameworks" do
- Rails::Initializer.run do |c|
- c.root = app_path
- c.frameworks -= [:action_view]
- end
- Rails.initialize!
+ class InitializerCustomFrameworkExtensionsTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
- assert_equal nil, ActionMailer::Base.template_root
- assert_equal [], ActionController::Base.view_paths
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
end
- test "Rails.root should be a Pathname" do
- Rails::Initializer.run do |c|
- c.root = app_path
- end
- Rails.initialize!
- assert_instance_of Pathname, Rails.root
+ test "database middleware doesn't initialize when activerecord is not in frameworks" do
+ use_frameworks []
+ require "#{app_path}/config/environment"
+
+ assert_nil defined?(ActiveRecord)
end
end
-end \ No newline at end of file
+end
diff --git a/railties/test/application/load_test.rb b/railties/test/application/load_test.rb
index 3da51c4355..1c5811b07a 100644
--- a/railties/test/application/load_test.rb
+++ b/railties/test/application/load_test.rb
@@ -1,27 +1,13 @@
require "isolation/abstract_unit"
-# require "rails"
-# require 'action_dispatch'
module ApplicationTests
class LoadTest < Test::Unit::TestCase
include ActiveSupport::Testing::Isolation
def rackup
- config = "#{app_path}/config.ru"
- # Copied from ActionDispatch::Utils.parse_config
- # ActionDispatch is not necessarily available at this point.
- require 'rack'
- if config =~ /\.ru$/
- cfgfile = ::File.read(config)
- if cfgfile[/^#\\(.*)/]
- opts.parse! $1.split(/\s+/)
- end
- inner_app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
- nil, config
- else
- require config
- inner_app = Object.const_get(::File.basename(config, '.rb').capitalize)
- end
+ require "rack"
+ app, options = Rack::Builder.parse_file("#{app_path}/config.ru")
+ app
end
def setup
@@ -34,20 +20,22 @@ module ApplicationTests
end
test "config.ru can be racked up" do
- @app = rackup
- assert_welcome get("/")
+ Dir.chdir app_path do
+ @app = rackup
+ assert_welcome get("/")
+ end
end
test "Rails.application is available after config.ru has been racked up" do
rackup
- assert Rails.application < Rails::Application
+ assert Rails.application.is_a?(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 ActionController::Dispatcher.new < Rails::Application
+ assert ActionController::Dispatcher.new.is_a?(Rails::Application)
end
test "the config object is available on the application object" do
diff --git a/railties/test/application/notifications_test.rb b/railties/test/application/notifications_test.rb
index 62ed4f4ad4..b57e829cca 100644
--- a/railties/test/application/notifications_test.rb
+++ b/railties/test/application/notifications_test.rb
@@ -1,46 +1,39 @@
require "isolation/abstract_unit"
module ApplicationTests
- class NotificationsTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
-
- class MyQueue
- attr_reader :events, :subscribers
-
- def initialize
- @events = []
- @subscribers = []
- end
-
- def publish(name, *args)
- @events << name
- end
+ class MyQueue
+ def publish(name, *args)
+ raise name
+ end
- def subscribe(pattern=nil, &block)
- @subscribers << pattern
- end
+ # Not a full queue implementation
+ def method_missing(name, *args, &blk)
+ self
end
+ end
+
+ class NotificationsTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
def setup
build_app
boot_rails
- require "rails"
+ FileUtils.rm_rf("#{app_path}/config/environments")
require "active_support/notifications"
- Rails::Initializer.run do |c|
- c.notifications.queue = MyQueue.new
- c.notifications.subscribe(/listening/) do
- puts "Cool"
- end
- end
+ @events = []
+
+ add_to_config <<-RUBY
+ config.notifications.notifier = ActiveSupport::Notifications::Notifier.new(ApplicationTests::MyQueue.new)
+ RUBY
end
test "new queue is set" do
- ActiveSupport::Notifications.instrument(:foo)
- assert_equal :foo, ActiveSupport::Notifications.queue.events.first
- end
+ use_frameworks []
+ require "#{app_path}/config/environment"
- test "configuration subscribers are loaded" do
- assert_equal 1, ActiveSupport::Notifications.queue.subscribers.count { |s| s == /listening/ }
+ assert_raise RuntimeError do
+ ActiveSupport::Notifications.publish('foo')
+ end
end
end
end
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
new file mode 100644
index 0000000000..725dd06929
--- /dev/null
+++ b/railties/test/application/routing_test.rb
@@ -0,0 +1,180 @@
+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 app
+ @app ||= begin
+ require "#{app_path}/config/environment"
+
+ Rails.application
+ end
+ end
+
+ test "rails/info/properties" do
+ get "/rails/info/properties"
+ assert_equal 200, last_response.status
+ end
+
+ test "simple controller" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :text => "foo"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match ':controller(/:action)'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+ end
+
+ test "multiple controllers" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :text => "foo"
+ end
+ end
+ RUBY
+
+ controller :bar, <<-RUBY
+ class BarController < ActionController::Base
+ def index
+ render :text => "bar"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match ':controller(/:action)'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+
+ get '/bar'
+ assert_equal 'bar', last_response.body
+ end
+
+ test "nested controller" do
+ controller 'foo', <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :text => "foo"
+ end
+ end
+ RUBY
+
+ controller 'admin/foo', <<-RUBY
+ module Admin
+ class FooController < ActionController::Base
+ def index
+ render :text => "admin::foo"
+ end
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match ':controller(/:action)'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+
+ get '/admin/foo'
+ assert_equal 'admin::foo', last_response.body
+ end
+
+ test "merges with plugin routes" do
+ controller 'foo', <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :text => "foo"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match 'foo', :to => 'foo#index'
+ end
+ RUBY
+
+ plugin 'bar', 'require File.dirname(__FILE__) + "/app/controllers/bar"' do |plugin|
+ plugin.write 'app/controllers/bar.rb', <<-RUBY
+ class BarController < ActionController::Base
+ def index
+ render :text => "bar"
+ end
+ end
+ RUBY
+
+ plugin.write 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match 'bar', :to => 'bar#index'
+ end
+ RUBY
+ end
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+
+ get '/bar'
+ assert_equal 'bar', last_response.body
+ end
+
+ test "reloads routes when configuration is changed" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def bar
+ render :text => "bar"
+ end
+
+ def baz
+ render :text => "baz"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match 'foo', :to => 'foo#bar'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'bar', last_response.body
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do |map|
+ match 'foo', :to => 'foo#baz'
+ end
+ RUBY
+
+ sleep 0.1
+
+ get '/foo'
+ assert_equal 'baz', last_response.body
+ end
+ end
+end
diff --git a/railties/test/fixtures/plugins/engines/engine/config/routes.rb b/railties/test/fixtures/plugins/engines/engine/config/routes.rb
index cca8d1b146..da44595693 100644
--- a/railties/test/fixtures/plugins/engines/engine/config/routes.rb
+++ b/railties/test/fixtures/plugins/engines/engine/config/routes.rb
@@ -1,3 +1,3 @@
ActionController::Routing::Routes.draw do |map|
- map.connect '/engine', :controller => "engine"
+ match '/engine', :to => "engine"
end
diff --git a/railties/test/fixtures/vendor/plugins/mspec/lib/generators/mspec_generator.rb b/railties/test/fixtures/vendor/plugins/mspec/lib/rails_generators/mspec_generator.rb
index 191bdbf2fc..191bdbf2fc 100644
--- a/railties/test/fixtures/vendor/plugins/mspec/lib/generators/mspec_generator.rb
+++ b/railties/test/fixtures/vendor/plugins/mspec/lib/rails_generators/mspec_generator.rb
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index 7d03a37f2a..27b6a49566 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -1,8 +1,10 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/app/app_generator'
class ActionsTest < GeneratorsTestCase
+ tests Rails::Generators::AppGenerator
+ arguments [destination_root]
+
def setup
super
@git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git'
@@ -171,21 +173,13 @@ class ActionsTest < GeneratorsTestCase
def test_route_should_add_data_to_the_routes_block_in_config_routes
run_generator
- route_command = "map.route '/login', :controller => 'sessions', :action => 'new'"
+ route_command = "route '/login', :controller => 'sessions', :action => 'new'"
action :route, route_command
assert_file 'config/routes.rb', /#{Regexp.escape(route_command)}/
end
protected
- def run_generator
- silence(:stdout) { Rails::Generators::AppGenerator.start [destination_root] }
- end
-
- def generator(config={})
- @generator ||= Rails::Generators::Base.new([], {}, { :destination_root => destination_root }.merge!(config))
- end
-
def action(*args, &block)
silence(:stdout){ generator.send(*args, &block) }
end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 10d0bc6bc2..7dd798db75 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -3,6 +3,7 @@ require 'generators/generators_test_helper'
require 'rails/generators/rails/app/app_generator'
class AppGeneratorTest < GeneratorsTestCase
+ arguments [destination_root]
def setup
super
@@ -49,24 +50,35 @@ class AppGeneratorTest < GeneratorsTestCase
end
def test_invalid_database_option_raises_an_error
- content = capture(:stderr){ run_generator(["-d", "unknown"]) }
+ 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){ Rails::Generators::AppGenerator.start [File.join(destination_root, "43-things")] }
+ assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content
+ end
+
+ def test_invalid_application_name_is_fixed
+ silence(:stdout){ Rails::Generators::AppGenerator.start [File.join(destination_root, "things-43")] }
+ assert_file "things-43/config/environment.rb", /Things43::Application/
+ end
+
def test_config_database_is_added_by_default
run_generator
assert_file "config/database.yml", /sqlite3/
end
def test_config_database_is_not_added_if_skip_activerecord_is_given
- run_generator ["--skip-activerecord"]
+ run_generator [destination_root, "--skip-activerecord"]
assert_no_file "config/database.yml"
end
- def test_activerecord_is_removed_from_frameworks_if_skip_activerecord_is_given
- run_generator ["--skip-activerecord"]
- assert_file "config/application.rb", /config\.frameworks \-= \[ :active_record \]/
- end
+ # TODO: Bring this back using requires
+ # def test_activerecord_is_removed_from_frameworks_if_skip_activerecord_is_given
+ # run_generator ["--skip-activerecord"]
+ # assert_file "config/application.rb", /config\.frameworks \-= \[ :active_record \]/
+ # end
def test_prototype_and_test_unit_are_added_by_default
run_generator
@@ -75,13 +87,13 @@ class AppGeneratorTest < GeneratorsTestCase
end
def test_prototype_and_test_unit_are_skipped_if_required
- run_generator ["--skip-prototype", "--skip-testunit"]
+ run_generator [destination_root, "--skip-prototype", "--skip-testunit"]
assert_no_file "public/javascripts/prototype.js"
assert_no_file "test"
end
def test_shebang_is_added_to_files
- run_generator ["--ruby", "foo/bar/baz"]
+ run_generator [destination_root, "--ruby", "foo/bar/baz"]
%w(
about
@@ -96,7 +108,7 @@ class AppGeneratorTest < GeneratorsTestCase
end
def test_shebang_when_is_the_same_as_default_use_env
- run_generator ["--ruby", Thor::Util.ruby_command]
+ run_generator [destination_root, "--ruby", Thor::Util.ruby_command]
%w(
about
@@ -112,11 +124,11 @@ class AppGeneratorTest < GeneratorsTestCase
def test_template_from_dir_pwd
FileUtils.cd(Rails.root)
- assert_match /It works from file!/, run_generator(["-m", "lib/template.rb"])
+ 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(["-m", "non/existant/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
@@ -126,7 +138,7 @@ class AppGeneratorTest < GeneratorsTestCase
template = %{ say "It works!" }
template.instance_eval "def read; self; end" # Make the string respond to read
- generator(:template => path, :database => "sqlite3").expects(:open).with(path).returns(template)
+ generator([destination_root], :template => path, :database => "sqlite3").expects(:open).with(path).returns(template)
assert_match /It works!/, silence(:stdout){ generator.invoke }
end
@@ -149,15 +161,20 @@ class AppGeneratorTest < GeneratorsTestCase
assert_file 'lib/test_file.rb', 'heres test data'
end
- protected
+ def test_dev_option
+ run_generator [destination_root, "--dev"]
+ rails_path = File.expand_path('../../..', Rails.root)
+ dev_gem = %(gem "rails", :path => #{rails_path.inspect})
+ assert_file 'Gemfile', /^#{Regexp.escape(dev_gem)}$/
+ end
- def run_generator(args=[])
- silence(:stdout) { Rails::Generators::AppGenerator.start [destination_root].concat(args) }
- end
+ def test_edge_option
+ run_generator [destination_root, "--edge"]
+ edge_gem = %(gem "rails", :git => "git://github.com/rails/rails.git")
+ assert_file 'Gemfile', /^#{Regexp.escape(edge_gem)}$/
+ end
- def generator(options={})
- @generator ||= Rails::Generators::AppGenerator.new([destination_root], options, :destination_root => destination_root)
- end
+ protected
def action(*args, &block)
silence(:stdout){ generator.send(*args, &block) }
diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb
index 56bc688ad0..8e2fd3b9ed 100644
--- a/railties/test/generators/controller_generator_test.rb
+++ b/railties/test/generators/controller_generator_test.rb
@@ -1,12 +1,12 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/controller/controller_generator'
class ControllerGeneratorTest < GeneratorsTestCase
+ arguments %w(Account foo bar)
def test_help_does_not_show_invoked_generators_options_if_they_already_exist
content = run_generator ["--help"]
- assert_no_match /Helper options:/, content
+ assert_no_match /Helper options\:/, content
end
def test_controller_skeleton_is_created
@@ -66,15 +66,8 @@ class ControllerGeneratorTest < GeneratorsTestCase
run_generator
assert_file "app/controllers/account_controller.rb" do |controller|
- assert_instance_method controller, :foo
- assert_instance_method controller, :bar
+ assert_instance_method :foo, controller
+ assert_instance_method :bar, controller
end
end
-
- protected
-
- def run_generator(args=["Account", "foo", "bar"])
- silence(:stdout) { Rails::Generators::ControllerGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb
index aea3f4da51..28377f23b0 100644
--- a/railties/test/generators/generator_generator_test.rb
+++ b/railties/test/generators/generator_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/generator/generator_generator'
class GeneratorGeneratorTest < GeneratorsTestCase
+ arguments %w(awesome)
def test_generator_skeleton_is_created
run_generator
@@ -16,11 +16,4 @@ class GeneratorGeneratorTest < GeneratorsTestCase
assert_file "lib/generators/awesome/awesome_generator.rb",
/class AwesomeGenerator < Rails::Generators::NamedBase/
end
-
- protected
-
- def run_generator(args=["awesome"], config={})
- silence(:stdout) { Rails::Generators::GeneratorGenerator.start args, config.merge(:destination_root => destination_root) }
- end
-
end
diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb
index 4ce48a453b..fcd0989fd7 100644
--- a/railties/test/generators/generators_test_helper.rb
+++ b/railties/test/generators/generators_test_helper.rb
@@ -10,93 +10,19 @@ end
Rails.application.config.root = Rails.root
require 'rails/generators'
+require 'rails/generators/test_case'
+
require 'rubygems'
require 'active_record'
require 'action_dispatch'
-CURRENT_PATH = File.expand_path(Dir.pwd)
-Rails::Generators.no_color!
-
-class GeneratorsTestCase < ActiveSupport::TestCase
- include FileUtils
-
- def destination_root
- File.join(Rails.root, "tmp")
- end
-
- def setup
- cd CURRENT_PATH
- rm_rf(destination_root)
- mkdir_p(destination_root)
- end
-
- def test_truth
- # don't complain, test/unit
- end
-
- def capture(stream)
- begin
- stream = stream.to_s
- eval "$#{stream} = StringIO.new"
- yield
- result = eval("$#{stream}").string
- ensure
- eval("$#{stream} = #{stream.upcase}")
- end
+class GeneratorsTestCase < Rails::Generators::TestCase
+ destination File.join(Rails.root, "tmp")
+ setup :prepare_destination
- result
+ def self.inherited(base)
+ base.tests Rails::Generators.const_get(base.name.sub(/Test$/, ''))
+ rescue
+ # Do nothing.
end
- alias :silence :capture
-
- def assert_file(relative, *contents)
- absolute = File.join(destination_root, relative)
- assert File.exists?(absolute), "Expected file #{relative.inspect} to exist, but does not"
-
- read = File.read(absolute) if block_given? || !contents.empty?
- yield read if block_given?
-
- contents.each do |content|
- case content
- when String
- assert_equal content, read
- when Regexp
- assert_match content, read
- end
- end
- end
-
- def assert_no_file(relative)
- absolute = File.join(destination_root, relative)
- assert !File.exists?(absolute), "Expected file #{relative.inspect} to not exist, but does"
- end
-
- def assert_migration(relative, *contents, &block)
- file_name = migration_file_name(relative)
- assert file_name, "Expected migration #{relative} to exist, but was not found"
- assert_file File.join(File.dirname(relative), file_name), *contents, &block
- end
-
- def assert_no_migration(relative)
- file_name = migration_file_name(relative)
- assert_nil file_name, "Expected migration #{relative} to not exist, but found #{file_name}"
- end
-
- def assert_class_method(content, method, &block)
- assert_instance_method content, "self.#{method}", &block
- end
-
- def assert_instance_method(content, method)
- assert content =~ /def #{method}(\(.+\))?(.*?)\n end/m, "Expected to have method #{method}"
- yield $2.strip if block_given?
- end
-
- protected
-
- def migration_file_name(relative)
- absolute = File.join(destination_root, relative)
- dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '')
-
- migration = Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first
- File.basename(migration) if migration
- end
-end
+end \ No newline at end of file
diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb
index f8bfc517a2..cf18782986 100644
--- a/railties/test/generators/helper_generator_test.rb
+++ b/railties/test/generators/helper_generator_test.rb
@@ -1,4 +1,3 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/helper/helper_generator'
@@ -6,6 +5,7 @@ ObjectHelper = Class.new
AnotherObjectHelperTest = Class.new
class HelperGeneratorTest < GeneratorsTestCase
+ arguments %w(admin)
def test_helper_skeleton_is_created
run_generator
@@ -50,11 +50,4 @@ class HelperGeneratorTest < GeneratorsTestCase
end
end
end
-
- protected
-
- def run_generator(args=["admin"])
- silence(:stdout) { Rails::Generators::HelperGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/integration_test_generator_test.rb b/railties/test/generators/integration_test_generator_test.rb
index 6a504ceea2..88e18be5b2 100644
--- a/railties/test/generators/integration_test_generator_test.rb
+++ b/railties/test/generators/integration_test_generator_test.rb
@@ -1,18 +1,11 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/integration_test/integration_test_generator'
class IntegrationTestGeneratorTest < GeneratorsTestCase
+ arguments %w(integration)
def test_integration_test_skeleton_is_created
run_generator
assert_file "test/integration/integration_test.rb", /class IntegrationTest < ActionController::IntegrationTest/
end
-
- protected
-
- def run_generator(args=["integration"])
- silence(:stdout) { Rails::Generators::IntegrationTestGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index 251474ad16..ee4346eb71 100644
--- a/railties/test/generators/mailer_generator_test.rb
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/mailer/mailer_generator'
class MailerGeneratorTest < GeneratorsTestCase
+ arguments %w(notifier foo bar)
def test_mailer_skeleton_is_created
run_generator
@@ -42,11 +42,4 @@ class MailerGeneratorTest < GeneratorsTestCase
assert_file "app/models/notifier.rb", /def foo/
assert_file "app/models/notifier.rb", /def bar/
end
-
- protected
-
- def run_generator(args=["notifier", "foo", "bar"])
- silence(:stdout) { Rails::Generators::MailerGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/metal_generator_test.rb b/railties/test/generators/metal_generator_test.rb
index 80bf342892..5d6a277561 100644
--- a/railties/test/generators/metal_generator_test.rb
+++ b/railties/test/generators/metal_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/metal/metal_generator'
class MetalGeneratorTest < GeneratorsTestCase
+ arguments %w(foo)
def test_metal_skeleton_is_created
run_generator
@@ -13,11 +13,4 @@ class MetalGeneratorTest < GeneratorsTestCase
content = capture(:stderr){ run_generator ["object"] }
assert_match /The name 'Object' is either already used in your application or reserved/, content
end
-
- protected
-
- def run_generator(args=["foo"])
- silence(:stdout) { Rails::Generators::MetalGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 35172a8be4..2fd3e5c056 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -1,32 +1,30 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/migration/migration_generator'
class MigrationGeneratorTest < GeneratorsTestCase
-
def test_migration
- @migration = "change_title_body_from_posts"
- run_generator
- assert_migration "db/migrate/#{@migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration/
+ migration = "change_title_body_from_posts"
+ run_generator [migration]
+ assert_migration "db/migrate/#{migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration/
end
def test_migration_with_class_name
- @migration = "ChangeTitleBodyFromPosts"
- run_generator
- assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{@migration} < ActiveRecord::Migration/
+ migration = "ChangeTitleBodyFromPosts"
+ run_generator [migration]
+ assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{migration} < ActiveRecord::Migration/
end
def test_add_migration_with_attributes
- @migration = "add_title_body_to_posts"
- run_generator [@migration, "title:string", "body:text"]
+ migration = "add_title_body_to_posts"
+ run_generator [migration, "title:string", "body:text"]
- assert_migration "db/migrate/#{@migration}.rb" do |content|
- assert_class_method content, :up do |up|
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_class_method :up, content do |up|
assert_match /add_column :posts, :title, :string/, up
assert_match /add_column :posts, :body, :text/, up
end
- assert_class_method content, :down do |down|
+ assert_class_method :down, content do |down|
assert_match /remove_column :posts, :title/, down
assert_match /remove_column :posts, :body/, down
end
@@ -34,26 +32,19 @@ class MigrationGeneratorTest < GeneratorsTestCase
end
def test_remove_migration_with_attributes
- @migration = "remove_title_body_from_posts"
- run_generator [@migration, "title:string", "body:text"]
+ migration = "remove_title_body_from_posts"
+ run_generator [migration, "title:string", "body:text"]
- assert_migration "db/migrate/#{@migration}.rb" do |content|
- assert_class_method content, :up do |up|
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_class_method :up, content do |up|
assert_match /remove_column :posts, :title/, up
assert_match /remove_column :posts, :body/, up
end
- assert_class_method content, :down do |down|
+ assert_class_method :down, content do |down|
assert_match /add_column :posts, :title, :string/, down
assert_match /add_column :posts, :body, :text/, down
end
end
end
-
- protected
-
- def run_generator(args=[@migration])
- silence(:stdout) { Rails::Generators::MigrationGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index e073b11e1e..051a43706b 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/model/model_generator'
class ModelGeneratorTest < GeneratorsTestCase
+ arguments %w(Account name:string age:integer)
def test_help_shows_invoked_generators_options
content = run_generator ["--help"]
@@ -84,13 +84,13 @@ class ModelGeneratorTest < GeneratorsTestCase
run_generator ["product", "name:string", "supplier_id:integer"]
assert_migration "db/migrate/create_products.rb" do |m|
- assert_class_method m, :up do |up|
+ assert_class_method :up, 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 m, :down do |down|
+ assert_class_method :down, m do |down|
assert_match /drop_table :products/, down
end
end
@@ -126,7 +126,7 @@ class ModelGeneratorTest < GeneratorsTestCase
run_generator ["account", "--no-timestamps"]
assert_migration "db/migrate/create_accounts.rb" do |m|
- assert_class_method m, :up do |up|
+ assert_class_method :up, m do |up|
assert_no_match /t.timestamps/, up
end
end
@@ -171,11 +171,4 @@ class ModelGeneratorTest < GeneratorsTestCase
content = capture(:stderr){ run_generator ["object"] }
assert_match /The name 'Object' is either already used in your application or reserved/, content
end
-
- protected
-
- def run_generator(args=["Account", "name:string", "age:integer"], config={})
- silence(:stdout) { Rails::Generators::ModelGenerator.start args, config.merge(:destination_root => destination_root) }
- end
-
end
diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb
index 98cbf9b8f6..8c1df3b992 100644
--- a/railties/test/generators/named_base_test.rb
+++ b/railties/test/generators/named_base_test.rb
@@ -1,4 +1,3 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
@@ -13,9 +12,10 @@ module ActiveRecord
end
class NamedBaseTest < GeneratorsTestCase
+ tests Rails::Generators::ScaffoldControllerGenerator
def test_named_generator_attributes
- g = Rails::Generators::ScaffoldControllerGenerator.new ["admin/foo"]
+ g = generator ["admin/foo"]
assert_equal 'admin/foo', g.name
assert_equal %w(admin), g.class_path
assert_equal 1, g.class_nesting_depth
@@ -28,12 +28,12 @@ class NamedBaseTest < GeneratorsTestCase
def test_named_generator_attributes_without_pluralized
ActiveRecord::Base.pluralize_table_names = false
- g = Rails::Generators::ScaffoldControllerGenerator.new ["admin/foo"]
+ g = generator ["admin/foo"]
assert_equal "admin_#{g.singular_name}", g.table_name
end
def test_scaffold_plural_names
- g = Rails::Generators::ScaffoldControllerGenerator.new ["ProductLine"]
+ g = generator ["ProductLine"]
assert_equal "ProductLines", g.controller_name
assert_equal "ProductLines", g.controller_class_name
assert_equal "product_lines", g.controller_file_name
diff --git a/railties/test/generators/observer_generator_test.rb b/railties/test/generators/observer_generator_test.rb
index 6fed2998dd..44d9e4a9f3 100644
--- a/railties/test/generators/observer_generator_test.rb
+++ b/railties/test/generators/observer_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/observer/observer_generator'
class ObserverGeneratorTest < GeneratorsTestCase
+ arguments %w(account)
def test_invokes_default_orm
run_generator
@@ -23,11 +23,4 @@ class ObserverGeneratorTest < GeneratorsTestCase
content = run_generator ["account", "--test-framework=rspec"]
assert_match /rspec \[not found\]/, content
end
-
- protected
-
- def run_generator(args=["account"])
- silence(:stdout) { Rails::Generators::ObserverGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/performance_test_generator_test.rb b/railties/test/generators/performance_test_generator_test.rb
index d19128f79a..099575ea1d 100644
--- a/railties/test/generators/performance_test_generator_test.rb
+++ b/railties/test/generators/performance_test_generator_test.rb
@@ -1,18 +1,11 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/performance_test/performance_test_generator'
class PerformanceTestGeneratorTest < GeneratorsTestCase
+ arguments %w(performance)
def test_performance_test_skeleton_is_created
run_generator
assert_file "test/performance/performance_test.rb", /class PerformanceTest < ActionController::PerformanceTest/
end
-
- protected
-
- def run_generator(args=["performance"])
- silence(:stdout) { Rails::Generators::PerformanceTestGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index f5b8b6ffb6..f84b8b6d50 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/plugin/plugin_generator'
class PluginGeneratorTest < GeneratorsTestCase
+ arguments %w(plugin_fu)
def test_plugin_skeleton_is_created
run_generator
@@ -46,11 +46,4 @@ class PluginGeneratorTest < GeneratorsTestCase
run_generator
run_generator ["plugin_fu"], :behavior => :revoke
end
-
- protected
-
- def run_generator(args=["plugin_fu"], config={})
- silence(:stdout) { Rails::Generators::PluginGenerator.start args, config.merge(:destination_root => destination_root) }
- end
-
end
diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb
index 886af01b22..15c0ca0f01 100644
--- a/railties/test/generators/resource_generator_test.rb
+++ b/railties/test/generators/resource_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/resource/resource_generator'
class ResourceGeneratorTest < GeneratorsTestCase
+ arguments %w(account)
def setup
super
@@ -50,8 +50,8 @@ class ResourceGeneratorTest < GeneratorsTestCase
run_generator ["account", "--actions", "index", "new"]
assert_file "app/controllers/accounts_controller.rb" do |controller|
- assert_instance_method controller, :index
- assert_instance_method controller, :new
+ assert_instance_method :index, controller
+ assert_instance_method :new, controller
end
assert_file "app/views/accounts/index.html.erb"
@@ -62,7 +62,7 @@ class ResourceGeneratorTest < GeneratorsTestCase
run_generator
assert_file "config/routes.rb" do |route|
- assert_match /map\.resources :accounts$/, route
+ assert_match /resources :accounts$/, route
end
end
@@ -70,7 +70,7 @@ class ResourceGeneratorTest < GeneratorsTestCase
run_generator ["account", "--singleton"]
assert_file "config/routes.rb" do |route|
- assert_match /map\.resource :account$/, route
+ assert_match /resource :account$/, route
end
end
@@ -93,14 +93,7 @@ class ResourceGeneratorTest < GeneratorsTestCase
run_generator ["account"], :behavior => :revoke
assert_file "config/routes.rb" do |route|
- assert_no_match /map\.resources :accounts$/, route
+ assert_no_match /resources :accounts$/, route
end
end
-
- protected
-
- def run_generator(args=["account"], config={})
- silence(:stdout) { Rails::Generators::ResourceGenerator.start args, config.merge(:destination_root => destination_root) }
- end
-
end
diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb
index 02155c295c..7593c14dd9 100644
--- a/railties/test/generators/scaffold_controller_generator_test.rb
+++ b/railties/test/generators/scaffold_controller_generator_test.rb
@@ -1,4 +1,3 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
@@ -8,6 +7,7 @@ module Unknown
end
class ScaffoldControllerGeneratorTest < GeneratorsTestCase
+ arguments %w(User name:string age:integer)
def test_controller_skeleton_is_created
run_generator
@@ -15,35 +15,35 @@ class ScaffoldControllerGeneratorTest < GeneratorsTestCase
assert_file "app/controllers/users_controller.rb" do |content|
assert_match /class UsersController < ApplicationController/, content
- assert_instance_method content, :index do |m|
+ assert_instance_method :index, content do |m|
assert_match /@users = User\.all/, m
end
- assert_instance_method content, :show do |m|
+ assert_instance_method :show, content do |m|
assert_match /@user = User\.find\(params\[:id\]\)/, m
end
- assert_instance_method content, :new do |m|
+ assert_instance_method :new, content do |m|
assert_match /@user = User\.new/, m
end
- assert_instance_method content, :edit do |m|
+ assert_instance_method :edit, content do |m|
assert_match /@user = User\.find\(params\[:id\]\)/, m
end
- assert_instance_method content, :create do |m|
+ assert_instance_method :create, content do |m|
assert_match /@user = User\.new\(params\[:user\]\)/, m
assert_match /@user\.save/, m
assert_match /@user\.errors/, m
end
- assert_instance_method content, :update do |m|
+ assert_instance_method :update, content do |m|
assert_match /@user = User\.find\(params\[:id\]\)/, m
assert_match /@user\.update_attributes\(params\[:user\]\)/, m
assert_match /@user\.errors/, m
end
- assert_instance_method content, :destroy do |m|
+ assert_instance_method :destroy, content do |m|
assert_match /@user = User\.find\(params\[:id\]\)/, m
assert_match /@user\.destroy/, m
end
@@ -108,7 +108,7 @@ class ScaffoldControllerGeneratorTest < GeneratorsTestCase
assert_file "app/controllers/users_controller.rb" do |content|
assert_match /class UsersController < ApplicationController/, content
- assert_instance_method content, :index do |m|
+ assert_instance_method :index, content do |m|
assert_match /@users = User\.all/, m
end
end
@@ -127,7 +127,7 @@ class ScaffoldControllerGeneratorTest < GeneratorsTestCase
assert_file "app/controllers/users_controller.rb" do |content|
assert_match /class UsersController < ApplicationController/, content
- assert_instance_method content, :index do |m|
+ assert_instance_method :index, content do |m|
assert_match /@users = User\.find\(:all\)/, m
assert_no_match /@users = User\.all/, m
end
@@ -135,11 +135,4 @@ class ScaffoldControllerGeneratorTest < GeneratorsTestCase
ensure
Unknown::Generators.send :remove_const, :ActiveModel
end
-
- protected
-
- def run_generator(args=["User", "name:string", "age:integer"])
- silence(:stdout) { Rails::Generators::ScaffoldControllerGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index c0652c034f..4ddc7b1c89 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -1,8 +1,8 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/scaffold/scaffold_generator'
class ScaffoldGeneratorTest < GeneratorsTestCase
+ arguments %w(product_line title:string price:integer)
def setup
super
@@ -25,42 +25,42 @@ class ScaffoldGeneratorTest < GeneratorsTestCase
# Route
assert_file "config/routes.rb" do |route|
- assert_match /map\.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_instance_method content, :index do |m|
+ assert_instance_method :index, content do |m|
assert_match /@product_lines = ProductLine\.all/, m
end
- assert_instance_method content, :show do |m|
+ assert_instance_method :show, content do |m|
assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m
end
- assert_instance_method content, :new do |m|
+ assert_instance_method :new, content do |m|
assert_match /@product_line = ProductLine\.new/, m
end
- assert_instance_method content, :edit do |m|
+ assert_instance_method :edit, content do |m|
assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m
end
- assert_instance_method content, :create do |m|
+ 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
end
- assert_instance_method content, :update do |m|
+ 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
end
- assert_instance_method content, :destroy do |m|
+ assert_instance_method :destroy, content do |m|
assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m
assert_match /@product_line\.destroy/, m
end
@@ -89,7 +89,7 @@ class ScaffoldGeneratorTest < GeneratorsTestCase
def test_scaffold_on_revoke
run_generator
- run_generator :behavior => :revoke
+ run_generator ["product_line"], :behavior => :revoke
# Model
assert_no_file "app/models/product_line.rb"
@@ -99,7 +99,7 @@ class ScaffoldGeneratorTest < GeneratorsTestCase
# Route
assert_file "config/routes.rb" do |route|
- assert_no_match /map\.resources :product_lines$/, route
+ assert_no_match /resources :product_lines$/, route
end
# Controller
@@ -117,14 +117,4 @@ class ScaffoldGeneratorTest < GeneratorsTestCase
# Stylesheets (should not be removed)
assert_file "public/stylesheets/scaffold.css"
end
-
- protected
-
- def run_generator(config={})
- silence(:stdout) do
- Rails::Generators::ScaffoldGenerator.start ["product_line", "title:string", "price:integer"],
- config.merge(:destination_root => destination_root)
- end
- end
-
end
diff --git a/railties/test/generators/session_migration_generator_test.rb b/railties/test/generators/session_migration_generator_test.rb
index 34fb996b7f..251ffb19ed 100644
--- a/railties/test/generators/session_migration_generator_test.rb
+++ b/railties/test/generators/session_migration_generator_test.rb
@@ -1,9 +1,7 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/session_migration/session_migration_generator'
class SessionMigrationGeneratorTest < GeneratorsTestCase
-
def test_session_migration_with_default_name
run_generator
assert_migration "db/migrate/add_sessions_table.rb", /class AddSessionsTable < ActiveRecord::Migration/
@@ -24,11 +22,4 @@ class SessionMigrationGeneratorTest < GeneratorsTestCase
ensure
ActiveRecord::SessionStore::Session.table_name = "sessions"
end
-
- protected
-
- def run_generator(args=[])
- silence(:stdout) { Rails::Generators::SessionMigrationGenerator.start args, :destination_root => destination_root }
- end
-
end
diff --git a/railties/test/generators/stylesheets_generator_test.rb b/railties/test/generators/stylesheets_generator_test.rb
index 15263d4bb8..d9079327ba 100644
--- a/railties/test/generators/stylesheets_generator_test.rb
+++ b/railties/test/generators/stylesheets_generator_test.rb
@@ -1,9 +1,7 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/stylesheets/stylesheets_generator'
class StylesheetsGeneratorTest < GeneratorsTestCase
-
def test_copy_stylesheets
run_generator
assert_file "public/stylesheets/scaffold.css"
@@ -11,14 +9,7 @@ class StylesheetsGeneratorTest < GeneratorsTestCase
def test_stylesheets_are_not_deleted_on_revoke
run_generator
- run_generator :behavior => :revoke
+ run_generator [], :behavior => :revoke
assert_file "public/stylesheets/scaffold.css"
end
-
- protected
-
- def run_generator(config={})
- silence(:stdout) { Rails::Generators::StylesheetsGenerator.start [], config.merge(:destination_root => destination_root) }
- end
-
end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index a8716d9992..2df218debc 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -9,6 +9,11 @@ class GeneratorsTest < GeneratorsTestCase
Gem.stubs(:respond_to?).with(:loaded_specs).returns(false)
end
+ def test_invoke_add_generators_to_raw_lookups
+ TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {})
+ Rails::Generators.invoke("test_unit:model", ["Account"])
+ end
+
def test_invoke_when_generator_is_not_found
output = capture(:stdout){ Rails::Generators.invoke :unknown }
assert_equal "Could not find generator unknown.\n", output
@@ -51,12 +56,6 @@ class GeneratorsTest < GeneratorsTestCase
assert_equal "foobar:foobar", klass.namespace
end
- def test_find_by_namespace_add_generators_to_raw_lookups
- klass = Rails::Generators.find_by_namespace("test_unit:model")
- assert klass
- assert_equal "test_unit:generators:model", klass.namespace
- end
-
def test_find_by_namespace_lookup_to_the_rails_root_folder
klass = Rails::Generators.find_by_namespace(:fixjour)
assert klass
@@ -96,7 +95,7 @@ class GeneratorsTest < GeneratorsTestCase
end
def test_builtin_generators
- assert Rails::Generators.builtin.include? %w(rails model)
+ assert Rails::Generators.builtin.include?("rails:model")
end
def test_rails_generators_help_with_builtin_information
@@ -107,7 +106,7 @@ class GeneratorsTest < GeneratorsTestCase
def test_rails_generators_with_others_information
output = capture(:stdout){ Rails::Generators.help }.split("\n").last
- assert_equal "Others: active_record:fixjour, fixjour, foobar, mspec, rails:javascripts.", output
+ assert_equal "Others: active_record:fixjour, fixjour, foobar:foobar, mspec, rails:javascripts, xspec.", output
end
def test_warning_is_shown_if_generator_cant_be_loaded
@@ -150,6 +149,13 @@ class GeneratorsTest < GeneratorsTestCase
assert_equal "test_unit:generators:plugin", klass.namespace
end
+ def test_fallbacks_for_generators_on_find_by_namespace_with_context
+ Rails::Generators.fallbacks[:remarkable] = :test_unit
+ klass = Rails::Generators.find_by_namespace(:remarkable, :rails, :plugin)
+ assert klass
+ assert_equal "test_unit:generators:plugin", klass.namespace
+ end
+
def test_fallbacks_for_generators_on_invoke
Rails::Generators.fallbacks[:shoulda] = :test_unit
TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {})
@@ -171,6 +177,8 @@ class GeneratorsTest < GeneratorsTestCase
end
assert_equal false, klass.class_options[:generate].default
+ ensure
+ Rails::Generators.subclasses.delete(klass)
end
def test_source_paths_for_not_namespaced_generators
diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb
index a9e60680ac..e308cbcb0e 100644
--- a/railties/test/initializable_test.rb
+++ b/railties/test/initializable_test.rb
@@ -150,6 +150,16 @@ module InitializableTests
Word.run_initializers
assert_equal "bird", $word
end
+
+ test "creating initializer without a block raises an error" do
+ assert_raise(ArgumentError) do
+ Class.new do
+ include Rails::Initializable
+
+ initializer :foo
+ end
+ end
+ end
end
class BeforeAfter < ActiveSupport::TestCase
diff --git a/railties/test/initializer/check_ruby_version_test.rb b/railties/test/initializer/check_ruby_version_test.rb
index 97d884e1be..311f19a28a 100644
--- a/railties/test/initializer/check_ruby_version_test.rb
+++ b/railties/test/initializer/check_ruby_version_test.rb
@@ -1,66 +1,32 @@
require "isolation/abstract_unit"
module InitializerTests
- class PathsTest < Test::Unit::TestCase
+ class CheckRubyVersionTest < Test::Unit::TestCase
include ActiveSupport::Testing::Isolation
def setup
build_app
boot_rails
- require "rails"
end
- test "rails does not initialize with ruby version 1.8.1" do
- assert_rails_does_not_boot "1.8.1"
- end
-
- test "rails does not initialize with ruby version 1.8.2" do
- assert_rails_does_not_boot "1.8.2"
- end
-
- test "rails does not initialize with ruby version 1.8.3" do
- assert_rails_does_not_boot "1.8.3"
- end
-
- test "rails does not initialize with ruby version 1.8.4" do
- assert_rails_does_not_boot "1.8.4"
- end
-
- test "rails does not initializes with ruby version 1.8.5" do
- assert_rails_does_not_boot "1.8.5"
- end
-
- test "rails does not initialize with ruby version 1.8.6" do
- assert_rails_does_not_boot "1.8.6"
- end
-
- test "rails initializes with ruby version 1.8.7" do
- assert_rails_boots "1.8.7"
- end
-
- test "rails initializes with the current version of Ruby" do
- assert_rails_boots
- end
-
- def set_ruby_version(version)
- $-w = nil
- Object.const_set(:RUBY_VERSION, version.freeze)
+ test "rails initializes with ruby 1.8.7 or later" do
+ if RUBY_VERSION < '1.8.7'
+ assert_rails_does_not_boot
+ else
+ assert_rails_boots
+ end
end
- def assert_rails_boots(version = nil)
- set_ruby_version(version) if version
+ def assert_rails_boots
assert_nothing_raised "It appears that rails does not boot" do
- Rails::Initializer.run { |c| c.frameworks = [] }
- Rails.initialize!
+ require "rails/all"
end
end
- def assert_rails_does_not_boot(version)
- set_ruby_version(version)
+ def assert_rails_does_not_boot
$stderr = File.open("/dev/null", "w")
assert_raises(SystemExit) do
- Rails::Initializer.run { |c| c.frameworks = [] }
- Rails.initialize!
+ require "rails/all"
end
end
end
diff --git a/railties/test/initializer/initialize_i18n_test.rb b/railties/test/initializer/initialize_i18n_test.rb
index 076816d73b..472566378d 100644
--- a/railties/test/initializer/initialize_i18n_test.rb
+++ b/railties/test/initializer/initialize_i18n_test.rb
@@ -7,16 +7,15 @@ module InitializerTests
def setup
build_app
boot_rails
- require "rails"
end
# test_config_defaults_and_settings_should_be_added_to_i18n_defaults
test "i18n config defaults and settings should be added to i18n defaults" do
- Rails::Initializer.run do |c|
- c.root = app_path
- c.i18n.load_path << "my/other/locale.yml"
- end
- Rails.initialize!
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.i18n.load_path << "my/other/locale.yml"
+ RUBY
+ require "#{app_path}/config/environment"
#{RAILS_FRAMEWORK_ROOT}/railties/test/fixtures/plugins/engines/engine/config/locales/en.yml
assert_equal %W(
diff --git a/railties/test/initializer/path_test.rb b/railties/test/initializer/path_test.rb
index 1b58a58555..bfb1887d11 100644
--- a/railties/test/initializer/path_test.rb
+++ b/railties/test/initializer/path_test.rb
@@ -1,101 +1,103 @@
require "isolation/abstract_unit"
-class PathsTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
-
- def setup
- build_app
- boot_rails
- require "rails"
- Rails::Initializer.run do |config|
- config.root = app_path
- config.frameworks = [:action_controller, :action_view, :action_mailer, :active_record]
- config.after_initialize do
- ActionController::Base.session_store = nil
- end
+module InitializerTests
+ class PathTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.after_initialize do
+ ActionController::Base.session_store = nil
+ end
+ RUBY
+ use_frameworks [:action_controller, :action_view, :action_mailer, :active_record]
+ require "#{app_path}/config/environment"
+ @paths = Rails.application.config.paths
end
- Rails.initialize!
- @paths = Rails.application.config.paths
- end
- def root(*path)
- app_path(*path).to_s
- end
+ def root(*path)
+ app_path(*path).to_s
+ end
- def assert_path(paths, *dir)
- assert_equal [root(*dir)], paths.paths
- end
+ def assert_path(paths, *dir)
+ assert_equal [root(*dir)], paths.paths
+ end
- def assert_in_load_path(*path)
- assert $:.any? { |p| File.expand_path(p) == root(*path) }, "Load path does not include '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----"
- end
+ def assert_in_load_path(*path)
+ assert $:.any? { |p| File.expand_path(p) == root(*path) }, "Load path does not include '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----"
+ end
- def assert_not_in_load_path(*path)
- assert !$:.any? { |p| File.expand_path(p) == root(*path) }, "Load path includes '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----"
- end
+ def assert_not_in_load_path(*path)
+ assert !$:.any? { |p| File.expand_path(p) == root(*path) }, "Load path includes '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----"
+ end
- test "booting up Rails yields a valid paths object" do
- assert_path @paths.app, "app"
- assert_path @paths.app.metals, "app", "metal"
- assert_path @paths.app.models, "app", "models"
- assert_path @paths.app.helpers, "app", "helpers"
- assert_path @paths.app.services, "app", "services"
- 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"
- assert_path @paths.config.environments, "config", "environments"
-
- assert_equal root("app", "controllers"), @paths.app.controllers.to_a.first
- assert_equal Pathname.new(File.dirname(__FILE__)).join("..", "..", "builtin", "rails_info").expand_path,
- Pathname.new(@paths.app.controllers.to_a[1]).expand_path
- end
+ test "booting up Rails yields a valid paths object" do
+ assert_path @paths.app, "app"
+ assert_path @paths.app.metals, "app", "metal"
+ assert_path @paths.app.models, "app", "models"
+ assert_path @paths.app.helpers, "app", "helpers"
+ assert_path @paths.app.services, "app", "services"
+ 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"
+ assert_path @paths.config.environments, "config", "environments"
+
+ assert_equal root("app", "controllers"), @paths.app.controllers.to_a.first
+ assert_equal Pathname.new(File.dirname(__FILE__)).join("..", "..", "builtin", "rails_info").expand_path,
+ Pathname.new(@paths.app.controllers.to_a[1]).expand_path
+ end
- test "booting up Rails yields a list of paths that are eager" do
- assert @paths.app.models.eager_load?
- assert @paths.app.controllers.eager_load?
- assert @paths.app.helpers.eager_load?
- assert @paths.app.metals.eager_load?
- end
+ test "booting up Rails yields a list of paths that are eager" do
+ assert @paths.app.models.eager_load?
+ assert @paths.app.controllers.eager_load?
+ assert @paths.app.helpers.eager_load?
+ assert @paths.app.metals.eager_load?
+ end
- test "environments has a glob equal to the current environment" do
- assert_equal "#{RAILS_ENV}.rb", @paths.config.environments.glob
- end
+ test "environments has a glob equal to the current environment" do
+ assert_equal "#{RAILS_ENV}.rb", @paths.config.environments.glob
+ end
- test "load path includes each of the paths in config.paths as long as the directories exist" do
- assert_in_load_path "app"
- assert_in_load_path "app", "controllers"
- assert_in_load_path "app", "models"
- assert_in_load_path "app", "helpers"
- assert_in_load_path "lib"
- assert_in_load_path "vendor"
-
- assert_not_in_load_path "app", "views"
- assert_not_in_load_path "app", "metal"
- assert_not_in_load_path "app", "services"
- assert_not_in_load_path "config"
- assert_not_in_load_path "config", "locales"
- assert_not_in_load_path "config", "environments"
- assert_not_in_load_path "tmp"
- assert_not_in_load_path "tmp", "cache"
- end
+ test "load path includes each of the paths in config.paths as long as the directories exist" do
+ assert_in_load_path "app"
+ assert_in_load_path "app", "controllers"
+ assert_in_load_path "app", "models"
+ assert_in_load_path "app", "helpers"
+ assert_in_load_path "lib"
+ assert_in_load_path "vendor"
+
+ assert_not_in_load_path "app", "views"
+ assert_not_in_load_path "app", "metal"
+ assert_not_in_load_path "app", "services"
+ assert_not_in_load_path "config"
+ assert_not_in_load_path "config", "locales"
+ assert_not_in_load_path "config", "environments"
+ assert_not_in_load_path "tmp"
+ assert_not_in_load_path "tmp", "cache"
+ end
- test "controller paths include builtin in development mode" do
- RAILS_ENV.replace "development"
- assert Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ }
- end
+ test "controller paths include builtin in development mode" do
+ RAILS_ENV.replace "development"
+ assert Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ }
+ end
- test "controller paths does not have builtin_directories in test mode" do
- RAILS_ENV.replace "test"
- assert !Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ }
- end
+ test "controller paths does not have builtin_directories in test mode" do
+ RAILS_ENV.replace "test"
+ assert !Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ }
+ end
- test "controller paths does not have builtin_directories in production mode" do
- RAILS_ENV.replace "production"
- assert !Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ }
- end
+ test "controller paths does not have builtin_directories in production mode" do
+ RAILS_ENV.replace "production"
+ assert !Rails::Configuration.new.paths.app.controllers.paths.any? { |p| p =~ /builtin/ }
+ end
-end \ No newline at end of file
+ end
+end
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index ba8b35d5cc..dc5fddb19d 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -89,6 +89,13 @@ module TestHelpers
end
end
+ routes = File.read("#{app_path}/config/routes.rb")
+ if routes =~ /(\n\s*end\s*)\Z/
+ File.open("#{app_path}/config/routes.rb", 'w') do |f|
+ f.puts $` + "\nmatch ':controller(/:action(/:id))(.:format)'\n" + $1
+ end
+ end
+
add_to_config 'config.action_controller.session = { :key => "_myapp_session", :secret => "bac838a849c1d5c4de2e6a50af826079" }'
end
@@ -128,7 +135,7 @@ module TestHelpers
def add_to_config(str)
environment = File.read("#{app_path}/config/application.rb")
- if environment =~ /(\n\s*end\s*)\Z/
+ if environment =~ /(\n\s*end\s*end\s*)\Z/
File.open("#{app_path}/config/application.rb", 'w') do |f|
f.puts $` + "\n#{str}\n" + $1
end
@@ -146,6 +153,14 @@ module TestHelpers
app_file("app/controllers/#{name}_controller.rb", contents)
end
+ def use_frameworks(arr)
+ to_remove = [:actionmailer,
+ :activemodel,
+ :activerecord,
+ :activeresource] - arr
+ $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
+ end
+
def boot_rails
root = File.expand_path('../../../..', __FILE__)
begin
@@ -192,6 +207,6 @@ Module.new do
`#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{tmp_path('app_template')}`
File.open("#{tmp_path}/app_template/config/boot.rb", 'w') do |f|
f.puts "require '#{environment}'" if require_environment
- f.puts "require 'rails'"
+ f.puts "require 'rails/all'"
end
end
diff --git a/railties/test/metal_test.rb b/railties/test/metal_test.rb
index 2256b191e2..91f55c2b5e 100644
--- a/railties/test/metal_test.rb
+++ b/railties/test/metal_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'rails/initializer'
class MetalTest < Test::Unit::TestCase
def test_metals_should_return_list_of_found_metal_apps
diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb
index c724799d64..d60d6177f6 100644
--- a/railties/test/paths_test.rb
+++ b/railties/test/paths_test.rb
@@ -2,7 +2,6 @@ require 'abstract_unit'
require 'rails/paths'
class PathsTest < ActiveSupport::TestCase
-
def setup
@root = Rails::Application::Root.new("/foo/bar")
end
@@ -228,4 +227,4 @@ class PathsTest < ActiveSupport::TestCase
@root.app.eager_load!
assert_equal ["/foo/bar/app"], @root.load_paths
end
-end \ No newline at end of file
+end
diff --git a/railties/test/plugins/configuration_test.rb b/railties/test/plugins/configuration_test.rb
new file mode 100644
index 0000000000..25bf24eb3b
--- /dev/null
+++ b/railties/test/plugins/configuration_test.rb
@@ -0,0 +1,36 @@
+require "isolation/abstract_unit"
+
+module PluginsTest
+ class ConfigurationTest < Test::Unit::TestCase
+ def setup
+ build_app
+ boot_rails
+ require "rails/all"
+ end
+
+ test "config is available to plugins" do
+ class Foo < Rails::Railtie ; end
+ assert_nil Foo.config.action_controller.foo
+ end
+
+ test "a config name is available for the plugin" do
+ class Foo < Rails::Railtie ; config.foo.greetings = "hello" ; end
+ assert_equal "hello", Foo.config.foo.greetings
+ end
+
+ test "plugin configurations are available in the application" do
+ class Foo < Rails::Railtie ; config.foo.greetings = "hello" ; end
+ require "#{app_path}/config/application"
+ assert_equal "hello", AppTemplate::Application.config.foo.greetings
+ end
+
+ test "plugin config merges are deep" do
+ class Foo < Rails::Railtie ; config.foo.greetings = 'hello' ; end
+ class MyApp < Rails::Application
+ config.foo.bar = "bar"
+ end
+ assert_equal "hello", MyApp.config.foo.greetings
+ assert_equal "bar", MyApp.config.foo.bar
+ end
+ end
+end
diff --git a/railties/test/plugins/framework_extension_test.rb b/railties/test/plugins/framework_extension_test.rb
new file mode 100644
index 0000000000..c920db77aa
--- /dev/null
+++ b/railties/test/plugins/framework_extension_test.rb
@@ -0,0 +1,52 @@
+require "isolation/abstract_unit"
+
+module PluginsTest
+ class FrameworkExtensionTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ require "rails/all"
+ end
+
+ test "rake_tasks block is executed when MyApp.load_tasks is called" do
+ $ran_block = false
+
+ class MyTie < Rails::Railtie
+ rake_tasks do
+ $ran_block = true
+ end
+ end
+
+ require "#{app_path}/config/environment"
+
+ assert !$ran_block
+ require 'rake'
+ require 'rake/testtask'
+ require 'rake/rdoctask'
+
+ AppTemplate::Application.load_tasks
+ assert $ran_block
+ end
+ end
+
+ class ActiveRecordExtensionTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ test "active_record extensions are applied to ActiveRecord" do
+ add_to_config "config.active_record.table_name_prefix = 'tbl_'"
+
+ require "#{app_path}/config/environment"
+
+ assert_equal 'tbl_', ActiveRecord::Base.table_name_prefix
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb
index a0484c0868..435bd34925 100644
--- a/railties/test/rails_info_controller_test.rb
+++ b/railties/test/rails_info_controller_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'action_controller'
+require 'action_controller/test_case'
require 'rails/info'
require 'rails/info_controller'
@@ -14,17 +15,12 @@ class InfoControllerTest < ActionController::TestCase
tests Rails::InfoController
def setup
- ActionController::Routing.use_controllers!(['rails/info'])
ActionController::Routing::Routes.draw do |map|
- map.connect ':controller/:action/:id'
+ match ':controller/:action'
end
@controller.stubs(:consider_all_requests_local => false, :local_request? => true)
end
- def teardown
- ActionController::Routing.use_controllers! nil
- end
-
test "info controller does not allow remote requests" do
@controller.stubs(:consider_all_requests_local => false, :local_request? => false)
get :properties