aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionmailer/CHANGELOG12
-rw-r--r--actionmailer/Rakefile2
-rw-r--r--actionmailer/lib/action_mailer.rb35
-rw-r--r--actionmailer/lib/action_mailer/base.rb61
-rw-r--r--actionmailer/lib/action_mailer/helpers.rb2
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb2
-rw-r--r--actionmailer/lib/action_mailer/part.rb10
-rw-r--r--actionmailer/lib/action_mailer/part_container.rb6
-rw-r--r--actionmailer/lib/action_mailer/quoting.rb2
-rw-r--r--actionmailer/lib/action_mailer/test_case.rb2
-rw-r--r--actionmailer/lib/action_mailer/test_helper.rb1
-rw-r--r--actionmailer/lib/action_mailer/utils.rb1
-rw-r--r--actionmailer/lib/action_mailer/vendor.rb14
-rw-r--r--actionmailer/lib/action_mailer/vendor/text_format.rb10
-rw-r--r--actionmailer/lib/action_mailer/vendor/tmail.rb17
-rw-r--r--actionmailer/lib/action_mailer/version.rb2
-rw-r--r--actionmailer/test/abstract_unit.rb8
-rw-r--r--actionmailer/test/asset_host_test.rb54
-rw-r--r--actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb1
-rw-r--r--actionmailer/test/fixtures/auto_layout_mailer/multipart.text.html.erb1
-rw-r--r--actionmailer/test/fixtures/auto_layout_mailer/multipart.text.plain.erb1
-rw-r--r--actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb1
-rw-r--r--actionmailer/test/mail_layout_test.rb17
-rw-r--r--actionmailer/test/mail_service_test.rb28
-rw-r--r--actionmailer/test/quoting_test.rb1
-rw-r--r--actionmailer/test/test_helper_test.rb8
-rw-r--r--actionpack/CHANGELOG63
-rw-r--r--actionpack/Rakefile3
-rw-r--r--actionpack/lib/action_controller.rb112
-rw-r--r--actionpack/lib/action_controller/assertions.rb69
-rw-r--r--actionpack/lib/action_controller/assertions/model_assertions.rb1
-rw-r--r--actionpack/lib/action_controller/assertions/response_assertions.rb3
-rw-r--r--actionpack/lib/action_controller/assertions/selector_assertions.rb3
-rw-r--r--actionpack/lib/action_controller/assertions/tag_assertions.rb5
-rw-r--r--actionpack/lib/action_controller/base.rb44
-rw-r--r--actionpack/lib/action_controller/caching.rb18
-rw-r--r--actionpack/lib/action_controller/caching/fragments.rb22
-rw-r--r--actionpack/lib/action_controller/cgi_ext/cookie.rb2
-rw-r--r--actionpack/lib/action_controller/cgi_process.rb1
-rw-r--r--actionpack/lib/action_controller/components.rb169
-rw-r--r--actionpack/lib/action_controller/dispatcher.rb23
-rw-r--r--actionpack/lib/action_controller/flash.rb2
-rw-r--r--actionpack/lib/action_controller/helpers.rb16
-rw-r--r--actionpack/lib/action_controller/integration.rb7
-rw-r--r--actionpack/lib/action_controller/layout.rb38
-rw-r--r--actionpack/lib/action_controller/middleware_stack.rb42
-rw-r--r--actionpack/lib/action_controller/mime_type.rb22
-rw-r--r--actionpack/lib/action_controller/performance_test.rb1
-rw-r--r--actionpack/lib/action_controller/polymorphic_routes.rb44
-rw-r--r--actionpack/lib/action_controller/rack_process.rb1
-rwxr-xr-xactionpack/lib/action_controller/request.rb14
-rw-r--r--actionpack/lib/action_controller/request_forgery_protection.rb48
-rw-r--r--actionpack/lib/action_controller/request_profiler.rb1
-rw-r--r--actionpack/lib/action_controller/rescue.rb14
-rw-r--r--actionpack/lib/action_controller/resources.rb120
-rw-r--r--actionpack/lib/action_controller/routing.rb1
-rw-r--r--actionpack/lib/action_controller/routing/builder.rb55
-rw-r--r--actionpack/lib/action_controller/routing/optimisations.rb10
-rw-r--r--actionpack/lib/action_controller/routing/recognition_optimisation.rb2
-rw-r--r--actionpack/lib/action_controller/routing/route.rb22
-rw-r--r--actionpack/lib/action_controller/routing/route_set.rb75
-rw-r--r--actionpack/lib/action_controller/routing/routing_ext.rb4
-rw-r--r--actionpack/lib/action_controller/routing/segments.rb59
-rw-r--r--actionpack/lib/action_controller/session/cookie_store.rb32
-rw-r--r--actionpack/lib/action_controller/session_management.rb7
-rw-r--r--actionpack/lib/action_controller/test_case.rb93
-rw-r--r--actionpack/lib/action_controller/test_process.rb27
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner.rb16
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb2
-rw-r--r--actionpack/lib/action_pack/version.rb2
-rw-r--r--actionpack/lib/action_view.rb38
-rw-r--r--actionpack/lib/action_view/base.rb32
-rw-r--r--actionpack/lib/action_view/erb/util.rb38
-rw-r--r--actionpack/lib/action_view/helpers.rb29
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb80
-rw-r--r--actionpack/lib/action_view/helpers/atom_feed_helper.rb13
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb6
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb14
-rw-r--r--actionpack/lib/action_view/helpers/javascript_helper.rb3
-rw-r--r--actionpack/lib/action_view/helpers/javascripts/controls.js963
-rw-r--r--actionpack/lib/action_view/helpers/javascripts/dragdrop.js972
-rw-r--r--actionpack/lib/action_view/helpers/javascripts/effects.js1120
-rw-r--r--actionpack/lib/action_view/helpers/javascripts/prototype.js4221
-rw-r--r--actionpack/lib/action_view/helpers/number_helper.rb7
-rw-r--r--actionpack/lib/action_view/helpers/prototype_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/sanitize_helper.rb10
-rw-r--r--actionpack/lib/action_view/helpers/scriptaculous_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/tag_helper.rb13
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb220
-rw-r--r--actionpack/lib/action_view/locale/en.yml (renamed from actionpack/lib/action_view/locale/en-US.yml)3
-rw-r--r--actionpack/lib/action_view/partials.rb32
-rw-r--r--actionpack/lib/action_view/paths.rb67
-rw-r--r--actionpack/lib/action_view/renderable.rb6
-rw-r--r--actionpack/lib/action_view/template.rb34
-rw-r--r--actionpack/lib/action_view/template_error.rb17
-rw-r--r--actionpack/lib/action_view/template_handler.rb26
-rw-r--r--actionpack/lib/action_view/template_handlers.rb9
-rw-r--r--actionpack/lib/action_view/template_handlers/erb.rb39
-rw-r--r--actionpack/lib/action_view/test_case.rb4
-rw-r--r--actionpack/test/abstract_unit.rb26
-rw-r--r--actionpack/test/active_record_unit.rb6
-rw-r--r--actionpack/test/activerecord/active_record_store_test.rb1
-rw-r--r--actionpack/test/activerecord/render_partial_with_record_identification_test.rb22
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb36
-rw-r--r--actionpack/test/controller/assert_select_test.rb136
-rw-r--r--actionpack/test/controller/base_test.rb2
-rw-r--r--actionpack/test/controller/caching_test.rb22
-rw-r--r--actionpack/test/controller/cgi_test.rb4
-rw-r--r--actionpack/test/controller/components_test.rb156
-rw-r--r--actionpack/test/controller/deprecation/deprecated_base_methods_test.rb20
-rw-r--r--actionpack/test/controller/dispatcher_test.rb2
-rw-r--r--actionpack/test/controller/helper_test.rb16
-rw-r--r--actionpack/test/controller/html-scanner/sanitizer_test.rb6
-rw-r--r--actionpack/test/controller/integration_test.rb2
-rw-r--r--actionpack/test/controller/integration_upload_test.rb2
-rw-r--r--actionpack/test/controller/layout_test.rb47
-rw-r--r--actionpack/test/controller/logging_test.rb46
-rw-r--r--actionpack/test/controller/mime_responds_test.rb16
-rw-r--r--actionpack/test/controller/mime_type_test.rb12
-rw-r--r--actionpack/test/controller/polymorphic_routes_test.rb38
-rw-r--r--actionpack/test/controller/rack_test.rb1
-rw-r--r--actionpack/test/controller/redirect_test.rb16
-rw-r--r--actionpack/test/controller/render_test.rb77
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb181
-rw-r--r--actionpack/test/controller/request_test.rb50
-rw-r--r--actionpack/test/controller/rescue_test.rb18
-rw-r--r--actionpack/test/controller/resources_test.rb296
-rw-r--r--actionpack/test/controller/routing_test.rb42
-rw-r--r--actionpack/test/controller/session/cookie_store_test.rb17
-rw-r--r--actionpack/test/controller/session/mem_cache_store_test.rb3
-rw-r--r--actionpack/test/controller/test_test.rb26
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb41
-rw-r--r--actionpack/test/controller/verification_test.rb2
-rw-r--r--actionpack/test/controller/view_paths_test.rb2
-rw-r--r--actionpack/test/controller/webservice_test.rb9
-rw-r--r--actionpack/test/fixtures/alternate_helpers/foo_helper.rb3
-rw-r--r--actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb1
-rw-r--r--actionpack/test/fixtures/test/dont_pick_me1
-rw-r--r--actionpack/test/fixtures/test/hello.builder2
-rw-r--r--actionpack/test/template/active_record_helper_i18n_test.rb24
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb52
-rw-r--r--actionpack/test/template/atom_feed_helper_test.rb11
-rw-r--r--actionpack/test/template/compiled_templates_test.rb59
-rw-r--r--actionpack/test/template/date_helper_i18n_test.rb22
-rw-r--r--actionpack/test/template/date_helper_test.rb40
-rw-r--r--actionpack/test/template/form_options_helper_test.rb3
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb38
-rw-r--r--actionpack/test/template/number_helper_i18n_test.rb33
-rw-r--r--actionpack/test/template/render_test.rb64
-rw-r--r--actionpack/test/template/tag_helper_test.rb4
-rw-r--r--actionpack/test/template/text_helper_test.rb149
-rw-r--r--actionpack/test/template/translation_helper_test.rb6
-rw-r--r--activemodel/lib/active_model/state_machine.rb14
-rw-r--r--activemodel/lib/active_model/state_machine/event.rb2
-rw-r--r--activemodel/lib/active_model/state_machine/machine.rb8
-rw-r--r--activemodel/lib/active_model/state_machine/state.rb7
-rw-r--r--activemodel/test/observing_test.rb38
-rw-r--r--activemodel/test/state_machine/event_test.rb18
-rw-r--r--activemodel/test/state_machine/machine_test.rb4
-rw-r--r--activemodel/test/state_machine/state_test.rb46
-rw-r--r--activemodel/test/state_machine/state_transition_test.rb106
-rw-r--r--activemodel/test/state_machine_test.rb174
-rw-r--r--activemodel/test/test_helper.rb36
-rw-r--r--activerecord/CHANGELOG20
-rw-r--r--activerecord/Rakefile2
-rw-r--r--activerecord/lib/active_record.rb82
-rw-r--r--activerecord/lib/active_record/association_preload.rb4
-rwxr-xr-xactiverecord/lib/active_record/associations.rb37
-rw-r--r--activerecord/lib/active_record/associations/association_proxy.rb1
-rw-r--r--activerecord/lib/active_record/associations/has_one_through_association.rb7
-rwxr-xr-xactiverecord/lib/active_record/base.rb54
-rw-r--r--activerecord/lib/active_record/calculations.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb22
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb8
-rwxr-xr-xactiverecord/lib/active_record/connection_adapters/abstract_adapter.rb6
-rw-r--r--activerecord/lib/active_record/fixtures.rb289
-rw-r--r--activerecord/lib/active_record/locale/en.yml (renamed from activerecord/lib/active_record/locale/en-US.yml)2
-rw-r--r--activerecord/lib/active_record/serialization.rb4
-rw-r--r--activerecord/lib/active_record/test_case.rb16
-rw-r--r--activerecord/lib/active_record/version.rb2
-rw-r--r--activerecord/test/cases/adapter_test_sqlserver.rb95
-rw-r--r--activerecord/test/cases/ar_schema_test.rb1
-rw-r--r--activerecord/test/cases/associations/eager_test.rb22
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb28
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb5
-rw-r--r--activerecord/test/cases/associations/has_one_through_associations_test.rb40
-rwxr-xr-xactiverecord/test/cases/base_test.rb13
-rw-r--r--activerecord/test/cases/binary_test.rb6
-rw-r--r--activerecord/test/cases/calculations_test.rb5
-rw-r--r--activerecord/test/cases/defaults_test.rb7
-rw-r--r--activerecord/test/cases/finder_test.rb7
-rw-r--r--activerecord/test/cases/fixtures_test.rb8
-rw-r--r--activerecord/test/cases/helper.rb29
-rw-r--r--activerecord/test/cases/i18n_test.rb12
-rw-r--r--activerecord/test/cases/inheritance_test.rb4
-rw-r--r--activerecord/test/cases/locking_test.rb4
-rw-r--r--activerecord/test/cases/method_scoping_test.rb67
-rw-r--r--activerecord/test/cases/migration_test.rb10
-rw-r--r--activerecord/test/cases/pooled_connections_test.rb24
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb1
-rw-r--r--activerecord/test/cases/table_name_test_sqlserver.rb23
-rw-r--r--activerecord/test/cases/validations_i18n_test.rb98
-rw-r--r--activerecord/test/fixtures/organizations.yml5
-rw-r--r--activerecord/test/models/author.rb1
-rw-r--r--activerecord/test/models/category.rb1
-rw-r--r--activerecord/test/models/developer.rb12
-rw-r--r--activerecord/test/models/member.rb2
-rw-r--r--activerecord/test/models/member_detail.rb4
-rw-r--r--activerecord/test/models/organization.rb4
-rw-r--r--activerecord/test/models/project.rb1
-rw-r--r--activerecord/test/schema/schema.rb10
-rw-r--r--activerecord/test/schema/sqlserver_specific_schema.rb5
-rw-r--r--activeresource/CHANGELOG2
-rw-r--r--activeresource/Rakefile2
-rw-r--r--activeresource/lib/active_resource/base.rb1
-rw-r--r--activeresource/lib/active_resource/version.rb2
-rw-r--r--activeresource/test/base_test.rb86
-rw-r--r--activeresource/test/format_test.rb28
-rw-r--r--activesupport/CHANGELOG25
-rw-r--r--activesupport/Rakefile3
-rw-r--r--activesupport/lib/active_support.rb64
-rw-r--r--activesupport/lib/active_support/backtrace_cleaner.rb72
-rw-r--r--activesupport/lib/active_support/cache.rb13
-rw-r--r--activesupport/lib/active_support/cache/drb_store.rb5
-rw-r--r--activesupport/lib/active_support/core_ext.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/array/access.rb26
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb9
-rw-r--r--activesupport/lib/active_support/core_ext/exception.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/file/atomic.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/hash/conversions.rb61
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/conversions.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/object/misc.rb18
-rw-r--r--activesupport/lib/active_support/core_ext/rexml.rb51
-rw-r--r--activesupport/lib/active_support/core_ext/string/iterators.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb2
-rw-r--r--activesupport/lib/active_support/dependencies.rb27
-rw-r--r--activesupport/lib/active_support/deprecation.rb52
-rw-r--r--activesupport/lib/active_support/duration.rb2
-rw-r--r--activesupport/lib/active_support/inflector.rb12
-rw-r--r--activesupport/lib/active_support/json/encoding.rb52
-rw-r--r--activesupport/lib/active_support/locale/en.yml (renamed from activesupport/lib/active_support/locale/en-US.yml)2
-rw-r--r--activesupport/lib/active_support/memoizable.rb44
-rw-r--r--activesupport/lib/active_support/message_encryptor.rb70
-rw-r--r--activesupport/lib/active_support/message_verifier.rb46
-rw-r--r--activesupport/lib/active_support/option_merger.rb8
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb8
-rw-r--r--activesupport/lib/active_support/rescuable.rb8
-rw-r--r--activesupport/lib/active_support/secure_random.rb14
-rw-r--r--activesupport/lib/active_support/test_case.rb49
-rw-r--r--activesupport/lib/active_support/testing/assertions.rb61
-rw-r--r--activesupport/lib/active_support/testing/declarative.rb21
-rw-r--r--activesupport/lib/active_support/testing/deprecation.rb55
-rw-r--r--activesupport/lib/active_support/testing/setup_and_teardown.rb138
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb1
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb8
-rw-r--r--activesupport/lib/active_support/vendor.rb17
-rwxr-xr-xactivesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb6
-rw-r--r--activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb (renamed from activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb)6
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Argentina/San_Juan.rb170
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/data_timezone.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/data_timezone.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/data_timezone_info.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/data_timezone_info.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Algiers.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Algiers.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Cairo.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Cairo.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Casablanca.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Casablanca.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Harare.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Harare.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Johannesburg.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Johannesburg.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Monrovia.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Monrovia.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Nairobi.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Nairobi.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Argentina/Buenos_Aires.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Argentina/Buenos_Aires.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Argentina/San_Juan.rb86
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Bogota.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Bogota.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Caracas.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Caracas.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Chicago.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Chicago.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Chihuahua.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Chihuahua.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Denver.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Denver.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Godthab.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Godthab.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Guatemala.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Guatemala.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Halifax.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Halifax.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Indiana/Indianapolis.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Indiana/Indianapolis.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Juneau.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Juneau.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/La_Paz.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/La_Paz.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Lima.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Lima.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Los_Angeles.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Los_Angeles.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Mazatlan.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Mazatlan.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Mexico_City.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Mexico_City.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Monterrey.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Monterrey.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/New_York.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/New_York.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Phoenix.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Phoenix.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Regina.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Regina.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Santiago.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Santiago.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Sao_Paulo.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Sao_Paulo.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/St_Johns.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/St_Johns.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Tijuana.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Tijuana.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Almaty.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Almaty.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Baghdad.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Baghdad.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Baku.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Baku.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Bangkok.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Bangkok.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Chongqing.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Chongqing.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Colombo.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Colombo.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Dhaka.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Dhaka.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Hong_Kong.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Hong_Kong.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Irkutsk.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Irkutsk.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Jakarta.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Jakarta.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Jerusalem.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Jerusalem.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kabul.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kabul.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kamchatka.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kamchatka.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Karachi.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Karachi.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Katmandu.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Katmandu.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kolkata.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kolkata.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Krasnoyarsk.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Krasnoyarsk.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kuala_Lumpur.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kuala_Lumpur.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kuwait.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kuwait.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Magadan.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Magadan.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Muscat.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Muscat.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Novosibirsk.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Novosibirsk.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Rangoon.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Rangoon.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Riyadh.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Riyadh.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Seoul.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Seoul.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Shanghai.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Shanghai.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Singapore.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Singapore.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Taipei.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Taipei.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tashkent.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tashkent.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tbilisi.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tbilisi.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tehran.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tehran.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tokyo.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tokyo.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Ulaanbaatar.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Ulaanbaatar.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Urumqi.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Urumqi.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Vladivostok.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Vladivostok.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yakutsk.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yakutsk.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yekaterinburg.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yekaterinburg.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yerevan.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yerevan.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/Azores.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/Azores.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/Cape_Verde.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/Cape_Verde.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/South_Georgia.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/South_Georgia.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Adelaide.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Adelaide.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Brisbane.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Brisbane.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Darwin.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Darwin.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Hobart.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Hobart.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Melbourne.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Melbourne.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Perth.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Perth.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Sydney.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Sydney.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Etc/UTC.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Etc/UTC.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Amsterdam.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Amsterdam.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Athens.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Athens.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Belgrade.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Belgrade.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Berlin.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Berlin.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Bratislava.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Bratislava.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Brussels.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Brussels.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Bucharest.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Bucharest.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Budapest.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Budapest.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Copenhagen.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Copenhagen.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Dublin.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Dublin.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Helsinki.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Helsinki.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Istanbul.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Istanbul.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Kiev.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Kiev.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Lisbon.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Lisbon.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Ljubljana.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Ljubljana.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/London.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/London.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Madrid.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Madrid.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Minsk.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Minsk.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Moscow.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Moscow.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Paris.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Paris.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Prague.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Prague.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Riga.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Riga.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Rome.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Rome.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Sarajevo.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Sarajevo.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Skopje.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Skopje.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Sofia.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Sofia.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Stockholm.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Stockholm.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Tallinn.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Tallinn.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Vienna.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Vienna.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Vilnius.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Vilnius.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Warsaw.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Warsaw.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Zagreb.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Zagreb.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Auckland.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Auckland.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Fiji.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Fiji.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Guam.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Guam.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Honolulu.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Honolulu.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Majuro.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Majuro.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Midway.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Midway.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Noumea.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Noumea.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Pago_Pago.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Pago_Pago.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Port_Moresby.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Port_Moresby.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Tongatapu.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Tongatapu.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/info_timezone.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/info_timezone.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/linked_timezone.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/linked_timezone.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/linked_timezone_info.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/linked_timezone_info.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/offset_rationals.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/offset_rationals.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/ruby_core_support.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/ruby_core_support.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/time_or_datetime.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/time_or_datetime.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_definition.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_definition.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_info.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_info.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_offset_info.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_offset_info.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_period.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_period.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_transition_info.rb (renamed from activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_transition_info.rb)0
-rw-r--r--activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb1021
-rw-r--r--activesupport/lib/active_support/version.rb2
-rw-r--r--activesupport/lib/active_support/xml_mini.rb111
-rw-r--r--activesupport/test/abstract_unit.rb49
-rw-r--r--activesupport/test/caching_test.rb44
-rw-r--r--activesupport/test/clean_backtrace_test.rb47
-rw-r--r--activesupport/test/core_ext/array_ext_test.rb24
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb68
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb112
-rw-r--r--activesupport/test/core_ext/duration_test.rb120
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb11
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb11
-rw-r--r--activesupport/test/core_ext/module/model_naming_test.rb8
-rw-r--r--activesupport/test/core_ext/module_test.rb11
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb32
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb4
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb146
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb138
-rw-r--r--activesupport/test/dependencies_test.rb10
-rw-r--r--activesupport/test/deprecation_test.rb26
-rw-r--r--activesupport/test/i18n_test.rb12
-rw-r--r--activesupport/test/inflector_test.rb6
-rw-r--r--activesupport/test/inflector_test_cases.rb15
-rw-r--r--activesupport/test/json/encoding_test.rb18
-rw-r--r--activesupport/test/memoizable_test.rb346
-rw-r--r--activesupport/test/message_encryptor_test.rb46
-rw-r--r--activesupport/test/message_verifier_test.rb25
-rw-r--r--activesupport/test/multibyte_unicode_database_test.rb6
-rw-r--r--activesupport/test/option_merger_test.rb8
-rw-r--r--activesupport/test/ordered_hash_test.rb12
-rw-r--r--activesupport/test/test_test.rb19
-rw-r--r--activesupport/test/time_zone_test.rb80
-rw-r--r--ci/cruise_config.rb2
-rw-r--r--railties/CHANGELOG74
-rw-r--r--railties/README25
-rw-r--r--railties/Rakefile49
-rwxr-xr-xrailties/bin/process/inspector3
-rwxr-xr-xrailties/bin/process/reaper3
-rwxr-xr-xrailties/bin/process/spawner3
-rwxr-xr-xrailties/bin/rails1
-rw-r--r--railties/builtin/rails_info/rails/info.rb16
-rw-r--r--railties/config.ru17
-rw-r--r--railties/configs/apache.conf40
-rw-r--r--railties/configs/initializers/backtrace_silencers.rb7
-rw-r--r--railties/configs/initializers/new_rails_defaults.rb2
-rw-r--r--railties/configs/initializers/session_store.rb15
-rw-r--r--railties/configs/lighttpd.conf54
-rw-r--r--railties/configs/locales/en.yml5
-rw-r--r--railties/dispatches/config.ru7
-rw-r--r--railties/doc/README_FOR_APP7
-rw-r--r--railties/doc/guides/html/2_2_release_notes.html48
-rw-r--r--railties/doc/guides/html/actioncontroller_basics.html330
-rw-r--r--railties/doc/guides/html/activerecord_validations_callbacks.html749
-rw-r--r--railties/doc/guides/html/authors.html13
-rw-r--r--railties/doc/guides/html/caching_with_rails.html72
-rw-r--r--railties/doc/guides/html/command_line.html434
-rw-r--r--railties/doc/guides/html/configuring.html438
-rw-r--r--railties/doc/guides/html/creating_plugins.html1148
-rw-r--r--railties/doc/guides/html/debugging_rails_applications.html194
-rw-r--r--railties/doc/guides/html/finders.html249
-rw-r--r--railties/doc/guides/html/form_helpers.html76
-rw-r--r--railties/doc/guides/html/getting_started_with_rails.html118
-rw-r--r--railties/doc/guides/html/index.html20
-rw-r--r--railties/doc/guides/html/layouts_and_rendering.html13
-rw-r--r--railties/doc/guides/html/migrations.html6
-rw-r--r--railties/doc/guides/html/routing_outside_in.html48
-rw-r--r--railties/doc/guides/html/testing_rails_applications.html594
-rw-r--r--railties/doc/guides/source/2_2_release_notes.txt27
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/changelog.txt5
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/cookies.txt2
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/csrf.txt32
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/filters.txt18
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/http_auth.txt6
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/index.txt14
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/introduction.txt6
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/methods.txt14
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt4
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/params.txt49
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt30
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/rescue.txt8
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/session.txt32
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/streaming.txt16
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/verification.txt6
-rw-r--r--railties/doc/guides/source/active_record_basics.txt2
-rw-r--r--railties/doc/guides/source/activerecord_validations_callbacks.txt404
-rw-r--r--railties/doc/guides/source/authors.txt14
-rw-r--r--railties/doc/guides/source/caching_with_rails.txt74
-rw-r--r--railties/doc/guides/source/command_line.txt147
-rw-r--r--railties/doc/guides/source/configuring.txt225
-rw-r--r--railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt140
-rw-r--r--railties/doc/guides/source/creating_plugins/basics.markdown861
-rw-r--r--railties/doc/guides/source/creating_plugins/controllers.txt59
-rw-r--r--railties/doc/guides/source/creating_plugins/core_ext.txt123
-rw-r--r--railties/doc/guides/source/creating_plugins/custom_route.txt16
-rw-r--r--railties/doc/guides/source/creating_plugins/gem.txt1
-rw-r--r--railties/doc/guides/source/creating_plugins/generator_method.txt (renamed from railties/doc/guides/source/creating_plugins/custom_generator.txt)58
-rw-r--r--railties/doc/guides/source/creating_plugins/helpers.txt51
-rw-r--r--railties/doc/guides/source/creating_plugins/index.txt108
-rw-r--r--railties/doc/guides/source/creating_plugins/migration_generator.txt127
-rw-r--r--railties/doc/guides/source/creating_plugins/models.txt76
-rw-r--r--railties/doc/guides/source/creating_plugins/odds_and_ends.txt57
-rw-r--r--railties/doc/guides/source/creating_plugins/preparation.txt169
-rw-r--r--railties/doc/guides/source/creating_plugins/string_to_squawk.txt103
-rw-r--r--railties/doc/guides/source/creating_plugins/test_setup.txt230
-rw-r--r--railties/doc/guides/source/creating_plugins/view_helper.txt61
-rw-r--r--railties/doc/guides/source/debugging_rails_applications.txt112
-rw-r--r--railties/doc/guides/source/finders.txt89
-rw-r--r--railties/doc/guides/source/form_helpers.txt85
-rw-r--r--railties/doc/guides/source/getting_started_with_rails.txt27
-rw-r--r--railties/doc/guides/source/index.txt8
-rw-r--r--railties/doc/guides/source/layouts_and_rendering.txt5
-rw-r--r--railties/doc/guides/source/migrations/foreign_keys.txt2
-rw-r--r--railties/doc/guides/source/migrations/rakeing_around.txt2
-rw-r--r--railties/doc/guides/source/migrations/scheming.txt2
-rw-r--r--railties/doc/guides/source/routing_outside_in.txt38
-rw-r--r--railties/doc/guides/source/testing_rails_applications.txt399
-rw-r--r--railties/environments/boot.rb4
-rw-r--r--railties/environments/environment.rb59
-rw-r--r--railties/environments/production.rb17
-rw-r--r--railties/environments/test.rb5
-rw-r--r--railties/helpers/application.rb15
-rw-r--r--railties/helpers/application_controller.rb10
-rw-r--r--railties/helpers/test_helper.rb2
-rw-r--r--railties/html/javascripts/controls.js144
-rw-r--r--railties/html/javascripts/dragdrop.js329
-rw-r--r--railties/html/javascripts/effects.js338
-rw-r--r--railties/lib/commands/process/inspector.rb68
-rw-r--r--railties/lib/commands/process/reaper.rb149
-rw-r--r--railties/lib/commands/process/spawner.rb219
-rw-r--r--railties/lib/commands/process/spinner.rb57
-rw-r--r--railties/lib/commands/runner.rb18
-rw-r--r--railties/lib/commands/server.rb122
-rw-r--r--railties/lib/commands/servers/base.rb31
-rw-r--r--railties/lib/commands/servers/lighttpd.rb94
-rw-r--r--railties/lib/commands/servers/mongrel.rb69
-rw-r--r--railties/lib/commands/servers/new_mongrel.rb16
-rw-r--r--railties/lib/commands/servers/thin.rb25
-rw-r--r--railties/lib/commands/servers/webrick.rb66
-rw-r--r--railties/lib/console_app.rb3
-rw-r--r--railties/lib/console_with_helpers.rb25
-rw-r--r--railties/lib/fcgi_handler.rb2
-rw-r--r--railties/lib/initializer.rb112
-rw-r--r--railties/lib/rails/backtrace_cleaner.rb33
-rw-r--r--railties/lib/rails/gem_dependency.rb1
-rw-r--r--railties/lib/rails/mongrel_server/commands.rb342
-rw-r--r--railties/lib/rails/mongrel_server/handler.rb55
-rw-r--r--railties/lib/rails/plugin.rb49
-rw-r--r--railties/lib/rails/plugin/loader.rb42
-rw-r--r--railties/lib/rails/rack.rb1
-rw-r--r--railties/lib/rails/rack/debugger.rb21
-rw-r--r--railties/lib/rails/rack/static.rb2
-rw-r--r--railties/lib/rails/vendor_gem_source_index.rb4
-rw-r--r--railties/lib/rails/version.rb2
-rw-r--r--railties/lib/rails_generator/base.rb3
-rw-r--r--railties/lib/rails_generator/commands.rb1
-rw-r--r--railties/lib/rails_generator/generators/applications/app/app_generator.rb347
-rw-r--r--railties/lib/rails_generator/generators/applications/app/scm/git.rb16
-rw-r--r--railties/lib/rails_generator/generators/applications/app/scm/scm.rb8
-rw-r--r--railties/lib/rails_generator/generators/applications/app/scm/svn.rb7
-rw-r--r--railties/lib/rails_generator/generators/applications/app/template_runner.rb363
-rw-r--r--railties/lib/rails_generator/generators/components/controller/USAGE23
-rw-r--r--railties/lib/rails_generator/generators/components/controller/controller_generator.rb8
-rw-r--r--railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb4
-rw-r--r--railties/lib/rails_generator/generators/components/helper/USAGE24
-rw-r--r--railties/lib/rails_generator/generators/components/helper/helper_generator.rb25
-rw-r--r--railties/lib/rails_generator/generators/components/helper/templates/helper.rb2
-rw-r--r--railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb4
-rw-r--r--railties/lib/rails_generator/generators/components/resource/USAGE4
-rw-r--r--railties/lib/rails_generator/generators/components/resource/resource_generator.rb2
-rw-r--r--railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb4
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb2
-rw-r--r--railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb4
-rw-r--r--railties/lib/rails_generator/secret_key_generator.rb2
-rw-r--r--railties/lib/tasks/databases.rake14
-rw-r--r--railties/lib/tasks/framework.rake22
-rw-r--r--railties/lib/tasks/middleware.rake7
-rw-r--r--railties/lib/tasks/misc.rake6
-rw-r--r--railties/lib/tasks/statistics.rake1
-rw-r--r--railties/lib/tasks/testing.rake8
-rw-r--r--railties/lib/test_help.rb23
-rw-r--r--railties/test/abstract_unit.rb12
-rw-r--r--railties/test/backtrace_cleaner_test.rb28
-rw-r--r--railties/test/fcgi_dispatcher_test.rb7
-rw-r--r--railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb2
-rw-r--r--railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb2
-rw-r--r--railties/test/fixtures/plugins/engines/engine/config/routes.rb3
-rw-r--r--railties/test/fixtures/plugins/engines/engine/init.rb3
-rw-r--r--railties/test/gem_dependency_test.rb14
-rw-r--r--railties/test/generators/generator_test_helper.rb31
-rw-r--r--railties/test/generators/rails_controller_generator_test.rb32
-rw-r--r--railties/test/generators/rails_helper_generator_test.rb36
-rw-r--r--railties/test/generators/rails_resource_generator_test.rb4
-rw-r--r--railties/test/generators/rails_scaffold_generator_test.rb7
-rw-r--r--railties/test/initializer_test.rb67
-rw-r--r--railties/test/plugin_loader_test.rb219
-rw-r--r--railties/test/plugin_locator_test.rb2
-rw-r--r--railties/test/rails_info_controller_test.rb2
-rw-r--r--railties/test/rails_info_test.rb10
-rw-r--r--railties/test/secret_key_generation_test.rb4
-rw-r--r--railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification39
-rw-r--r--railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb1
-rw-r--r--railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification39
-rw-r--r--railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb1
603 files changed, 13060 insertions, 17183 deletions
diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG
index d8636fd83d..5dc7a33f55 100644
--- a/actionmailer/CHANGELOG
+++ b/actionmailer/CHANGELOG
@@ -1,3 +1,15 @@
+*2.3.0 [Edge]*
+
+* Fixed RFC-2045 quoted-printable bug #1421 [squadette]
+
+* Fixed that no body charset would be set when there are attachments present #740 [Paweł Kondzior]
+
+
+*2.2.1 [RC2] (November 14th, 2008)*
+
+* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 [Grant Hollingworth]
+
+
*2.2.0 [RC1] (October 24th, 2008)*
* Add layout functionality to mailers [Pratik]
diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile
index 9f4a387126..c3826e3a27 100644
--- a/actionmailer/Rakefile
+++ b/actionmailer/Rakefile
@@ -55,7 +55,7 @@ spec = Gem::Specification.new do |s|
s.rubyforge_project = "actionmailer"
s.homepage = "http://www.rubyonrails.org"
- s.add_dependency('actionpack', '= 2.2.0' + PKG_BUILD)
+ s.add_dependency('actionpack', '= 2.3.0' + PKG_BUILD)
s.has_rdoc = true
s.requirements << 'none'
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
index 2a9210deb9..0f173ea4e8 100644
--- a/actionmailer/lib/action_mailer.rb
+++ b/actionmailer/lib/action_mailer.rb
@@ -31,22 +31,31 @@ rescue LoadError
end
end
-require 'action_mailer/vendor'
-require 'tmail'
+require 'action_view'
-require 'action_mailer/base'
-require 'action_mailer/helpers'
-require 'action_mailer/mail_helper'
-require 'action_mailer/quoting'
-require 'action_mailer/test_helper'
+module ActionMailer
+ def self.load_all!
+ [Base, Part, ::Text::Format, ::Net::SMTP]
+ end
-require 'net/smtp'
+ autoload :AdvAttrAccessor, 'action_mailer/adv_attr_accessor'
+ autoload :Base, 'action_mailer/base'
+ autoload :Helpers, 'action_mailer/helpers'
+ 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'
+end
-ActionMailer::Base.class_eval do
- include ActionMailer::Quoting
- include ActionMailer::Helpers
+module Text
+ autoload :Format, 'action_mailer/vendor/text_format'
+end
- helper MailHelper
+module Net
+ autoload :SMTP, 'net/smtp'
end
-silence_warnings { TMail::Encoder.const_set("MAX_LINE_LEN", 200) }
+autoload :MailHelper, 'action_mailer/mail_helper'
+autoload :TMail, 'action_mailer/vendor/tmail'
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index 043f56ba17..730dd2d7aa 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -1,9 +1,3 @@
-require 'action_mailer/adv_attr_accessor'
-require 'action_mailer/part'
-require 'action_mailer/part_container'
-require 'action_mailer/utils'
-require 'tmail/net'
-
module ActionMailer #:nodoc:
# Action Mailer allows you to send email from your application using a mailer model and views.
#
@@ -245,7 +239,7 @@ module ActionMailer #:nodoc:
# 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
+ include AdvAttrAccessor, PartContainer, Quoting, Utils
if Object.const_defined?(:ActionController)
include ActionController::UrlWriter
include ActionController::Layout
@@ -386,12 +380,15 @@ module ActionMailer #:nodoc:
end
def method_missing(method_symbol, *parameters) #:nodoc:
- match = matches_dynamic_method?(method_symbol)
- case match[1]
- when 'create' then new(match[2], *parameters).mail
- when 'deliver' then new(match[2], *parameters).deliver!
- when 'new' then nil
- else super
+ if match = matches_dynamic_method?(method_symbol)
+ case match[1]
+ when 'create' then new(match[2], *parameters).mail
+ when 'deliver' then new(match[2], *parameters).deliver!
+ when 'new' then nil
+ else super
+ end
+ else
+ super
end
end
@@ -423,12 +420,6 @@ module ActionMailer #:nodoc:
new.deliver!(mail)
end
- def register_template_extension(extension)
- ActiveSupport::Deprecation.warn(
- "ActionMailer::Base.register_template_extension has been deprecated." +
- "Use ActionView::Base.register_template_extension instead", caller)
- end
-
def template_root
self.view_paths && self.view_paths.first
end
@@ -440,7 +431,7 @@ module ActionMailer #:nodoc:
private
def matches_dynamic_method?(method_name) #:nodoc:
method_name = method_name.to_s
- /(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
+ /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
end
end
@@ -546,7 +537,12 @@ module ActionMailer #:nodoc:
end
def render_message(method_name, body)
+ if method_name.respond_to?(:content_type)
+ @current_template_content_type = method_name.content_type
+ end
render :file => method_name, :body => body
+ ensure
+ @current_template_content_type = nil
end
def render(opts)
@@ -565,7 +561,11 @@ module ActionMailer #:nodoc:
end
def default_template_format
- :html
+ if @current_template_content_type
+ Mime::Type.lookup(@current_template_content_type).to_sym
+ else
+ :html
+ end
end
def candidate_for_layout?(options)
@@ -585,7 +585,9 @@ module ActionMailer #:nodoc:
end
def initialize_template_class(assigns)
- ActionView::Base.new(view_paths, assigns, self)
+ template = ActionView::Base.new(view_paths, assigns, self)
+ template.template_format = default_template_format
+ template
end
def sort_parts(parts, order = [])
@@ -634,11 +636,11 @@ module ActionMailer #:nodoc:
if @parts.empty?
m.set_content_type(real_content_type, nil, ctype_attrs)
- m.body = Utils.normalize_new_lines(body)
+ m.body = normalize_new_lines(body)
else
if String === body
part = TMail::Mail.new
- part.body = Utils.normalize_new_lines(body)
+ part.body = normalize_new_lines(body)
part.set_content_type(real_content_type, nil, ctype_attrs)
part.set_content_disposition "inline"
m.parts << part
@@ -663,8 +665,10 @@ module ActionMailer #:nodoc:
mail.ready_to_send
sender = mail['return-path'] || mail.from
- Net::SMTP.start(smtp_settings[:address], smtp_settings[:port], smtp_settings[:domain],
- smtp_settings[:user_name], smtp_settings[:password], smtp_settings[:authentication]) do |smtp|
+ smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
+ smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto)
+ smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password],
+ smtp_settings[:authentication]) do |smtp|
smtp.sendmail(mail.encoded, sender, destinations)
end
end
@@ -682,4 +686,9 @@ module ActionMailer #:nodoc:
deliveries << mail
end
end
+
+ Base.class_eval do
+ include Helpers
+ helper MailHelper
+ end
end
diff --git a/actionmailer/lib/action_mailer/helpers.rb b/actionmailer/lib/action_mailer/helpers.rb
index 5f6dcd77cd..31f7de8d60 100644
--- a/actionmailer/lib/action_mailer/helpers.rb
+++ b/actionmailer/lib/action_mailer/helpers.rb
@@ -1,3 +1,5 @@
+require 'active_support/dependencies'
+
module ActionMailer
module Helpers #:nodoc:
def self.included(base) #:nodoc:
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
index 11fd7d77e0..351b966abe 100644
--- a/actionmailer/lib/action_mailer/mail_helper.rb
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -1,5 +1,3 @@
-require 'text/format'
-
module MailHelper
# Uses Text::Format to take the text and format it, indented two spaces for
# each line, and wrapped at 72 columns.
diff --git a/actionmailer/lib/action_mailer/part.rb b/actionmailer/lib/action_mailer/part.rb
index 2dabf15f08..977c0b2b5c 100644
--- a/actionmailer/lib/action_mailer/part.rb
+++ b/actionmailer/lib/action_mailer/part.rb
@@ -1,15 +1,10 @@
-require 'action_mailer/adv_attr_accessor'
-require 'action_mailer/part_container'
-require 'action_mailer/utils'
-
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 ActionMailer::AdvAttrAccessor
- include ActionMailer::PartContainer
+ 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
@@ -64,7 +59,7 @@ module ActionMailer
when "base64" then
part.body = TMail::Base64.folding_encode(body)
when "quoted-printable"
- part.body = [Utils.normalize_new_lines(body)].pack("M*")
+ part.body = [normalize_new_lines(body)].pack("M*")
else
part.body = body
end
@@ -102,7 +97,6 @@ module ActionMailer
end
private
-
def squish(values={})
values.delete_if { |k,v| v.nil? }
end
diff --git a/actionmailer/lib/action_mailer/part_container.rb b/actionmailer/lib/action_mailer/part_container.rb
index 3e3d6b9d4f..abfd8f8426 100644
--- a/actionmailer/lib/action_mailer/part_container.rb
+++ b/actionmailer/lib/action_mailer/part_container.rb
@@ -41,7 +41,11 @@ module ActionMailer
private
def parse_content_type(defaults=nil)
- return [defaults && defaults.content_type, {}] if content_type.blank?
+ 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)]
diff --git a/actionmailer/lib/action_mailer/quoting.rb b/actionmailer/lib/action_mailer/quoting.rb
index a2f2c70799..94fa042002 100644
--- a/actionmailer/lib/action_mailer/quoting.rb
+++ b/actionmailer/lib/action_mailer/quoting.rb
@@ -12,7 +12,7 @@ module ActionMailer
# account multi-byte characters (if executing with $KCODE="u", for instance)
def quoted_printable_encode(character)
result = ""
- character.each_byte { |b| result << "=%02x" % b }
+ character.each_byte { |b| result << "=%02X" % b }
result
end
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb
index d474afe3a2..8035db6f03 100644
--- a/actionmailer/lib/action_mailer/test_case.rb
+++ b/actionmailer/lib/action_mailer/test_case.rb
@@ -10,7 +10,7 @@ module ActionMailer
end
class TestCase < ActiveSupport::TestCase
- include ActionMailer::Quoting
+ include Quoting, TestHelper
setup :initialize_test_deliveries
setup :set_expected_mail
diff --git a/actionmailer/lib/action_mailer/test_helper.rb b/actionmailer/lib/action_mailer/test_helper.rb
index 3a1612442f..f234c0248c 100644
--- a/actionmailer/lib/action_mailer/test_helper.rb
+++ b/actionmailer/lib/action_mailer/test_helper.rb
@@ -58,6 +58,7 @@ module ActionMailer
end
end
+# TODO: Deprecate this
module Test
module Unit
class TestCase
diff --git a/actionmailer/lib/action_mailer/utils.rb b/actionmailer/lib/action_mailer/utils.rb
index 552f695a92..26d2e60aaf 100644
--- a/actionmailer/lib/action_mailer/utils.rb
+++ b/actionmailer/lib/action_mailer/utils.rb
@@ -3,6 +3,5 @@ module ActionMailer
def normalize_new_lines(text)
text.to_s.gsub(/\r\n?/, "\n")
end
- module_function :normalize_new_lines
end
end
diff --git a/actionmailer/lib/action_mailer/vendor.rb b/actionmailer/lib/action_mailer/vendor.rb
deleted file mode 100644
index 7a20e9bd6e..0000000000
--- a/actionmailer/lib/action_mailer/vendor.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# Prefer gems to the bundled libs.
-require 'rubygems'
-
-begin
- gem 'tmail', '~> 1.2.3'
-rescue Gem::LoadError
- $:.unshift "#{File.dirname(__FILE__)}/vendor/tmail-1.2.3"
-end
-
-begin
- gem 'text-format', '>= 0.6.3'
-rescue Gem::LoadError
- $:.unshift "#{File.dirname(__FILE__)}/vendor/text-format-0.6.3"
-end
diff --git a/actionmailer/lib/action_mailer/vendor/text_format.rb b/actionmailer/lib/action_mailer/vendor/text_format.rb
new file mode 100644
index 0000000000..c6c8c394d0
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/text_format.rb
@@ -0,0 +1,10 @@
+# Prefer gems to the bundled libs.
+require 'rubygems'
+
+begin
+ gem 'text-format', '>= 0.6.3'
+rescue Gem::LoadError
+ $:.unshift "#{File.dirname(__FILE__)}/text-format-0.6.3"
+end
+
+require 'text/format'
diff --git a/actionmailer/lib/action_mailer/vendor/tmail.rb b/actionmailer/lib/action_mailer/vendor/tmail.rb
new file mode 100644
index 0000000000..51d36cdd0d
--- /dev/null
+++ b/actionmailer/lib/action_mailer/vendor/tmail.rb
@@ -0,0 +1,17 @@
+# 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'
+
+silence_warnings do
+ TMail::Encoder.const_set("MAX_LINE_LEN", 200)
+end
diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb
index 9728d1b4db..9cd7a14b73 100644
--- a/actionmailer/lib/action_mailer/version.rb
+++ b/actionmailer/lib/action_mailer/version.rb
@@ -1,7 +1,7 @@
module ActionMailer
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 2
+ MINOR = 3
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
index 905f25c9f7..1617b88c8e 100644
--- a/actionmailer/test/abstract_unit.rb
+++ b/actionmailer/test/abstract_unit.rb
@@ -24,11 +24,15 @@ class MockSMTP
def sendmail(mail, from, to)
@@deliveries << [mail, from, to]
end
+
+ def start(*args)
+ yield self
+ end
end
class Net::SMTP
- def self.start(*args)
- yield MockSMTP.new
+ def self.new(*args)
+ MockSMTP.new
end
end
diff --git a/actionmailer/test/asset_host_test.rb b/actionmailer/test/asset_host_test.rb
new file mode 100644
index 0000000000..1c92dd266d
--- /dev/null
+++ b/actionmailer/test/asset_host_test.rb
@@ -0,0 +1,54 @@
+require 'abstract_unit'
+
+class AssetHostMailer < ActionMailer::Base
+ def email_with_asset(recipient)
+ recipients recipient
+ subject "testing email containing asset path while asset_host is set"
+ from "tester@example.com"
+ end
+end
+
+class AssetHostTest < Test::Unit::TestCase
+ def setup
+ set_delivery_method :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries = []
+
+ @recipient = 'test@localhost'
+ end
+
+ def teardown
+ restore_delivery_method
+ end
+
+ 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
+ end
+
+ def test_asset_host_as_one_arguement_proc
+ ActionController::Base.asset_host = Proc.new { |source|
+ if source.starts_with?('/images')
+ "http://images.example.com"
+ else
+ "http://assets.example.com"
+ end
+ }
+ mail = AssetHostMailer.deliver_email_with_asset(@recipient)
+ assert_equal "<img alt=\"Somelogo\" src=\"http://images.example.com/images/somelogo.png\" />", mail.body.strip
+ end
+
+ def test_asset_host_as_two_arguement_proc
+ ActionController::Base.asset_host = Proc.new {|source,request|
+ if request && request.ssl?
+ "https://www.example.com"
+ else
+ "http://www.example.com"
+ end
+ }
+ mail = nil
+ assert_nothing_raised { mail = AssetHostMailer.deliver_email_with_asset(@recipient) }
+ assert_equal "<img alt=\"Somelogo\" src=\"http://www.example.com/images/somelogo.png\" />", mail.body.strip
+ end
+end \ No newline at end of file
diff --git a/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb b/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb
new file mode 100644
index 0000000000..b3f0438d03
--- /dev/null
+++ b/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb
@@ -0,0 +1 @@
+<%= image_tag "somelogo.png" %> \ No newline at end of file
diff --git a/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.html.erb b/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.html.erb
new file mode 100644
index 0000000000..6d73f199c4
--- /dev/null
+++ b/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.html.erb
@@ -0,0 +1 @@
+text/html multipart \ No newline at end of file
diff --git a/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.plain.erb b/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.plain.erb
new file mode 100644
index 0000000000..f4b91e4031
--- /dev/null
+++ b/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.plain.erb
@@ -0,0 +1 @@
+text/plain multipart \ No newline at end of file
diff --git a/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb b/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb
new file mode 100644
index 0000000000..111576b672
--- /dev/null
+++ b/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb
@@ -0,0 +1 @@
+text/plain layout - <%= yield %> \ No newline at end of file
diff --git a/actionmailer/test/mail_layout_test.rb b/actionmailer/test/mail_layout_test.rb
index ffba9a16bd..c185bd5acd 100644
--- a/actionmailer/test/mail_layout_test.rb
+++ b/actionmailer/test/mail_layout_test.rb
@@ -20,6 +20,12 @@ class AutoLayoutMailer < ActionMailer::Base
from "tester@example.com"
body render(:inline => "Hello, <%= @world %>", :layout => false, :body => { :world => "Earth" })
end
+
+ def multipart(recipient)
+ recipients recipient
+ subject "You have a mail"
+ from "tester@example.com"
+ end
end
class ExplicitLayoutMailer < ActionMailer::Base
@@ -56,6 +62,17 @@ class LayoutMailerTest < Test::Unit::TestCase
assert_equal "Hello from layout Inside", mail.body.strip
end
+ def test_should_pickup_multipart_layout
+ mail = AutoLayoutMailer.create_multipart(@recipient)
+ 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/html', mail.parts.last.content_type
+ assert_equal "Hello from layout text/html multipart", mail.parts.last.body
+ end
+
def test_should_pickup_layout_given_to_render
mail = AutoLayoutMailer.create_spam(@recipient)
assert_equal "Spammer layout Hello, Earth", mail.body.strip
diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb
index 7f9540c44b..c49049cc6a 100644
--- a/actionmailer/test/mail_service_test.rb
+++ b/actionmailer/test/mail_service_test.rb
@@ -915,6 +915,8 @@ 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_equal 'text/plain', mail.parts[0].content_type
+ assert_equal 'utf-8', mail.parts[0].charset
end
def test_custom_content_type_attributes
@@ -938,6 +940,20 @@ EOF
mail = TestMailer.create_body_ivar(@recipient)
assert_equal "body: foo\nbar: baz", mail.body
end
+
+ def test_starttls_is_enabled_if_supported
+ MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(true)
+ MockSMTP.any_instance.expects(:enable_starttls_auto)
+ ActionMailer::Base.delivery_method = :smtp
+ TestMailer.deliver_signed_up(@recipient)
+ end
+
+ def test_starttls_is_disabled_if_not_supported
+ MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(false)
+ MockSMTP.any_instance.expects(:enable_starttls_auto).never
+ ActionMailer::Base.delivery_method = :smtp
+ TestMailer.deliver_signed_up(@recipient)
+ end
end
end # uses_mocha
@@ -1031,4 +1047,16 @@ class RespondToTest < Test::Unit::TestCase
def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_digit
assert !RespondToMailer.respond_to?(:deliver_1_template)
end
+
+ def test_should_not_respond_to_method_where_deliver_is_not_a_suffix
+ assert !RespondToMailer.respond_to?(:foo_deliver_template)
+ end
+
+ def test_should_still_raise_exception_with_expected_message_when_calling_an_undefined_method
+ error = assert_raises NoMethodError do
+ RespondToMailer.not_a_method
+ end
+
+ assert_match /undefined method.*not_a_method/, error.message
+ end
end
diff --git a/actionmailer/test/quoting_test.rb b/actionmailer/test/quoting_test.rb
index 13a859a5cc..2650efccdb 100644
--- a/actionmailer/test/quoting_test.rb
+++ b/actionmailer/test/quoting_test.rb
@@ -1,6 +1,5 @@
# encoding: utf-8
require 'abstract_unit'
-require 'tmail'
require 'tempfile'
class QuotingTest < Test::Unit::TestCase
diff --git a/actionmailer/test/test_helper_test.rb b/actionmailer/test/test_helper_test.rb
index f8913e548c..9d22bb26bd 100644
--- a/actionmailer/test/test_helper_test.rb
+++ b/actionmailer/test/test_helper_test.rb
@@ -36,7 +36,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
def test_encode
- assert_equal "=?utf-8?Q?=0aasdf=0a?=", encode("\nasdf\n")
+ assert_equal "=?utf-8?Q?=0Aasdf=0A?=", encode("\nasdf\n")
end
def test_assert_emails
@@ -84,7 +84,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
def test_assert_emails_too_few_sent
- error = assert_raises Test::Unit::AssertionFailedError do
+ error = assert_raises ActiveSupport::TestCase::Assertion do
assert_emails 2 do
TestHelperMailer.deliver_test
end
@@ -94,7 +94,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
def test_assert_emails_too_many_sent
- error = assert_raises Test::Unit::AssertionFailedError do
+ error = assert_raises ActiveSupport::TestCase::Assertion do
assert_emails 1 do
TestHelperMailer.deliver_test
TestHelperMailer.deliver_test
@@ -105,7 +105,7 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
def test_assert_no_emails_failure
- error = assert_raises Test::Unit::AssertionFailedError do
+ error = assert_raises ActiveSupport::TestCase::Assertion do
assert_no_emails do
TestHelperMailer.deliver_test
end
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 17fada156d..352c4253f4 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,4 +1,65 @@
-*2.2.1 [RC2 or 2.2 final]*
+*2.3.0 [Edge]*
+
+* Allow users to opt out of the spoofing checks in Request#remote_ip. Useful for sites whose traffic regularly triggers false positives. [Darren Boyd]
+
+* Deprecated formatted_polymorphic_url. [Jeremy Kemper]
+
+* Added the option to declare an asset_host as an object that responds to call (see http://github.com/dhh/asset-hosting-with-minimum-ssl for an example) [DHH]
+
+* Added support for multiple routes.rb files (useful for plugin engines). This also means that draw will no longer clear the route set, you have to do that by hand (shouldn't make a difference to you unless you're doing some funky stuff) [DHH]
+
+* Dropped formatted_* routes in favor of just passing in :format as an option. This cuts resource routes generation in half #1359 [aaronbatalion]
+
+* Remove support for old double-encoded cookies from the cookie store. These values haven't been generated since before 2.1.0, and any users who have visited the app in the intervening 6 months will have had their cookie upgraded. [Koz]
+
+* Allow helpers directory to be overridden via ActionController::Base.helpers_dir #1424 [Sam Pohlenz]
+
+* Remove deprecated ActionController::Base#assign_default_content_type_and_charset
+
+* Changed the default of ActionView#render to assume partials instead of files when not given an options hash [DHH]. Examples:
+
+ # Instead of <%= render :partial => "account" %>
+ <%= render "account" %>
+
+ # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %>
+ <%= render "account", :account => @buyer %>
+
+ # @account is an Account instance, so it uses the RecordIdentifier to replace
+ # <%= render :partial => "accounts/account", :locals => { :account => @account } %>
+ <%= render(@account) %>
+
+ # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
+ # <%= render :partial => "posts/post", :collection => @posts %>
+ <%= render(@posts) %>
+
+* Remove deprecated render_component. Please use the plugin from http://github.com/rails/render_component/tree/master [Pratik]
+
+* Fixed RedCloth and BlueCloth shouldn't preload. Instead just assume that they're available if you want to use textilize and markdown and let autoload require them [DHH]
+
+
+*2.2.2 (November 21st, 2008)*
+
+* I18n: translate number_to_human_size. Add storage_units: [Bytes, KB, MB, GB, TB] to your translations. #1448 [Yaroslav Markin]
+
+* Restore backwards compatible functionality for setting relative_url_root. Include deprecation
+
+* Switched the CSRF module to use the request content type to decide if the request is forgeable. #1145 [Jeff Cohen]
+
+* Added :only and :except to map.resources to let people cut down on the number of redundant routes in an application. Typically only useful for huge routesets. #1215 [Tom Stuart]
+
+ map.resources :products, :only => :show do |product|
+ product.resources :images, :except => :destroy
+ end
+
+* Added render :js for people who want to render inline JavaScript replies without using RJS [DHH]
+
+* Fixed that polymorphic_url should compact given array #1317 [hiroshi]
+
+* Fixed the sanitize helper to avoid double escaping already properly escaped entities #683 [antonmos/Ryan McGeary]
+
+* Fixed that FormTagHelper generated illegal html if name contained square brackets #1238 [Vladimir Dobriakov]
+
+* Fix regression bug that made date_select and datetime_select raise a Null Pointer Exception when a nil date/datetime was passed and only month and year were displayed #1289 [Bernardo Padua/Tor Erik]
* Simplified the logging format for parameters (don't include controller, action, and format as duplicates) [DHH]
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 73da8b1ce3..1a1b908122 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -80,7 +80,8 @@ spec = Gem::Specification.new do |s|
s.has_rdoc = true
s.requirements << 'none'
- s.add_dependency('activesupport', '= 2.2.0' + PKG_BUILD)
+ s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
+ s.add_dependency('rack', '= 0.4.0')
s.require_path = 'lib'
s.autorequire = 'action_controller'
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 2efd0dad2e..2981f625a1 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -31,49 +31,77 @@ rescue LoadError
end
end
-$:.unshift "#{File.dirname(__FILE__)}/action_controller/vendor/html-scanner"
+gem 'rack', '~> 0.4.0'
+require 'rack'
-require 'action_controller/base'
-require 'action_controller/request'
-require 'action_controller/rescue'
-require 'action_controller/benchmarking'
-require 'action_controller/flash'
-require 'action_controller/filters'
-require 'action_controller/layout'
-require 'action_controller/mime_responds'
-require 'action_controller/helpers'
-require 'action_controller/cookies'
-require 'action_controller/cgi_process'
-require 'action_controller/caching'
-require 'action_controller/verification'
-require 'action_controller/streaming'
-require 'action_controller/session_management'
-require 'action_controller/http_authentication'
-require 'action_controller/components'
-require 'action_controller/rack_process'
-require 'action_controller/record_identifier'
-require 'action_controller/request_forgery_protection'
-require 'action_controller/headers'
-require 'action_controller/translation'
+module ActionController
+ # TODO: Review explicit to see if they will automatically be handled by
+ # the initilizer if they are really needed.
+ def self.load_all!
+ [Base, CgiRequest, CgiResponse, RackRequest, RackRequest, Http::Headers, UrlRewriter, UrlWriter]
+ end
-require 'action_view'
+ autoload :AbstractRequest, 'action_controller/request'
+ autoload :AbstractResponse, 'action_controller/response'
+ autoload :Base, 'action_controller/base'
+ autoload :Benchmarking, 'action_controller/benchmarking'
+ autoload :Caching, 'action_controller/caching'
+ autoload :CgiRequest, 'action_controller/cgi_process'
+ autoload :CgiResponse, 'action_controller/cgi_process'
+ autoload :Cookies, 'action_controller/cookies'
+ autoload :Dispatcher, 'action_controller/dispatcher'
+ autoload :Filters, 'action_controller/filters'
+ autoload :Flash, 'action_controller/flash'
+ autoload :Helpers, 'action_controller/helpers'
+ autoload :HttpAuthentication, 'action_controller/http_authentication'
+ autoload :Integration, 'action_controller/integration'
+ autoload :IntegrationTest, 'action_controller/integration'
+ autoload :Layout, 'action_controller/layout'
+ autoload :MiddlewareStack, 'action_controller/middleware_stack'
+ autoload :MimeResponds, 'action_controller/mime_responds'
+ autoload :PolymorphicRoutes, 'action_controller/polymorphic_routes'
+ autoload :RackRequest, 'action_controller/rack_process'
+ autoload :RackResponse, 'action_controller/rack_process'
+ autoload :RecordIdentifier, 'action_controller/record_identifier'
+ autoload :RequestForgeryProtection, 'action_controller/request_forgery_protection'
+ autoload :Rescue, 'action_controller/rescue'
+ autoload :Resources, 'action_controller/resources'
+ autoload :Routing, 'action_controller/routing'
+ autoload :SessionManagement, 'action_controller/session_management'
+ autoload :StatusCodes, 'action_controller/status_codes'
+ autoload :Streaming, 'action_controller/streaming'
+ autoload :TestCase, 'action_controller/test_case'
+ autoload :TestProcess, 'action_controller/test_process'
+ autoload :Translation, 'action_controller/translation'
+ autoload :UrlRewriter, 'action_controller/url_rewriter'
+ autoload :UrlWriter, 'action_controller/url_rewriter'
+ autoload :Verification, 'action_controller/verification'
+
+ module Assertions
+ autoload :DomAssertions, 'action_controller/assertions/dom_assertions'
+ autoload :ModelAssertions, 'action_controller/assertions/model_assertions'
+ autoload :ResponseAssertions, 'action_controller/assertions/response_assertions'
+ autoload :RoutingAssertions, 'action_controller/assertions/routing_assertions'
+ autoload :SelectorAssertions, 'action_controller/assertions/selector_assertions'
+ autoload :TagAssertions, 'action_controller/assertions/tag_assertions'
+ end
+
+ module Http
+ autoload :Headers, 'action_controller/headers'
+ end
+end
-ActionController::Base.class_eval do
- include ActionController::Flash
- include ActionController::Filters
- include ActionController::Layout
- include ActionController::Benchmarking
- include ActionController::Rescue
- include ActionController::MimeResponds
- include ActionController::Helpers
- include ActionController::Cookies
- include ActionController::Caching
- include ActionController::Verification
- include ActionController::Streaming
- include ActionController::SessionManagement
- include ActionController::HttpAuthentication::Basic::ControllerMethods
- include ActionController::Components
- include ActionController::RecordIdentifier
- include ActionController::RequestForgeryProtection
- include ActionController::Translation
+class CGI
+ class Session
+ autoload :ActiveRecordStore, 'action_controller/session/active_record_store'
+ autoload :CookieStore, 'action_controller/session/cookie_store'
+ autoload :DRbStore, 'action_controller/session/drb_store'
+ autoload :MemCacheStore, 'action_controller/session/mem_cache_store'
+ end
end
+
+autoload :Mime, 'action_controller/mime_type'
+
+autoload :HTML, 'action_controller/vendor/html-scanner'
+
+require 'action_view'
diff --git a/actionpack/lib/action_controller/assertions.rb b/actionpack/lib/action_controller/assertions.rb
deleted file mode 100644
index 5b9a2b71f2..0000000000
--- a/actionpack/lib/action_controller/assertions.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-require 'test/unit/assertions'
-
-module ActionController #:nodoc:
- # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
- # can be used against. These collections are:
- #
- # * assigns: Instance variables assigned in the action that are available for the view.
- # * session: Objects being saved in the session.
- # * flash: The flash objects currently in the session.
- # * cookies: Cookies being sent to the user on this request.
- #
- # These collections can be used just like any other hash:
- #
- # assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
- # assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
- # assert flash.empty? # makes sure that there's nothing in the flash
- #
- # For historic reasons, the assigns hash uses string-based keys. So assigns[:person] won't work, but assigns["person"] will. To
- # appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
- # So assigns(:person) will work just like assigns["person"], but again, assigns[:person] will not work.
- #
- # On top of the collections, you have the complete url that a given action redirected to available in redirect_to_url.
- #
- # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
- # action call which can then be asserted against.
- #
- # == Manipulating the request collections
- #
- # The collections described above link to the response, so you can test if what the actions were expected to do happened. But
- # sometimes you also want to manipulate these collections in the incoming request. This is really only relevant for sessions
- # and cookies, though. For sessions, you just do:
- #
- # @request.session[:key] = "value"
- #
- # For cookies, you need to manually create the cookie, like this:
- #
- # @request.cookies["key"] = CGI::Cookie.new("key", "value")
- #
- # == Testing named routes
- #
- # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
- # Example:
- #
- # assert_redirected_to page_url(:title => 'foo')
- module Assertions
- def self.included(klass)
- %w(response selector tag dom routing model).each do |kind|
- require "action_controller/assertions/#{kind}_assertions"
- klass.module_eval { include const_get("#{kind.camelize}Assertions") }
- end
- end
-
- def clean_backtrace(&block)
- yield
- rescue Test::Unit::AssertionFailedError => error
- framework_path = Regexp.new(File.expand_path("#{File.dirname(__FILE__)}/assertions"))
- error.backtrace.reject! { |line| File.expand_path(line) =~ framework_path }
- raise
- end
- end
-end
-
-module Test #:nodoc:
- module Unit #:nodoc:
- class TestCase #:nodoc:
- include ActionController::Assertions
- end
- end
-end
diff --git a/actionpack/lib/action_controller/assertions/model_assertions.rb b/actionpack/lib/action_controller/assertions/model_assertions.rb
index d25214bb66..3a7b39b106 100644
--- a/actionpack/lib/action_controller/assertions/model_assertions.rb
+++ b/actionpack/lib/action_controller/assertions/model_assertions.rb
@@ -11,6 +11,7 @@ module ActionController
# assert_valid(model)
#
def assert_valid(record)
+ ::ActiveSupport::Deprecation.warn("assert_valid is deprecated. Use assert record.valid? instead", caller)
clean_backtrace do
assert record.valid?, record.errors.full_messages.join("\n")
end
diff --git a/actionpack/lib/action_controller/assertions/response_assertions.rb b/actionpack/lib/action_controller/assertions/response_assertions.rb
index e2e8bbdc71..7ab24389b8 100644
--- a/actionpack/lib/action_controller/assertions/response_assertions.rb
+++ b/actionpack/lib/action_controller/assertions/response_assertions.rb
@@ -1,6 +1,3 @@
-require 'rexml/document'
-require 'html/document'
-
module ActionController
module Assertions
# A small suite of assertions that test responses from Rails applications.
diff --git a/actionpack/lib/action_controller/assertions/selector_assertions.rb b/actionpack/lib/action_controller/assertions/selector_assertions.rb
index bcbb570e4b..e03fed7abb 100644
--- a/actionpack/lib/action_controller/assertions/selector_assertions.rb
+++ b/actionpack/lib/action_controller/assertions/selector_assertions.rb
@@ -3,9 +3,6 @@
# Under MIT and/or CC By license.
#++
-require 'rexml/document'
-require 'html/document'
-
module ActionController
module Assertions
unless const_defined?(:NO_STRIP)
diff --git a/actionpack/lib/action_controller/assertions/tag_assertions.rb b/actionpack/lib/action_controller/assertions/tag_assertions.rb
index 90ba3668fb..80249e0e83 100644
--- a/actionpack/lib/action_controller/assertions/tag_assertions.rb
+++ b/actionpack/lib/action_controller/assertions/tag_assertions.rb
@@ -1,6 +1,3 @@
-require 'rexml/document'
-require 'html/document'
-
module ActionController
module Assertions
# Pair of assertions to testing elements in the HTML output of the response.
@@ -127,4 +124,4 @@ module ActionController
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index b001b355dc..c2f0c1c4f6 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -1,12 +1,3 @@
-require 'action_controller/mime_type'
-require 'action_controller/request'
-require 'action_controller/response'
-require 'action_controller/routing'
-require 'action_controller/resources'
-require 'action_controller/url_rewriter'
-require 'action_controller/status_codes'
-require 'action_view'
-require 'drb'
require 'set'
module ActionController #:nodoc:
@@ -336,6 +327,10 @@ module ActionController #:nodoc:
# sets it to <tt>:authenticity_token</tt> by default.
cattr_accessor :request_forgery_protection_token
+ # Controls the IP Spoofing check when determining the remote IP.
+ @@ip_spoofing_check = true
+ cattr_accessor :ip_spoofing_check
+
# Indicates whether or not optimise the generated named
# route helper methods
cattr_accessor :optimise_named_routes
@@ -529,7 +524,7 @@ module ActionController #:nodoc:
end
def send_response
- response.prepare! unless component_request?
+ response.prepare!
response
end
@@ -876,8 +871,9 @@ module ActionController #:nodoc:
end
end
- response.layout = layout = pick_layout(options)
- logger.info("Rendering template within #{layout}") if logger && layout
+ layout = pick_layout(options)
+ response.layout = layout.path_without_format_and_extension if layout
+ logger.info("Rendering template within #{layout.path_without_format_and_extension}") if logger && layout
if content_type = options[:content_type]
response.content_type = content_type.to_s
@@ -1029,10 +1025,10 @@ module ActionController #:nodoc:
#
# * <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 starting with protocol:// (like http://)</tt> - Is passed straight through as the target for redirection.
- # * <tt>String not containing a protocol</tt> - The current protocol and host is prepended to the string.
+ # * <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 redirect_to(request.env["HTTP_REFERER"])
+ # Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
#
# Examples:
# redirect_to :action => "show", :id => 5
@@ -1064,7 +1060,7 @@ module ActionController #:nodoc:
status = 302
end
- response.redirected_to= options
+ response.redirected_to = options
logger.info("Redirected to #{options}") if logger && logger.info?
case options
@@ -1239,9 +1235,9 @@ module ActionController #:nodoc:
def log_processing_for_parameters
parameters = respond_to?(:filter_parameters) ? filter_parameters(params) : params.dup
- parameters = parameters.except!(:controller, :action, :format)
+ parameters = parameters.except!(:controller, :action, :format, :_method)
- logger.info " Parameters: #{parameters.inspect}"
+ logger.info " Parameters: #{parameters.inspect}" unless parameters.empty?
end
def default_render #:nodoc:
@@ -1270,11 +1266,6 @@ module ActionController #:nodoc:
@action_name = (params['action'] || 'index')
end
- def assign_default_content_type_and_charset
- response.assign_default_content_type_and_charset!
- end
- deprecate :assign_default_content_type_and_charset => :'response.assign_default_content_type_and_charset!'
-
def action_methods
self.class.action_methods
end
@@ -1337,4 +1328,11 @@ module ActionController #:nodoc:
close_session
end
end
+
+ Base.class_eval do
+ include Flash, Filters, Layout, Benchmarking, Rescue, MimeResponds, Helpers
+ include Cookies, Caching, Verification, Streaming
+ include SessionManagement, HttpAuthentication::Basic::ControllerMethods
+ include RecordIdentifier, RequestForgeryProtection, Translation
+ end
end
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index c4063dfb4b..b4d251eb3c 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -2,13 +2,6 @@ require 'fileutils'
require 'uri'
require 'set'
-require 'action_controller/caching/pages'
-require 'action_controller/caching/actions'
-require 'action_controller/caching/sql_cache'
-require 'action_controller/caching/sweeping'
-require 'action_controller/caching/fragments'
-
-
module ActionController #:nodoc:
# Caching is a cheap way of speeding up slow applications by keeping the result of calculations, renderings, and database calls
# around for subsequent requests. Action Controller affords you three approaches in varying levels of granularity: Page, Action, Fragment.
@@ -31,6 +24,12 @@ module ActionController #:nodoc:
# ActionController::Base.cache_store = :mem_cache_store, "localhost"
# ActionController::Base.cache_store = MyOwnStore.new("parameter")
module Caching
+ autoload :Actions, 'action_controller/caching/actions'
+ autoload :Fragments, 'action_controller/caching/fragments'
+ autoload :Pages, 'action_controller/caching/pages'
+ autoload :SqlCache, 'action_controller/caching/sql_cache'
+ autoload :Sweeping, 'action_controller/caching/sweeping'
+
def self.included(base) #:nodoc:
base.class_eval do
@@cache_store = nil
@@ -63,10 +62,9 @@ module ActionController #:nodoc:
end
end
-
- private
+ private
def cache_configured?
self.class.cache_configured?
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
index 31cbe27452..c41b1a12cf 100644
--- a/actionpack/lib/action_controller/caching/fragments.rb
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -10,23 +10,23 @@ module ActionController #:nodoc:
# <%= render :partial => "topic", :collection => Topic.find(:all) %>
# <% end %>
#
- # This cache will bind to the name of the action that called it, so if this code was part of the view for the topics/list action, you would
- # be able to invalidate it using <tt>expire_fragment(:controller => "topics", :action => "list")</tt>.
- #
- # This default behavior is of limited use if you need to cache multiple fragments per action or if the action itself is cached using
+ # This cache will bind to the name of the action that called it, so if this code was part of the view for the topics/list action, you would
+ # be able to invalidate it using <tt>expire_fragment(:controller => "topics", :action => "list")</tt>.
+ #
+ # This default behavior is of limited use if you need to cache multiple fragments per action or if the action itself is cached using
# <tt>caches_action</tt>, so we also have the option to qualify the name of the cached fragment with something like:
#
# <% cache(:action => "list", :action_suffix => "all_topics") do %>
#
- # That would result in a name such as "/topics/list/all_topics", avoiding conflicts with the action cache and with any fragments that use a
- # different suffix. Note that the URL doesn't have to really exist or be callable - the url_for system is just used to generate unique
- # cache names that we can refer to when we need to expire the cache.
- #
+ # That would result in a name such as "/topics/list/all_topics", avoiding conflicts with the action cache and with any fragments that use a
+ # different suffix. Note that the URL doesn't have to really exist or be callable - the url_for system is just used to generate unique
+ # cache names that we can refer to when we need to expire the cache.
+ #
# The expiration call for this example is:
- #
+ #
# expire_fragment(:controller => "topics", :action => "list", :action_suffix => "all_topics")
module Fragments
- # Given a key (as described in <tt>expire_fragment</tt>), returns a key suitable for use in reading,
+ # Given a key (as described in <tt>expire_fragment</tt>), returns a key suitable for use in reading,
# writing, or expiring a cached fragment. If the key is a hash, the generated key is the return
# value of url_for on that hash (without the protocol). All keys are prefixed with "views/" and uses
# ActiveSupport::Cache.expand_cache_key for the expansion.
@@ -50,7 +50,7 @@ module ActionController #:nodoc:
# Writes <tt>content</tt> to the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats)
def write_fragment(key, content, options = nil)
- return unless cache_configured?
+ return content unless cache_configured?
key = fragment_cache_key(key)
diff --git a/actionpack/lib/action_controller/cgi_ext/cookie.rb b/actionpack/lib/action_controller/cgi_ext/cookie.rb
index 009ddd1c64..9cd19bb12d 100644
--- a/actionpack/lib/action_controller/cgi_ext/cookie.rb
+++ b/actionpack/lib/action_controller/cgi_ext/cookie.rb
@@ -1,3 +1,5 @@
+require 'delegate'
+
CGI.module_eval { remove_const "Cookie" }
# TODO: document how this differs from stdlib CGI::Cookie
diff --git a/actionpack/lib/action_controller/cgi_process.rb b/actionpack/lib/action_controller/cgi_process.rb
index fabacd9b83..45b51a7488 100644
--- a/actionpack/lib/action_controller/cgi_process.rb
+++ b/actionpack/lib/action_controller/cgi_process.rb
@@ -1,5 +1,4 @@
require 'action_controller/cgi_ext'
-require 'action_controller/session/cookie_store'
module ActionController #:nodoc:
class Base
diff --git a/actionpack/lib/action_controller/components.rb b/actionpack/lib/action_controller/components.rb
deleted file mode 100644
index f446b91e7e..0000000000
--- a/actionpack/lib/action_controller/components.rb
+++ /dev/null
@@ -1,169 +0,0 @@
-module ActionController #:nodoc:
- # Components allow you to call other actions for their rendered response while executing another action. You can either delegate
- # the entire response rendering or you can mix a partial response in with your other content.
- #
- # class WeblogController < ActionController::Base
- # # Performs a method and then lets hello_world output its render
- # def delegate_action
- # do_other_stuff_before_hello_world
- # render_component :controller => "greeter", :action => "hello_world", :params => { :person => "david" }
- # end
- # end
- #
- # class GreeterController < ActionController::Base
- # def hello_world
- # render :text => "#{params[:person]} says, Hello World!"
- # end
- # end
- #
- # The same can be done in a view to do a partial rendering:
- #
- # Let's see a greeting:
- # <%= render_component :controller => "greeter", :action => "hello_world" %>
- #
- # It is also possible to specify the controller as a class constant, bypassing the inflector
- # code to compute the controller class at runtime:
- #
- # <%= render_component :controller => GreeterController, :action => "hello_world" %>
- #
- # == When to use components
- #
- # Components should be used with care. They're significantly slower than simply splitting reusable parts into partials and
- # conceptually more complicated. Don't use components as a way of separating concerns inside a single application. Instead,
- # reserve components to those rare cases where you truly have reusable view and controller elements that can be employed
- # across many applications at once.
- #
- # So to repeat: Components are a special-purpose approach that can often be replaced with better use of partials and filters.
- module Components
- def self.included(base) #:nodoc:
- base.class_eval do
- include InstanceMethods
- include ActiveSupport::Deprecation
- extend ClassMethods
- helper HelperMethods
-
- # If this controller was instantiated to process a component request,
- # +parent_controller+ points to the instantiator of this controller.
- attr_accessor :parent_controller
-
- alias_method_chain :process_cleanup, :components
- alias_method_chain :set_session_options, :components
- alias_method_chain :flash, :components
-
- alias_method :component_request?, :parent_controller
- end
- end
-
- module ClassMethods
- # Track parent controller to identify component requests
- def process_with_components(request, response, parent_controller = nil) #:nodoc:
- controller = new
- controller.parent_controller = parent_controller
- controller.process(request, response)
- end
- end
-
- module HelperMethods
- def render_component(options)
- @controller.__send__(:render_component_as_string, options)
- end
- end
-
- module InstanceMethods
- # Extracts the action_name from the request parameters and performs that action.
- def process_with_components(request, response, method = :perform_action, *arguments) #:nodoc:
- flash.discard if component_request?
- process_without_components(request, response, method, *arguments)
- end
-
- protected
- # Renders the component specified as the response for the current method
- def render_component(options) #:doc:
- component_logging(options) do
- render_for_text(component_response(options, true).body, response.headers["Status"])
- end
- end
- deprecate :render_component => "Please install render_component plugin from http://github.com/rails/render_component/tree/master"
-
- # Returns the component response as a string
- def render_component_as_string(options) #:doc:
- component_logging(options) do
- response = component_response(options, false)
-
- if redirected = response.redirected_to
- render_component_as_string(redirected)
- else
- response.body
- end
- end
- end
- deprecate :render_component_as_string => "Please install render_component plugin from http://github.com/rails/render_component/tree/master"
-
- def flash_with_components(refresh = false) #:nodoc:
- if !defined?(@_flash) || refresh
- @_flash =
- if defined?(@parent_controller)
- @parent_controller.flash
- else
- flash_without_components
- end
- end
- @_flash
- end
-
- private
- def component_response(options, reuse_response)
- klass = component_class(options)
- request = request_for_component(klass.controller_name, options)
- new_response = reuse_response ? response : response.dup
-
- klass.process_with_components(request, new_response, self)
- end
-
- # determine the controller class for the component request
- def component_class(options)
- if controller = options[:controller]
- controller.is_a?(Class) ? controller : "#{controller.camelize}Controller".constantize
- else
- self.class
- end
- end
-
- # Create a new request object based on the current request.
- # The new request inherits the session from the current request,
- # bypassing any session options set for the component controller's class
- def request_for_component(controller_name, options)
- new_request = request.dup
- new_request.session = request.session
-
- new_request.instance_variable_set(
- :@parameters,
- (options[:params] || {}).with_indifferent_access.update(
- "controller" => controller_name, "action" => options[:action], "id" => options[:id]
- )
- )
-
- new_request
- end
-
- def component_logging(options)
- if logger
- logger.info "Start rendering component (#{options.inspect}): "
- result = yield
- logger.info "\n\nEnd of component rendering"
- result
- else
- yield
- end
- end
-
- def set_session_options_with_components(request)
- set_session_options_without_components(request) unless component_request?
- end
-
- def process_cleanup_with_components
- process_cleanup_without_components unless component_request?
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb
index f3e173004a..47199af2b4 100644
--- a/actionpack/lib/action_controller/dispatcher.rb
+++ b/actionpack/lib/action_controller/dispatcher.rb
@@ -12,18 +12,8 @@ module ActionController
after_dispatch :cleanup_application
end
- # Common callbacks
- to_prepare :load_application_controller do
- begin
- require_dependency 'application' unless defined?(::ApplicationController)
- rescue LoadError => error
- raise unless error.message =~ /application\.rb/
- end
- end
-
if defined?(ActiveRecord)
after_dispatch :checkin_connections
- before_dispatch { ActiveRecord::Base.verify_active_connections! }
to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers }
end
@@ -71,7 +61,7 @@ module ActionController
private
def failsafe_response_body(status)
- error_path = "#{error_file_path}/#{status.to_s[0..3]}.html"
+ error_path = "#{error_file_path}/#{status.to_s[0..2]}.html"
if File.exist?(error_path)
File.read(error_path)
@@ -95,6 +85,9 @@ module ActionController
end
end
+ cattr_accessor :middleware
+ self.middleware = MiddlewareStack.new
+
cattr_accessor :error_file_path
self.error_file_path = Rails.public_path if defined?(Rails.public_path)
@@ -103,6 +96,7 @@ module ActionController
def initialize(output = $stdout, request = nil, response = nil)
@output, @request, @response = output, request, response
+ @app = @@middleware.build(lambda { |env| self._call(env) })
end
def dispatch_unlocked
@@ -137,6 +131,10 @@ module ActionController
end
def call(env)
+ @app.call(env)
+ end
+
+ def _call(env)
@request = RackRequest.new(env)
@response = RackResponse.new(@request)
dispatch
@@ -147,7 +145,6 @@ module ActionController
run_callbacks :prepare_dispatch
Routing::Routes.reload
- ActionController::Base.view_paths.reload!
ActionView::Helpers::AssetTagHelper::AssetTag::Cache.clear
end
@@ -186,7 +183,7 @@ module ActionController
def failsafe_rescue(exception)
self.class.failsafe_response(@output, '500 Internal Server Error', exception) do
- if @controller ||= defined?(::ApplicationController) ? ::ApplicationController : Base
+ if @controller ||= (::ApplicationController rescue Base)
@controller.process_with_exception(@request, @response, exception).out(@output)
else
raise exception
diff --git a/actionpack/lib/action_controller/flash.rb b/actionpack/lib/action_controller/flash.rb
index 0148fb5c04..62fa381a6f 100644
--- a/actionpack/lib/action_controller/flash.rb
+++ b/actionpack/lib/action_controller/flash.rb
@@ -165,7 +165,7 @@ module ActionController #:nodoc:
def assign_shortcuts_with_flash(request, response) #:nodoc:
assign_shortcuts_without_flash(request, response)
flash(:refresh)
- flash.sweep if @_session && !component_request?
+ flash.sweep if @_session
end
end
end
diff --git a/actionpack/lib/action_controller/helpers.rb b/actionpack/lib/action_controller/helpers.rb
index 9cffa07b26..402750c57d 100644
--- a/actionpack/lib/action_controller/helpers.rb
+++ b/actionpack/lib/action_controller/helpers.rb
@@ -1,13 +1,17 @@
+require 'active_support/dependencies'
+
# FIXME: helper { ... } is broken on Ruby 1.9
module ActionController #:nodoc:
module Helpers #:nodoc:
- HELPERS_DIR = (defined?(RAILS_ROOT) ? "#{RAILS_ROOT}/app/helpers" : "app/helpers")
-
def self.included(base)
# Initialize the base module to aggregate its helpers.
base.class_inheritable_accessor :master_helper_module
base.master_helper_module = Module.new
+ # Set the default directory for helpers
+ base.class_inheritable_accessor :helpers_dir
+ base.helpers_dir = (defined?(RAILS_ROOT) ? "#{RAILS_ROOT}/app/helpers" : "app/helpers")
+
# Extend base with class methods to declare helpers.
base.extend(ClassMethods)
@@ -88,8 +92,8 @@ module ActionController #:nodoc:
# When the argument is a module it will be included directly in the template class.
# helper FooHelper # => includes FooHelper
#
- # When the argument is the symbol <tt>:all</tt>, the controller will include all helpers from
- # <tt>app/helpers/**/*.rb</tt> under RAILS_ROOT.
+ # When the argument is the symbol <tt>:all</tt>, the controller will include all helpers beneath
+ # <tt>ActionController::Base.helpers_dir</tt> (defaults to <tt>app/helpers/**/*.rb</tt> under RAILS_ROOT).
# helper :all
#
# Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available
@@ -213,8 +217,8 @@ module ActionController #:nodoc:
# Extract helper names from files in app/helpers/**/*.rb
def all_application_helpers
- extract = /^#{Regexp.quote(HELPERS_DIR)}\/?(.*)_helper.rb$/
- Dir["#{HELPERS_DIR}/**/*_helper.rb"].map { |file| file.sub extract, '\1' }
+ extract = /^#{Regexp.quote(helpers_dir)}\/?(.*)_helper.rb$/
+ Dir["#{helpers_dir}/**/*_helper.rb"].map { |file| file.sub extract, '\1' }
end
end
end
diff --git a/actionpack/lib/action_controller/integration.rb b/actionpack/lib/action_controller/integration.rb
index fc473c269c..65e3eed678 100644
--- a/actionpack/lib/action_controller/integration.rb
+++ b/actionpack/lib/action_controller/integration.rb
@@ -1,9 +1,6 @@
-require 'active_support/test_case'
-require 'action_controller/dispatcher'
-require 'action_controller/test_process'
-
require 'stringio'
require 'uri'
+require 'active_support/test_case'
module ActionController
module Integration #:nodoc:
@@ -16,7 +13,7 @@ module ActionController
# rather than instantiating Integration::Session directly.
class Session
include Test::Unit::Assertions
- include ActionController::Assertions
+ include ActionController::TestCase::Assertions
include ActionController::TestProcess
# The integer HTTP status code of the last request.
diff --git a/actionpack/lib/action_controller/layout.rb b/actionpack/lib/action_controller/layout.rb
index 3631ce86af..54108df06d 100644
--- a/actionpack/lib/action_controller/layout.rb
+++ b/actionpack/lib/action_controller/layout.rb
@@ -175,13 +175,12 @@ module ActionController #:nodoc:
def default_layout(format) #:nodoc:
layout = read_inheritable_attribute(:layout)
return layout unless read_inheritable_attribute(:auto_layout)
- @default_layout ||= {}
- @default_layout[format] ||= default_layout_with_format(format, layout)
- @default_layout[format]
+ find_layout(layout, format)
end
- def layout_list #:nodoc:
- Array(view_paths).sum([]) { |path| Dir["#{path}/layouts/**/*"] }
+ def find_layout(layout, *formats) #:nodoc:
+ return layout if layout.respond_to?(:render)
+ view_paths.find_template(layout.to_s =~ /layouts\// ? layout : "layouts/#{layout}", *formats)
end
private
@@ -189,7 +188,7 @@ module ActionController #:nodoc:
inherited_without_layout(child)
unless child.name.blank?
layout_match = child.name.underscore.sub(/_controller$/, '').sub(/^controllers\//, '')
- child.layout(layout_match, {}, true) unless child.layout_list.grep(%r{layouts/#{layout_match}(\.[a-z][0-9a-z]*)+$}).empty?
+ child.layout(layout_match, {}, true) if child.find_layout(layout_match, :all)
end
end
@@ -200,15 +199,6 @@ module ActionController #:nodoc:
def normalize_conditions(conditions)
conditions.inject({}) {|hash, (key, value)| hash.merge(key => [value].flatten.map {|action| action.to_s})}
end
-
- def default_layout_with_format(format, layout)
- list = layout_list
- if list.grep(%r{layouts/#{layout}\.#{format}(\.[a-z][0-9a-z]*)+$}).empty?
- (!list.grep(%r{layouts/#{layout}\.([a-z][0-9a-z]*)+$}).empty? && format == :html) ? layout : nil
- else
- layout
- end
- end
end
# Returns the name of the active layout. If the layout was specified as a method reference (through a symbol), this method
@@ -217,20 +207,18 @@ module ActionController #:nodoc:
# weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard.
def active_layout(passed_layout = nil)
layout = passed_layout || self.class.default_layout(default_template_format)
+
active_layout = case layout
- when String then layout
when Symbol then __send__(layout)
when Proc then layout.call(self)
+ else layout
end
- # Explicitly passed layout names with slashes are looked up relative to the template root,
- # but auto-discovered layouts derived from a nested controller will contain a slash, though be relative
- # to the 'layouts' directory so we have to check the file system to infer which case the layout name came from.
if active_layout
- if active_layout.include?('/') && ! layout_directory?(active_layout)
- active_layout
+ if layout = self.class.find_layout(active_layout, @template.template_format)
+ layout
else
- "layouts/#{active_layout}"
+ raise ActionView::MissingTemplate.new(self.class.view_paths, active_layout)
end
end
end
@@ -271,12 +259,6 @@ module ActionController #:nodoc:
end
end
- def layout_directory?(layout_name)
- @template.__send__(:_pick_template, "#{File.join('layouts', layout_name)}.#{@template.template_format}") ? true : false
- rescue ActionView::MissingTemplate
- false
- end
-
def default_template_format
response.template.template_format
end
diff --git a/actionpack/lib/action_controller/middleware_stack.rb b/actionpack/lib/action_controller/middleware_stack.rb
new file mode 100644
index 0000000000..1864bed23a
--- /dev/null
+++ b/actionpack/lib/action_controller/middleware_stack.rb
@@ -0,0 +1,42 @@
+module ActionController
+ class MiddlewareStack < Array
+ class Middleware
+ attr_reader :klass, :args, :block
+
+ def initialize(klass, *args, &block)
+ @klass = klass.is_a?(Class) ? klass : klass.to_s.constantize
+ @args = args
+ @block = block
+ end
+
+ def ==(middleware)
+ case middleware
+ when Middleware
+ klass == middleware.klass
+ when Class
+ klass == middleware
+ else
+ klass == middleware.to_s.constantize
+ end
+ end
+
+ def inspect
+ str = @klass.to_s
+ @args.each { |arg| str += ", #{arg.inspect}" }
+ str
+ end
+
+ def build(app)
+ klass.new(app, *args, &block)
+ end
+ end
+
+ def use(*args, &block)
+ push(Middleware.new(*args, &block))
+ end
+
+ def build(app)
+ reverse.inject(app) { |a, e| e.build(a) }
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/mime_type.rb b/actionpack/lib/action_controller/mime_type.rb
index 26edca3b69..6923a13f3f 100644
--- a/actionpack/lib/action_controller/mime_type.rb
+++ b/actionpack/lib/action_controller/mime_type.rb
@@ -20,8 +20,20 @@ module Mime
# end
class Type
@@html_types = Set.new [:html, :all]
+ cattr_reader :html_types
+
+ # These are the content types which browsers can generate without using ajax, flash, etc
+ # i.e. following a link, getting an image or posting a form. CSRF protection
+ # only needs to protect against these types.
+ @@browser_generated_types = Set.new [:html, :url_encoded_form, :multipart_form, :text]
+ cattr_reader :browser_generated_types
+
+
@@unverifiable_types = Set.new [:text, :json, :csv, :xml, :rss, :atom, :yaml]
- cattr_reader :html_types, :unverifiable_types
+ def self.unverifiable_types
+ ActiveSupport::Deprecation.warn("unverifiable_types is deprecated and has no effect", caller)
+ @@unverifiable_types
+ end
# A simple helper class used in parsing the accept header
class AcceptItem #:nodoc:
@@ -165,15 +177,19 @@ module Mime
end
# Returns true if Action Pack should check requests using this Mime Type for possible request forgery. See
- # ActionController::RequestForgerProtection.
+ # ActionController::RequestForgeryProtection.
def verify_request?
- !@@unverifiable_types.include?(to_sym)
+ browser_generated?
end
def html?
@@html_types.include?(to_sym) || @string =~ /html/
end
+ def browser_generated?
+ @@browser_generated_types.include?(to_sym)
+ end
+
private
def method_missing(method, *args)
if method.to_s =~ /(\w+)\?$/
diff --git a/actionpack/lib/action_controller/performance_test.rb b/actionpack/lib/action_controller/performance_test.rb
index 85543fffae..d88180087d 100644
--- a/actionpack/lib/action_controller/performance_test.rb
+++ b/actionpack/lib/action_controller/performance_test.rb
@@ -1,4 +1,3 @@
-require 'action_controller/integration'
require 'active_support/testing/performance'
require 'active_support/testing/default'
diff --git a/actionpack/lib/action_controller/polymorphic_routes.rb b/actionpack/lib/action_controller/polymorphic_routes.rb
index cc228c4230..dce50c6c3b 100644
--- a/actionpack/lib/action_controller/polymorphic_routes.rb
+++ b/actionpack/lib/action_controller/polymorphic_routes.rb
@@ -36,12 +36,11 @@ module ActionController
#
# * <tt>edit_polymorphic_url</tt>, <tt>edit_polymorphic_path</tt>
# * <tt>new_polymorphic_url</tt>, <tt>new_polymorphic_path</tt>
- # * <tt>formatted_polymorphic_url</tt>, <tt>formatted_polymorphic_path</tt>
#
# Example usage:
#
# edit_polymorphic_path(@post) # => "/posts/1/edit"
- # formatted_polymorphic_path([@post, :pdf]) # => "/posts/1.pdf"
+ # polymorphic_path(@post, :format => :pdf) # => "/posts/1.pdf"
module PolymorphicRoutes
# Constructs a call to a named RESTful route for the given record and returns the
# resulting URL string. For example:
@@ -55,7 +54,7 @@ module ActionController
# ==== Options
#
# * <tt>:action</tt> - Specifies the action prefix for the named route:
- # <tt>:new</tt>, <tt>:edit</tt>, or <tt>:formatted</tt>. Default is no prefix.
+ # <tt>:new</tt> or <tt>:edit</tt>. Default is no prefix.
# * <tt>:routing_type</tt> - Allowed values are <tt>:path</tt> or <tt>:url</tt>.
# Default is <tt>:url</tt>.
#
@@ -73,13 +72,13 @@ module ActionController
#
def polymorphic_url(record_or_hash_or_array, options = {})
if record_or_hash_or_array.kind_of?(Array)
- record_or_hash_or_array = record_or_hash_or_array.dup
+ record_or_hash_or_array = record_or_hash_or_array.compact
+ record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1
end
record = extract_record(record_or_hash_or_array)
- format = extract_format(record_or_hash_or_array, options)
namespace = extract_namespace(record_or_hash_or_array)
-
+
args = case record_or_hash_or_array
when Hash; [ record_or_hash_or_array ]
when Array; record_or_hash_or_array.dup
@@ -99,11 +98,10 @@ module ActionController
end
args.delete_if {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}
- args << format if format
-
+
named_route = build_named_route_call(record_or_hash_or_array, namespace, inflection, options)
- url_options = options.except(:action, :routing_type, :format)
+ url_options = options.except(:action, :routing_type)
unless url_options.empty?
args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
end
@@ -118,7 +116,7 @@ module ActionController
polymorphic_url(record_or_hash_or_array, options)
end
- %w(edit new formatted).each do |action|
+ %w(edit new).each do |action|
module_eval <<-EOT, __FILE__, __LINE__
def #{action}_polymorphic_url(record_or_hash, options = {})
polymorphic_url(record_or_hash, options.merge(:action => "#{action}"))
@@ -130,9 +128,21 @@ module ActionController
EOT
end
+ def formatted_polymorphic_url(record_or_hash, options = {})
+ ActiveSupport::Deprecation.warn("formatted_polymorphic_url has been deprecated. Please pass :format to the polymorphic_url method instead", caller)
+ options[:format] = record_or_hash.pop if Array === record_or_hash
+ polymorphic_url(record_or_hash, options)
+ end
+
+ def formatted_polymorphic_path(record_or_hash, options = {})
+ ActiveSupport::Deprecation.warn("formatted_polymorphic_path has been deprecated. Please pass :format to the polymorphic_path method instead", caller)
+ options[:format] = record_or_hash.pop if record_or_hash === Array
+ polymorphic_url(record_or_hash, options.merge(:routing_type => :path))
+ end
+
private
def action_prefix(options)
- options[:action] ? "#{options[:action]}_" : options[:format] ? "formatted_" : ""
+ options[:action] ? "#{options[:action]}_" : ''
end
def routing_type(options)
@@ -170,17 +180,7 @@ module ActionController
else record_or_hash_or_array
end
end
-
- def extract_format(record_or_hash_or_array, options)
- if options[:action].to_s == "formatted" && record_or_hash_or_array.is_a?(Array)
- record_or_hash_or_array.pop
- elsif options[:format]
- options[:format]
- else
- nil
- end
- end
-
+
# Remove the first symbols from the array and return the url prefix
# implied by those symbols.
def extract_namespace(record_or_hash_or_array)
diff --git a/actionpack/lib/action_controller/rack_process.rb b/actionpack/lib/action_controller/rack_process.rb
index e8ea3704a8..58d7b53e31 100644
--- a/actionpack/lib/action_controller/rack_process.rb
+++ b/actionpack/lib/action_controller/rack_process.rb
@@ -1,5 +1,4 @@
require 'action_controller/cgi_ext'
-require 'action_controller/session/cookie_store'
module ActionController #:nodoc:
class RackRequest < AbstractRequest #:nodoc:
diff --git a/actionpack/lib/action_controller/request.rb b/actionpack/lib/action_controller/request.rb
index a6d4abf029..087fffe87d 100755
--- a/actionpack/lib/action_controller/request.rb
+++ b/actionpack/lib/action_controller/request.rb
@@ -13,7 +13,7 @@ module ActionController
ActiveSupport::Deprecation.warn(
"ActionController::AbstractRequest.relative_url_root= has been renamed." +
"You can now set it with config.action_controller.relative_url_root=", caller)
- ActionController::base.relative_url_root=relative_url_root
+ ActionController::Base.relative_url_root=relative_url_root
end
HTTP_METHODS = %w(get head put post delete options)
@@ -209,7 +209,7 @@ module ActionController
# delimited list in the case of multiple chained proxies; the last
# address which is not trusted is the originating IP.
def remote_ip
- remote_addr_list = @env['REMOTE_ADDR'] && @env['REMOTE_ADDR'].split(',').collect(&:strip)
+ remote_addr_list = @env['REMOTE_ADDR'] && @env['REMOTE_ADDR'].scan(/[^,\s]+/)
unless remote_addr_list.blank?
not_trusted_addrs = remote_addr_list.reject {|addr| addr =~ TRUSTED_PROXIES}
@@ -218,7 +218,7 @@ module ActionController
remote_ips = @env['HTTP_X_FORWARDED_FOR'] && @env['HTTP_X_FORWARDED_FOR'].split(',')
if @env.include? 'HTTP_CLIENT_IP'
- if remote_ips && !remote_ips.include?(@env['HTTP_CLIENT_IP'])
+ if ActionController::Base.ip_spoofing_check && remote_ips && !remote_ips.include?(@env['HTTP_CLIENT_IP'])
# We don't know which came from the proxy, and which from the user
raise ActionControllerError.new(<<EOM)
IP spoofing attack?!
@@ -369,11 +369,9 @@ EOM
# Returns the interpreted \path to requested resource after all the installation
# directory of this application was taken into account.
def path
- path = (uri = request_uri) ? uri.split('?').first.to_s : ''
-
- # Cut off the path to the installation directory if given
- path.sub!(%r/^#{ActionController::Base.relative_url_root}/, '')
- path || ''
+ path = request_uri.to_s[/\A[^\?]*/]
+ path.sub!(/\A#{ActionController::Base.relative_url_root}/, '')
+ path
end
memoize :path
diff --git a/actionpack/lib/action_controller/request_forgery_protection.rb b/actionpack/lib/action_controller/request_forgery_protection.rb
index 05a6d8bb79..f3e6288c26 100644
--- a/actionpack/lib/action_controller/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/request_forgery_protection.rb
@@ -5,8 +5,6 @@ module ActionController #:nodoc:
module RequestForgeryProtection
def self.included(base)
base.class_eval do
- class_inheritable_accessor :request_forgery_protection_options
- self.request_forgery_protection_options = {}
helper_method :form_authenticity_token
helper_method :protect_against_forgery?
end
@@ -14,7 +12,7 @@ module ActionController #:nodoc:
end
# Protecting controller actions from CSRF attacks by ensuring that all forms are coming from the current web application, not a
- # forged link from another site, is done by embedding a token based on the session (which an attacker wouldn't know) in all
+ # forged link from another site, is done by embedding a token based on a random string stored in the session (which an attacker wouldn't know) in all
# forms and Ajax requests generated by Rails and then verifying the authenticity of that token in the controller. Only
# HTML/JavaScript requests are checked, so this will not protect your XML API (presumably you'll have a different authentication
# scheme there anyway). Also, GET requests are not protected as these should be idempotent anyway.
@@ -57,12 +55,8 @@ module ActionController #:nodoc:
# Example:
#
# class FooController < ApplicationController
- # # uses the cookie session store (then you don't need a separate :secret)
# protect_from_forgery :except => :index
#
- # # uses one of the other session stores that uses a session_id value.
- # protect_from_forgery :secret => 'my-little-pony', :except => :index
- #
# # you can disable csrf protection on controller-by-controller basis:
# skip_before_filter :verify_authenticity_token
# end
@@ -70,13 +64,12 @@ module ActionController #:nodoc:
# Valid Options:
#
# * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call. Set which actions are verified.
- # * <tt>:secret</tt> - Custom salt used to generate the <tt>form_authenticity_token</tt>.
- # Leave this off if you are using the cookie session store.
- # * <tt>:digest</tt> - Message digest used for hashing. Defaults to 'SHA1'.
def protect_from_forgery(options = {})
self.request_forgery_protection_token ||= :authenticity_token
before_filter :verify_authenticity_token, :only => options.delete(:only), :except => options.delete(:except)
- request_forgery_protection_options.update(options)
+ if options[:secret] || options[:digest]
+ ActiveSupport::Deprecation.warn("protect_from_forgery only takes :only and :except options now. :digest and :secret have no effect", caller)
+ end
end
end
@@ -90,7 +83,7 @@ module ActionController #:nodoc:
#
# * is the format restricted? By default, only HTML and AJAX requests are checked.
# * is it a GET request? Gets should be safe and idempotent
- # * Does the form_authenticity_token match the given _token value from the params?
+ # * Does the form_authenticity_token match the given token value from the params?
def verified_request?
!protect_against_forgery? ||
request.method == :get ||
@@ -99,40 +92,15 @@ module ActionController #:nodoc:
end
def verifiable_request_format?
- request.content_type.nil? || request.content_type.verify_request?
+ !request.content_type.nil? && request.content_type.verify_request?
end
# Sets the token value for the current session. Pass a <tt>:secret</tt> option
# in +protect_from_forgery+ to add a custom salt to the hash.
def form_authenticity_token
- @form_authenticity_token ||= if !session.respond_to?(:session_id)
- raise InvalidAuthenticityToken, "Request Forgery Protection requires a valid session. Use #allow_forgery_protection to disable it, or use a valid session."
- elsif request_forgery_protection_options[:secret]
- authenticity_token_from_session_id
- elsif session.respond_to?(:dbman) && session.dbman.respond_to?(:generate_digest)
- authenticity_token_from_cookie_session
- else
- raise InvalidAuthenticityToken, "No :secret given to the #protect_from_forgery call. Set that or use a session store capable of generating its own keys (Cookie Session Store)."
- end
- end
-
- # Generates a unique digest using the session_id and the CSRF secret.
- def authenticity_token_from_session_id
- key = if request_forgery_protection_options[:secret].respond_to?(:call)
- request_forgery_protection_options[:secret].call(@session)
- else
- request_forgery_protection_options[:secret]
- end
- digest = request_forgery_protection_options[:digest] ||= 'SHA1'
- OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest), key.to_s, session.session_id.to_s)
- end
-
- # No secret was given, so assume this is a cookie session store.
- def authenticity_token_from_cookie_session
- session[:csrf_id] ||= CGI::Session.generate_unique_id
- session.dbman.generate_digest(session[:csrf_id])
+ session[:_csrf_token] ||= ActiveSupport::SecureRandom.base64(32)
end
-
+
def protect_against_forgery?
allow_forgery_protection && request_forgery_protection_token
end
diff --git a/actionpack/lib/action_controller/request_profiler.rb b/actionpack/lib/action_controller/request_profiler.rb
index a6471d0c08..70bb77e7ac 100644
--- a/actionpack/lib/action_controller/request_profiler.rb
+++ b/actionpack/lib/action_controller/request_profiler.rb
@@ -1,5 +1,4 @@
require 'optparse'
-require 'action_controller/integration'
module ActionController
class RequestProfiler
diff --git a/actionpack/lib/action_controller/rescue.rb b/actionpack/lib/action_controller/rescue.rb
index ec8e9b92d5..9c24c3def4 100644
--- a/actionpack/lib/action_controller/rescue.rb
+++ b/actionpack/lib/action_controller/rescue.rb
@@ -68,9 +68,8 @@ module ActionController #:nodoc:
logger.fatal(exception.to_s)
else
logger.fatal(
- "\n\n#{exception.class} (#{exception.message}):\n " +
- clean_backtrace(exception).join("\n ") +
- "\n\n"
+ "\n#{exception.class} (#{exception.message}):\n " +
+ clean_backtrace(exception).join("\n ") + "\n\n"
)
end
end
@@ -151,13 +150,8 @@ module ActionController #:nodoc:
end
def clean_backtrace(exception)
- if backtrace = exception.backtrace
- if defined?(RAILS_ROOT)
- backtrace.map { |line| line.sub RAILS_ROOT, '' }
- else
- backtrace
- end
- end
+ defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) ?
+ Rails.backtrace_cleaner.clean(exception.backtrace) : exception.backtrace
end
end
end
diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb
index 872b0dab3d..b6cfe2dd68 100644
--- a/actionpack/lib/action_controller/resources.rb
+++ b/actionpack/lib/action_controller/resources.rb
@@ -42,7 +42,11 @@ module ActionController
#
# Read more about REST at http://en.wikipedia.org/wiki/Representational_State_Transfer
module Resources
+ INHERITABLE_OPTIONS = :namespace, :shallow, :actions
+
class Resource #:nodoc:
+ DEFAULT_ACTIONS = :index, :create, :new, :edit, :show, :update, :destroy
+
attr_reader :collection_methods, :member_methods, :new_methods
attr_reader :path_prefix, :name_prefix, :path_segment
attr_reader :plural, :singular
@@ -57,6 +61,7 @@ module ActionController
arrange_actions
add_default_actions
+ set_allowed_actions
set_prefixes
end
@@ -113,6 +118,10 @@ module ActionController
@singular.to_s == @plural.to_s
end
+ def has_action?(action)
+ !DEFAULT_ACTIONS.include?(action) || @options[:actions].nil? || @options[:actions].include?(action)
+ end
+
protected
def arrange_actions
@collection_methods = arrange_actions_by_methods(options.delete(:collection))
@@ -125,6 +134,25 @@ module ActionController
add_default_action(new_methods, :get, :new)
end
+ def set_allowed_actions
+ only = @options.delete(:only)
+ except = @options.delete(:except)
+
+ if only && except
+ raise ArgumentError, 'Please supply either :only or :except, not both.'
+ elsif only == :all || except == :none
+ options[:actions] = DEFAULT_ACTIONS
+ elsif only == :none || except == :all
+ options[:actions] = []
+ elsif only
+ options[:actions] = DEFAULT_ACTIONS & Array(only).map(&:to_sym)
+ elsif except
+ options[:actions] = DEFAULT_ACTIONS - Array(except).map(&:to_sym)
+ else
+ # leave options[:actions] alone
+ end
+ end
+
def set_prefixes
@path_prefix = options.delete(:path_prefix)
@name_prefix = options.delete(:name_prefix)
@@ -353,6 +381,25 @@ module ActionController
#
# map.resources :users, :has_many => { :posts => :comments }, :shallow => true
#
+ # * <tt>:only</tt> and <tt>:except</tt> - Specify which of the seven default actions should be routed to.
+ #
+ # <tt>:only</tt> and <tt>:except</tt> may be set to <tt>:all</tt>, <tt>:none</tt>, an action name or a
+ # list of action names. By default, routes are generated for all seven actions.
+ #
+ # For example:
+ #
+ # map.resources :posts, :only => [:index, :show] do |post|
+ # post.resources :comments, :except => [:update, :destroy]
+ # end
+ # # --> GET /posts (maps to the PostsController#index action)
+ # # --> POST /posts (fails)
+ # # --> GET /posts/1 (maps to the PostsController#show action)
+ # # --> DELETE /posts/1 (fails)
+ # # --> POST /posts/1/comments (maps to the CommentsController#create action)
+ # # --> PUT /posts/1/comments/1 (fails)
+ #
+ # The <tt>:only</tt> and <tt>:except</tt> options are inherited by any nested resource(s).
+ #
# If <tt>map.resources</tt> is called with multiple resources, they all get the same options applied.
#
# Examples:
@@ -478,7 +525,7 @@ module ActionController
map_associations(resource, options)
if block_given?
- with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block)
+ with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
end
end
end
@@ -488,14 +535,14 @@ module ActionController
with_options :controller => resource.controller do |map|
map_collection_actions(map, resource)
- map_default_singleton_actions(map, resource)
map_new_actions(map, resource)
map_member_actions(map, resource)
+ map_default_singleton_actions(map, resource)
map_associations(resource, options)
if block_given?
- with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block)
+ with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
end
end
end
@@ -507,7 +554,7 @@ module ActionController
name_prefix = "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}"
Array(options[:has_one]).each do |association|
- resource(association, :path_prefix => path_prefix, :name_prefix => name_prefix, :namespace => options[:namespace], :shallow => options[:shallow])
+ resource(association, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => path_prefix, :name_prefix => name_prefix))
end
end
@@ -522,7 +569,7 @@ module ActionController
map_has_many_associations(resource, association, options)
end
when Symbol, String
- resources(associations, :path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], :has_many => options[:has_many])
+ resources(associations, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :has_many => options[:has_many]))
else
end
end
@@ -531,41 +578,39 @@ module ActionController
resource.collection_methods.each do |method, actions|
actions.each do |action|
[method].flatten.each do |m|
- action_options = action_options_for(action, resource, m)
- map_named_routes(map, "#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}", action_options)
+ map_resource_routes(map, resource, action, "#{resource.path}#{resource.action_separator}#{action}", "#{action}_#{resource.name_prefix}#{resource.plural}", m)
end
end
end
end
def map_default_collection_actions(map, resource)
- index_action_options = action_options_for("index", resource)
index_route_name = "#{resource.name_prefix}#{resource.plural}"
if resource.uncountable?
index_route_name << "_index"
end
- map_named_routes(map, index_route_name, resource.path, index_action_options)
-
- create_action_options = action_options_for("create", resource)
- map_unnamed_routes(map, resource.path, create_action_options)
+ map_resource_routes(map, resource, :index, resource.path, index_route_name)
+ map_resource_routes(map, resource, :create, resource.path, index_route_name)
end
def map_default_singleton_actions(map, resource)
- create_action_options = action_options_for("create", resource)
- map_unnamed_routes(map, resource.path, create_action_options)
+ map_resource_routes(map, resource, :create, resource.path, "#{resource.shallow_name_prefix}#{resource.singular}")
end
def map_new_actions(map, resource)
resource.new_methods.each do |method, actions|
actions.each do |action|
- action_options = action_options_for(action, resource, method)
- if action == :new
- map_named_routes(map, "new_#{resource.name_prefix}#{resource.singular}", resource.new_path, action_options)
- else
- map_named_routes(map, "#{action}_new_#{resource.name_prefix}#{resource.singular}", "#{resource.new_path}#{resource.action_separator}#{action}", action_options)
+ route_path = resource.new_path
+ route_name = "new_#{resource.name_prefix}#{resource.singular}"
+
+ unless action == :new
+ route_path = "#{route_path}#{resource.action_separator}#{action}"
+ route_name = "#{action}_#{route_name}"
end
+
+ map_resource_routes(map, resource, action, route_path, route_name, method)
end
end
end
@@ -574,34 +619,31 @@ module ActionController
resource.member_methods.each do |method, actions|
actions.each do |action|
[method].flatten.each do |m|
- action_options = action_options_for(action, resource, m)
-
action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash)
action_path ||= Base.resources_path_names[action] || action
- map_named_routes(map, "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action_path}", action_options)
+ map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m)
end
end
end
- show_action_options = action_options_for("show", resource)
- map_named_routes(map, "#{resource.shallow_name_prefix}#{resource.singular}", resource.member_path, show_action_options)
-
- update_action_options = action_options_for("update", resource)
- map_unnamed_routes(map, resource.member_path, update_action_options)
-
- destroy_action_options = action_options_for("destroy", resource)
- map_unnamed_routes(map, resource.member_path, destroy_action_options)
+ route_path = "#{resource.shallow_name_prefix}#{resource.singular}"
+ map_resource_routes(map, resource, :show, resource.member_path, route_path)
+ map_resource_routes(map, resource, :update, resource.member_path, route_path)
+ map_resource_routes(map, resource, :destroy, resource.member_path, route_path)
end
- def map_unnamed_routes(map, path_without_format, options)
- map.connect(path_without_format, options)
- map.connect("#{path_without_format}.:format", options)
- end
+ def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil)
+ if resource.has_action?(action)
+ action_options = action_options_for(action, resource, method)
+ formatted_route_path = "#{route_path}.:format"
- def map_named_routes(map, name, path_without_format, options)
- map.named_route(name, path_without_format, options)
- map.named_route("formatted_#{name}", "#{path_without_format}.:format", options)
+ if route_name && @set.named_routes[route_name.to_sym].nil?
+ map.named_route(route_name, formatted_route_path, action_options)
+ else
+ map.connect(formatted_route_path, action_options)
+ end
+ end
end
def add_conditions_for(conditions, method)
@@ -625,7 +667,3 @@ module ActionController
end
end
end
-
-class ActionController::Routing::RouteSet::Mapper
- include ActionController::Resources
-end
diff --git a/actionpack/lib/action_controller/routing.rb b/actionpack/lib/action_controller/routing.rb
index 8d51e823a6..efd474097e 100644
--- a/actionpack/lib/action_controller/routing.rb
+++ b/actionpack/lib/action_controller/routing.rb
@@ -1,6 +1,5 @@
require 'cgi'
require 'uri'
-require 'action_controller/polymorphic_routes'
require 'action_controller/routing/optimisations'
require 'action_controller/routing/routing_ext'
require 'action_controller/routing/route'
diff --git a/actionpack/lib/action_controller/routing/builder.rb b/actionpack/lib/action_controller/routing/builder.rb
index 7b888fa8d2..44d759444a 100644
--- a/actionpack/lib/action_controller/routing/builder.rb
+++ b/actionpack/lib/action_controller/routing/builder.rb
@@ -1,23 +1,16 @@
module ActionController
module Routing
class RouteBuilder #:nodoc:
- attr_accessor :separators, :optional_separators
+ attr_reader :separators, :optional_separators
+ attr_reader :separator_regexp, :nonseparator_regexp, :interval_regexp
def initialize
- self.separators = Routing::SEPARATORS
- self.optional_separators = %w( / )
- end
-
- def separator_pattern(inverted = false)
- "[#{'^' if inverted}#{Regexp.escape(separators.join)}]"
- end
-
- def interval_regexp
- Regexp.new "(.*?)(#{separators.source}|$)"
- end
+ @separators = Routing::SEPARATORS
+ @optional_separators = %w( / )
- def multiline_regexp?(expression)
- expression.options & Regexp::MULTILINE == Regexp::MULTILINE
+ @separator_regexp = /[#{Regexp.escape(separators.join)}]/
+ @nonseparator_regexp = /\A([^#{Regexp.escape(separators.join)}]+)/
+ @interval_regexp = /(.*?)(#{separator_regexp}|$)/
end
# Accepts a "route path" (a string defining a route), and returns the array
@@ -30,7 +23,7 @@ module ActionController
rest, segments = path, []
until rest.empty?
- segment, rest = segment_for rest
+ segment, rest = segment_for(rest)
segments << segment
end
segments
@@ -39,20 +32,22 @@ module ActionController
# A factory method that returns a new segment instance appropriate for the
# format of the given string.
def segment_for(string)
- segment = case string
- when /\A:(\w+)/
- key = $1.to_sym
- case key
- when :controller then ControllerSegment.new(key)
- else DynamicSegment.new key
- end
- when /\A\*(\w+)/ then PathSegment.new($1.to_sym, :optional => true)
- when /\A\?(.*?)\?/
- StaticSegment.new($1, :optional => true)
- when /\A(#{separator_pattern(:inverted)}+)/ then StaticSegment.new($1)
- when Regexp.new(separator_pattern) then
- DividerSegment.new($&, :optional => (optional_separators.include? $&))
- end
+ segment =
+ case string
+ when /\A\.(:format)?\//
+ OptionalFormatSegment.new
+ when /\A:(\w+)/
+ key = $1.to_sym
+ key == :controller ? ControllerSegment.new(key) : DynamicSegment.new(key)
+ when /\A\*(\w+)/
+ PathSegment.new($1.to_sym, :optional => true)
+ when /\A\?(.*?)\?/
+ StaticSegment.new($1, :optional => true)
+ when nonseparator_regexp
+ StaticSegment.new($1)
+ when separator_regexp
+ DividerSegment.new($&, :optional => optional_separators.include?($&))
+ end
[segment, $~.post_match]
end
@@ -98,7 +93,7 @@ module ActionController
if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
end
- if multiline_regexp?(requirement)
+ if requirement.multiline?
raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
end
segment.regexp = requirement
diff --git a/actionpack/lib/action_controller/routing/optimisations.rb b/actionpack/lib/action_controller/routing/optimisations.rb
index 0a87303bda..714cf97861 100644
--- a/actionpack/lib/action_controller/routing/optimisations.rb
+++ b/actionpack/lib/action_controller/routing/optimisations.rb
@@ -65,7 +65,7 @@ module ActionController
# rather than triggering the expensive logic in +url_for+.
class PositionalArguments < Optimiser
def guard_conditions
- number_of_arguments = route.segment_keys.size
+ number_of_arguments = route.required_segment_keys.size
# if they're using foo_url(:id=>2) it's one
# argument, but we don't want to generate /foos/id2
if number_of_arguments == 1
@@ -106,12 +106,8 @@ module ActionController
# argument
class PositionalArgumentsWithAdditionalParams < PositionalArguments
def guard_conditions
- [
- "args.size == #{route.segment_keys.size + 1}",
- "!args.last.has_key?(:anchor)",
- "!args.last.has_key?(:port)",
- "!args.last.has_key?(:host)"
- ]
+ ["args.size == #{route.segment_keys.size + 1}"] +
+ UrlRewriter::RESERVED_OPTIONS.collect{ |key| "!args.last.has_key?(:#{key})" }
end
# This case uses almost the same code as positional arguments,
diff --git a/actionpack/lib/action_controller/routing/recognition_optimisation.rb b/actionpack/lib/action_controller/routing/recognition_optimisation.rb
index 6c47ced6d1..3b98b16683 100644
--- a/actionpack/lib/action_controller/routing/recognition_optimisation.rb
+++ b/actionpack/lib/action_controller/routing/recognition_optimisation.rb
@@ -148,7 +148,7 @@ module ActionController
end
nil
end
- }, __FILE__, __LINE__
+ }, '(recognize_optimized)', 1
end
def clear_recognize_optimized!
diff --git a/actionpack/lib/action_controller/routing/route.rb b/actionpack/lib/action_controller/routing/route.rb
index 3b2cb28545..e2077edad8 100644
--- a/actionpack/lib/action_controller/routing/route.rb
+++ b/actionpack/lib/action_controller/routing/route.rb
@@ -35,6 +35,11 @@ module ActionController
segment.key if segment.respond_to? :key
end.compact
end
+
+ def required_segment_keys
+ required_segments = segments.select {|seg| (!seg.optional? && !seg.is_a?(DividerSegment)) || seg.is_a?(PathSegment) }
+ required_segments.collect { |seg| seg.key if seg.respond_to?(:key)}.compact
+ end
# Build a query string from the keys of the given hash. If +only_keys+
# is given (as an array), only the keys indicated will be used to build
@@ -122,6 +127,16 @@ module ActionController
super
end
+ def generate(options, hash, expire_on = {})
+ path, hash = generate_raw(options, hash, expire_on)
+ append_query_string(path, hash, extra_keys(options))
+ end
+
+ def generate_extras(options, hash, expire_on = {})
+ path, hash = generate_raw(options, hash, expire_on)
+ [path, extra_keys(options)]
+ end
+
private
def requirement_for(key)
return requirements[key] if requirements.key? key
@@ -150,11 +165,6 @@ module ActionController
# the query string. (Never use keys from the recalled request when building the
# query string.)
- method_decl = "def generate(#{args})\npath, hash = generate_raw(options, hash, expire_on)\nappend_query_string(path, hash, extra_keys(options))\nend"
- instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})"
-
- method_decl = "def generate_extras(#{args})\npath, hash = generate_raw(options, hash, expire_on)\n[path, extra_keys(options)]\nend"
- instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})"
raw_method
end
@@ -219,7 +229,7 @@ module ActionController
next_capture = 1
extraction = segments.collect do |segment|
x = segment.match_extraction(next_capture)
- next_capture += Regexp.new(segment.regexp_chunk).number_of_captures
+ next_capture += segment.number_of_captures
x
end
extraction.compact
diff --git a/actionpack/lib/action_controller/routing/route_set.rb b/actionpack/lib/action_controller/routing/route_set.rb
index ff448490e9..13646aef61 100644
--- a/actionpack/lib/action_controller/routing/route_set.rb
+++ b/actionpack/lib/action_controller/routing/route_set.rb
@@ -7,6 +7,8 @@ module ActionController
# Mapper instances have relatively few instance methods, in order to avoid
# clashes with named routes.
class Mapper #:doc:
+ include ActionController::Resources
+
def initialize(set) #:nodoc:
@set = set
end
@@ -136,9 +138,13 @@ module ActionController
end
end
+ def named_helper_module_eval(code, *args)
+ @module.module_eval(code, *args)
+ end
+
def define_hash_access(route, name, kind, options)
selector = hash_access_name(name, kind)
- @module.module_eval <<-end_eval # We use module_eval to avoid leaks
+ named_helper_module_eval <<-end_eval # We use module_eval to avoid leaks
def #{selector}(options = nil)
options ? #{options.inspect}.merge(options) : #{options.inspect}
end
@@ -166,8 +172,9 @@ module ActionController
#
# foo_url(bar, baz, bang, :sort_by => 'baz')
#
- @module.module_eval <<-end_eval # We use module_eval to avoid leaks
+ named_helper_module_eval <<-end_eval # We use module_eval to avoid leaks
def #{selector}(*args)
+
#{generate_optimisation_block(route, kind)}
opts = if args.empty? || Hash === args.first
@@ -182,6 +189,14 @@ module ActionController
end
url_for(#{hash_access_method}(opts))
+
+ end
+ #Add an alias to support the now deprecated formatted_* URL.
+ def formatted_#{selector}(*args)
+ ActiveSupport::Deprecation.warn(
+ "formatted_#{selector}() has been deprecated. please pass format to the standard" +
+ "#{selector}() method instead.", caller)
+ #{selector}(*args)
end
protected :#{selector}
end_eval
@@ -189,9 +204,11 @@ module ActionController
end
end
- attr_accessor :routes, :named_routes, :configuration_file
+ attr_accessor :routes, :named_routes, :configuration_files
def initialize
+ self.configuration_files = []
+
self.routes = []
self.named_routes = NamedRouteCollection.new
@@ -205,7 +222,6 @@ module ActionController
end
def draw
- clear!
yield Mapper.new(self)
install_helpers
end
@@ -229,8 +245,22 @@ module ActionController
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
+
def load!
- Routing.use_controllers! nil # Clear the controller cache so we may discover new ones
+ Routing.use_controllers!(nil) # Clear the controller cache so we may discover new ones
clear!
load_routes!
end
@@ -239,24 +269,39 @@ module ActionController
alias reload! load!
def reload
- if @routes_last_modified && configuration_file
- mtime = File.stat(configuration_file).mtime
- # if it hasn't been changed, then just return
- return if mtime == @routes_last_modified
- # if it has changed then record the new time and fall to the load! below
- @routes_last_modified = mtime
+ 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
end
+
load!
end
def load_routes!
- if configuration_file
- load configuration_file
- @routes_last_modified = File.stat(configuration_file).mtime
+ if configuration_files.any?
+ configuration_files.each { |config| load(config) }
+ @routes_last_modified = routes_changed_at
else
add_route ":controller/:action/:id"
end
end
+
+ def routes_changed_at
+ routes_changed_at = nil
+
+ 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 add_route(path, options = {})
route = builder.build(path, options)
@@ -358,7 +403,7 @@ module ActionController
end
# don't use the recalled keys when determining which routes to check
- routes = routes_by_controller[controller][action][options.keys.sort_by { |x| x.object_id }]
+ routes = routes_by_controller[controller][action][options.reject {|k,v| !v}.keys.sort_by { |x| x.object_id }]
routes.each do |route|
results = route.__send__(method, options, merged, expire_on)
diff --git a/actionpack/lib/action_controller/routing/routing_ext.rb b/actionpack/lib/action_controller/routing/routing_ext.rb
index 5f4ba90d0c..4a82b2af5f 100644
--- a/actionpack/lib/action_controller/routing/routing_ext.rb
+++ b/actionpack/lib/action_controller/routing/routing_ext.rb
@@ -27,6 +27,10 @@ class Regexp #:nodoc:
Regexp.new("|#{source}").match('').captures.length
end
+ def multiline?
+ options & MULTILINE == MULTILINE
+ end
+
class << self
def optionalize(pattern)
case unoptionalize(pattern)
diff --git a/actionpack/lib/action_controller/routing/segments.rb b/actionpack/lib/action_controller/routing/segments.rb
index e5f174ae2c..5dda3d4d00 100644
--- a/actionpack/lib/action_controller/routing/segments.rb
+++ b/actionpack/lib/action_controller/routing/segments.rb
@@ -13,6 +13,10 @@ module ActionController
@is_optional = false
end
+ def number_of_captures
+ Regexp.new(regexp_chunk).number_of_captures
+ end
+
def extraction_code
nil
end
@@ -84,6 +88,10 @@ module ActionController
optional? ? Regexp.optionalize(chunk) : chunk
end
+ def number_of_captures
+ 0
+ end
+
def build_pattern(pattern)
escaped = Regexp.escape(value)
if optional? && ! pattern.empty?
@@ -194,10 +202,16 @@ module ActionController
end
end
+ def number_of_captures
+ if regexp
+ regexp.number_of_captures + 1
+ else
+ 1
+ end
+ end
+
def build_pattern(pattern)
- chunk = regexp_chunk
- chunk = "(#{chunk})" if Regexp.new(chunk).number_of_captures == 0
- pattern = "#{chunk}#{pattern}"
+ pattern = "#{regexp_chunk}#{pattern}"
optional? ? Regexp.optionalize(pattern) : pattern
end
@@ -230,6 +244,10 @@ module ActionController
"(?i-:(#{(regexp || Regexp.union(*possible_names)).source}))"
end
+ def number_of_captures
+ 1
+ end
+
# Don't URI.escape the controller name since it may contain slashes.
def interpolation_chunk(value_code = local_name)
"\#{#{value_code}.to_s}"
@@ -275,6 +293,10 @@ module ActionController
regexp || "(.*)"
end
+ def number_of_captures
+ regexp ? regexp.number_of_captures : 1
+ end
+
def optionality_implied?
true
end
@@ -286,5 +308,36 @@ module ActionController
end
end
end
+
+ # The OptionalFormatSegment allows for any resource route to have an optional
+ # :format, which decreases the amount of routes created by 50%.
+ class OptionalFormatSegment < DynamicSegment
+
+ def initialize(key = nil, options = {})
+ super(:format, {:optional => true}.merge(options))
+ end
+
+ def interpolation_chunk
+ "." + super
+ end
+
+ def regexp_chunk
+ '(\.[^/?\.]+)?'
+ end
+
+ def to_s
+ '(.:format)?'
+ end
+
+ #the value should not include the period (.)
+ def match_extraction(next_capture)
+ %[
+ if (m = match[#{next_capture}])
+ params[:#{key}] = URI.unescape(m.from(1))
+ end
+ ]
+ end
+ end
+
end
end
diff --git a/actionpack/lib/action_controller/session/cookie_store.rb b/actionpack/lib/action_controller/session/cookie_store.rb
index f2fb200950..ea0ea4f841 100644
--- a/actionpack/lib/action_controller/session/cookie_store.rb
+++ b/actionpack/lib/action_controller/session/cookie_store.rb
@@ -1,6 +1,5 @@
require 'cgi'
require 'cgi/session'
-require 'openssl' # to generate the HMAC message digest
# This cookie-based session store is the Rails default. Sessions typically
# contain at most a user_id and flash message; both fit within the 4K cookie
@@ -121,32 +120,20 @@ class CGI::Session::CookieStore
write_cookie('value' => nil, 'expires' => 1.year.ago)
end
- # Generate the HMAC keyed message digest. Uses SHA1 by default.
- def generate_digest(data)
- key = @secret.respond_to?(:call) ? @secret.call(@session) : @secret
- OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(@digest), key, data)
- end
-
private
# Marshal a session hash into safe cookie data. Include an integrity hash.
def marshal(session)
- data = ActiveSupport::Base64.encode64s(Marshal.dump(session))
- "#{data}--#{generate_digest(data)}"
+ verifier.generate(session)
end
# Unmarshal cookie data to a hash and verify its integrity.
def unmarshal(cookie)
if cookie
- data, digest = cookie.split('--')
-
- # Do two checks to transparently support old double-escaped data.
- unless digest == generate_digest(data) || digest == generate_digest(data = CGI.unescape(data))
- delete
- raise TamperedWithCookie
- end
-
- Marshal.load(ActiveSupport::Base64.decode64(data))
+ verifier.verify(cookie)
end
+ rescue ActiveSupport::MessageVerifier::InvalidSignature
+ delete
+ raise TamperedWithCookie
end
# Read the session data cookie.
@@ -164,4 +151,13 @@ class CGI::Session::CookieStore
def clear_old_cookie_value
@session.cgi.cookies[@cookie_options['name']].clear
end
+
+ def verifier
+ if @secret.respond_to?(:call)
+ key = @secret.call
+ else
+ key = @secret
+ end
+ ActiveSupport::MessageVerifier.new(key, @digest)
+ end
end
diff --git a/actionpack/lib/action_controller/session_management.rb b/actionpack/lib/action_controller/session_management.rb
index fd3d94ed97..60a9aec39c 100644
--- a/actionpack/lib/action_controller/session_management.rb
+++ b/actionpack/lib/action_controller/session_management.rb
@@ -1,10 +1,3 @@
-require 'action_controller/session/cookie_store'
-require 'action_controller/session/drb_store'
-require 'action_controller/session/mem_cache_store'
-if Object.const_defined?(:ActiveRecord)
- require 'action_controller/session/active_record_store'
-end
-
module ActionController #:nodoc:
module SessionManagement #:nodoc:
def self.included(base)
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 4fc60f0697..79a8e1364d 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -1,20 +1,6 @@
require 'active_support/test_case'
module ActionController
- class NonInferrableControllerError < ActionControllerError
- def initialize(name)
- @name = name
- super "Unable to determine the controller to test from #{name}. " +
- "You'll need to specify it using 'tests YourController' in your " +
- "test case definition. This could mean that #{inferred_controller_name} does not exist " +
- "or it contains syntax errors"
- end
-
- def inferred_controller_name
- @name.sub(/Test$/, '')
- end
- end
-
# Superclass for ActionController functional tests. Functional tests allow you to
# test a single controller action per test method. This should not be confused with
# integration tests (see ActionController::IntegrationTest), which are more like
@@ -74,7 +60,66 @@ module ActionController
# class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
# tests WidgetController
# end
+ #
+ # == Testing controller internals
+ #
+ # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
+ # can be used against. These collections are:
+ #
+ # * assigns: Instance variables assigned in the action that are available for the view.
+ # * session: Objects being saved in the session.
+ # * flash: The flash objects currently in the session.
+ # * cookies: Cookies being sent to the user on this request.
+ #
+ # These collections can be used just like any other hash:
+ #
+ # assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
+ # assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
+ # assert flash.empty? # makes sure that there's nothing in the flash
+ #
+ # For historic reasons, the assigns hash uses string-based keys. So assigns[:person] won't work, but assigns["person"] will. To
+ # appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
+ # So assigns(:person) will work just like assigns["person"], but again, assigns[:person] will not work.
+ #
+ # On top of the collections, you have the complete url that a given action redirected to available in redirect_to_url.
+ #
+ # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
+ # action call which can then be asserted against.
+ #
+ # == Manipulating the request collections
+ #
+ # The collections described above link to the response, so you can test if what the actions were expected to do happened. But
+ # sometimes you also want to manipulate these collections in the incoming request. This is really only relevant for sessions
+ # and cookies, though. For sessions, you just do:
+ #
+ # @request.session[:key] = "value"
+ #
+ # For cookies, you need to manually create the cookie, like this:
+ #
+ # @request.cookies["key"] = CGI::Cookie.new("key", "value")
+ #
+ # == Testing named routes
+ #
+ # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
+ # Example:
+ #
+ # assert_redirected_to page_url(:title => 'foo')
class TestCase < ActiveSupport::TestCase
+ module Assertions
+ %w(response selector tag dom routing model).each do |kind|
+ include ActionController::Assertions.const_get("#{kind.camelize}Assertions")
+ end
+
+ def clean_backtrace(&block)
+ yield
+ rescue ActiveSupport::TestCase::Assertion => error
+ framework_path = Regexp.new(File.expand_path("#{File.dirname(__FILE__)}/assertions"))
+ error.backtrace.reject! { |line| File.expand_path(line) =~ framework_path }
+ raise
+ end
+ end
+ include Assertions
+
# When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline
# (bystepping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular
# rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else
@@ -107,7 +152,7 @@ module ActionController
end
def controller_class=(new_class)
- prepare_controller_class(new_class)
+ prepare_controller_class(new_class) if new_class
write_inheritable_attribute(:controller_class, new_class)
end
@@ -122,7 +167,7 @@ module ActionController
def determine_default_controller_class(name)
name.sub(/Test$/, '').constantize
rescue NameError
- raise NonInferrableControllerError.new(name)
+ nil
end
def prepare_controller_class(new_class)
@@ -131,17 +176,23 @@ module ActionController
end
def setup_controller_request_and_response
- @controller = self.class.controller_class.new
- @controller.request = @request = TestRequest.new
+ @request = TestRequest.new
@response = TestResponse.new
- @controller.params = {}
- @controller.send(:initialize_current_url)
+ if klass = self.class.controller_class
+ @controller ||= klass.new rescue nil
+ end
+
+ if @controller
+ @controller.request = @request
+ @controller.params = {}
+ @controller.send(:initialize_current_url)
+ end
end
# Cause the action to be rescued according to the regular rules for rescue_action when the visitor is not local
def rescue_action_in_public!
@request.remote_addr = '208.77.188.166' # example.com
end
- end
+ end
end
diff --git a/actionpack/lib/action_controller/test_process.rb b/actionpack/lib/action_controller/test_process.rb
index 7a31f0e8d5..cd3914f011 100644
--- a/actionpack/lib/action_controller/test_process.rb
+++ b/actionpack/lib/action_controller/test_process.rb
@@ -1,4 +1,3 @@
-require 'action_controller/assertions'
require 'action_controller/test_case'
module ActionController #:nodoc:
@@ -201,6 +200,11 @@ module ActionController #:nodoc:
alias_method :server_error?, :error?
+ # Was there a client client?
+ def client_error?
+ (400..499).include?(response_code)
+ end
+
# Returns the redirection location or nil
def redirect_url
headers['Location']
@@ -284,7 +288,7 @@ module ActionController #:nodoc:
# See AbstractResponse for more information on controller response objects.
class TestResponse < AbstractResponse
include TestResponseBehavior
-
+
def recycle!
headers.delete('ETag')
headers.delete('Last-Modified')
@@ -333,10 +337,10 @@ module ActionController #:nodoc:
# a file upload.
#
# Usage example, within a functional test:
- # post :change_avatar, :avatar => ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + '/files/spongebob.png', 'image/png')
+ # 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(Test::Unit::TestCase.fixture_path + '/files/spongebob.png', 'image/png', :binary)
+ # post :change_avatar, :avatar => ActionController::TestUploadedFile.new(ActionController::TestCase.fixture_path + '/files/spongebob.png', 'image/png', :binary)
require 'tempfile'
class TestUploadedFile
# The filename, *not* including the path, of the "uploaded" file
@@ -395,6 +399,7 @@ module ActionController #:nodoc:
@html_document = nil
@request.env['REQUEST_METHOD'] ||= "GET"
+
@request.action = action.to_s
parameters ||= {}
@@ -463,15 +468,15 @@ module ActionController #:nodoc:
html_document.find_all(conditions)
end
- def method_missing(selector, *args)
- if ActionController::Routing::Routes.named_routes.helpers.include?(selector)
- @controller.send(selector, *args)
+ 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(Test::Unit::TestCase.fixture_path + path, type)</tt>:
+ # 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')
#
@@ -480,11 +485,7 @@ module ActionController #:nodoc:
#
# post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary)
def fixture_file_upload(path, mime_type = nil, binary = false)
- ActionController::TestUploadedFile.new(
- Test::Unit::TestCase.respond_to?(:fixture_path) ? Test::Unit::TestCase.fixture_path + path : path,
- mime_type,
- binary
- )
+ ActionController::TestUploadedFile.new("#{ActionController::TestCase.try(:fixture_path)}#{path}", mime_type, binary)
end
# A helper to make it easier to test different route configurations.
diff --git a/actionpack/lib/action_controller/vendor/html-scanner.rb b/actionpack/lib/action_controller/vendor/html-scanner.rb
new file mode 100644
index 0000000000..f622d195ee
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/html-scanner.rb
@@ -0,0 +1,16 @@
+$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'
+end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
index 12c8405101..ae20f9947c 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
@@ -160,7 +160,7 @@ module HTML
if !options[:attributes].include?(attr_name) || contains_bad_protocols?(attr_name, value)
node.attributes.delete(attr_name)
else
- node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(value)
+ node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(CGI::unescapeHTML(value))
end
end
end
diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb
index 288b62778e..f20e44a7d5 100644
--- a/actionpack/lib/action_pack/version.rb
+++ b/actionpack/lib/action_pack/version.rb
@@ -1,7 +1,7 @@
module ActionPack #:nodoc:
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 2
+ MINOR = 3
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index 7cd9b633ac..210a5f1a93 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -31,23 +31,27 @@ rescue LoadError
end
end
-require 'action_view/template_handlers'
-require 'action_view/renderable'
-require 'action_view/renderable_partial'
-
-require 'action_view/template'
-require 'action_view/inline_template'
-require 'action_view/paths'
-
-require 'action_view/base'
-require 'action_view/partials'
-require 'action_view/template_error'
-
-I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en-US.yml"
+module ActionView
+ def self.load_all!
+ [Base, InlineTemplate, TemplateError]
+ end
-require 'action_view/helpers'
+ autoload :Base, 'action_view/base'
+ autoload :Helpers, 'action_view/helpers'
+ autoload :InlineTemplate, 'action_view/inline_template'
+ autoload :Partials, 'action_view/partials'
+ autoload :PathSet, 'action_view/paths'
+ autoload :Renderable, 'action_view/renderable'
+ autoload :RenderablePartial, 'action_view/renderable_partial'
+ autoload :Template, 'action_view/template'
+ autoload :TemplateError, 'action_view/template_error'
+ autoload :TemplateHandler, 'action_view/template_handler'
+ autoload :TemplateHandlers, 'action_view/template_handlers'
+ autoload :Helpers, 'action_view/helpers'
+end
-ActionView::Base.class_eval do
- include ActionView::Partials
- include ActionView::Helpers
+class ERB
+ autoload :Util, 'action_view/erb/util'
end
+
+I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 945246a39a..da1f283deb 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -157,7 +157,7 @@ module ActionView #:nodoc:
#
# See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.
class Base
- include ERB::Util
+ include Helpers, Partials, ::ERB::Util
extend ActiveSupport::Memoizable
attr_accessor :base_path, :assigns, :template_extension
@@ -234,16 +234,21 @@ module ActionView #:nodoc:
@view_paths = self.class.process_view_paths(paths)
end
- # Renders the template present at <tt>template_path</tt> (relative to the view_paths array).
- # The hash in <tt>local_assigns</tt> is made available as local variables.
+ # Returns the result of a render that's dictated by the options hash. The primary options are:
+ #
+ # * <tt>:partial</tt> - See ActionView::Partials.
+ # * <tt>:update</tt> - Calls update_page with the block given.
+ # * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
+ # * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
+ # * <tt>:text</tt> - Renders the text passed in out.
+ #
+ # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
+ # as the locals hash.
def render(options = {}, local_assigns = {}, &block) #:nodoc:
local_assigns ||= {}
- if options.is_a?(String)
- render(:file => options, :locals => local_assigns)
- elsif options == :update
- update_page(&block)
- elsif options.is_a?(Hash)
+ case options
+ when Hash
options = options.reverse_merge(:locals => {})
if options[:layout]
_render_with_layout(options, local_assigns, &block)
@@ -256,6 +261,10 @@ module ActionView #:nodoc:
elsif options[:text]
options[:text]
end
+ when :update
+ update_page(&block)
+ else
+ render_partial(:partial => options, :locals => local_assigns)
end
end
@@ -313,11 +322,10 @@ module ActionView #:nodoc:
end
# OPTIMIZE: Checks to lookup template in view path
- if template = self.view_paths["#{template_file_name}.#{template_format}"]
- template
- elsif template = self.view_paths[template_file_name]
+ if template = self.view_paths.find_template(template_file_name, template_format)
template
- elsif @_render_stack.first && template = self.view_paths["#{template_file_name}.#{@_render_stack.first.format_and_extension}"]
+ elsif (first_render = @_render_stack.first) && first_render.respond_to?(:format_and_extension) &&
+ (template = self.view_paths["#{template_file_name}.#{first_render.format_and_extension}"])
template
elsif template_format == :js && template = self.view_paths["#{template_file_name}.html"]
@template_format = :html
diff --git a/actionpack/lib/action_view/erb/util.rb b/actionpack/lib/action_view/erb/util.rb
new file mode 100644
index 0000000000..3c77c5ce76
--- /dev/null
+++ b/actionpack/lib/action_view/erb/util.rb
@@ -0,0 +1,38 @@
+require 'erb'
+
+class ERB
+ module Util
+ HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' }
+ JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }
+
+ # A utility method for escaping HTML tag characters.
+ # This method is also aliased as <tt>h</tt>.
+ #
+ # In your ERb templates, use this method to escape any unsafe content. For example:
+ # <%=h @person.name %>
+ #
+ # ==== Example:
+ # puts html_escape("is a > 0 & a < 10?")
+ # # => is a &gt; 0 &amp; a &lt; 10?
+ def html_escape(s)
+ s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
+ end
+
+ # A utility method for escaping HTML entities in JSON strings.
+ # This method is also aliased as <tt>j</tt>.
+ #
+ # In your ERb templates, use this method to escape any HTML entities:
+ # <%=j @person.to_json %>
+ #
+ # ==== Example:
+ # puts json_escape("is a > 0 & a < 10?")
+ # # => is a \u003E 0 \u0026 a \u003C 10?
+ def json_escape(s)
+ s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] }
+ end
+
+ alias j json_escape
+ module_function :j
+ module_function :json_escape
+ end
+end
diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb
index ff97df204c..693ab7c2e0 100644
--- a/actionpack/lib/action_view/helpers.rb
+++ b/actionpack/lib/action_view/helpers.rb
@@ -1,10 +1,28 @@
-Dir.entries(File.expand_path("#{File.dirname(__FILE__)}/helpers")).sort.each do |file|
- next unless file =~ /^([a-z][a-z_]*_helper).rb$/
- require "action_view/helpers/#{$1}"
-end
-
module ActionView #:nodoc:
module Helpers #:nodoc:
+ autoload :ActiveRecordHelper, 'action_view/helpers/active_record_helper'
+ autoload :AssetTagHelper, 'action_view/helpers/asset_tag_helper'
+ autoload :AtomFeedHelper, 'action_view/helpers/atom_feed_helper'
+ autoload :BenchmarkHelper, 'action_view/helpers/benchmark_helper'
+ autoload :CacheHelper, 'action_view/helpers/cache_helper'
+ autoload :CaptureHelper, 'action_view/helpers/capture_helper'
+ autoload :DateHelper, 'action_view/helpers/date_helper'
+ autoload :DebugHelper, 'action_view/helpers/debug_helper'
+ autoload :FormHelper, 'action_view/helpers/form_helper'
+ autoload :FormOptionsHelper, 'action_view/helpers/form_options_helper'
+ autoload :FormTagHelper, 'action_view/helpers/form_tag_helper'
+ autoload :JavascriptHelper, 'action_view/helpers/javascript_helper'
+ autoload :NumberHelper, 'action_view/helpers/number_helper'
+ autoload :PrototypeHelper, 'action_view/helpers/prototype_helper'
+ autoload :RecordIdentificationHelper, 'action_view/helpers/record_identification_helper'
+ autoload :RecordTagHelper, 'action_view/helpers/record_tag_helper'
+ autoload :SanitizeHelper, 'action_view/helpers/sanitize_helper'
+ autoload :ScriptaculousHelper, 'action_view/helpers/scriptaculous_helper'
+ autoload :TagHelper, 'action_view/helpers/tag_helper'
+ autoload :TextHelper, 'action_view/helpers/text_helper'
+ autoload :TranslationHelper, 'action_view/helpers/translation_helper'
+ autoload :UrlHelper, 'action_view/helpers/url_helper'
+
def self.included(base)
base.extend(ClassMethods)
end
@@ -24,6 +42,7 @@ module ActionView #:nodoc:
include FormHelper
include FormOptionsHelper
include FormTagHelper
+ include JavaScriptHelper
include NumberHelper
include PrototypeHelper
include RecordIdentificationHelper
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index 8bbe74b7ef..0633d5414e 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -80,6 +80,12 @@ module ActionView
# end
# }
#
+ # You can also implement a custom asset host object that responds to the call method and tasks one or two parameters just like the proc.
+ #
+ # config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
+ # "http://asset%d.example.com", "https://asset1.example.com"
+ # )
+ #
# === Using asset timestamps
#
# By default, Rails will append all asset paths with that asset's timestamp. This allows you to set a cache-expiration date for the
@@ -151,7 +157,7 @@ module ActionView
# javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr.js
# javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
def javascript_path(source)
- JavaScriptTag.create(self, @controller, source).public_path
+ JavaScriptTag.new(self, @controller, source).public_path
end
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
@@ -314,7 +320,7 @@ module ActionView
# stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style.css
# stylesheet_path "http://www.railsapplication.com/css/style.js" # => http://www.railsapplication.com/css/style.css
def stylesheet_path(source)
- StylesheetTag.create(self, @controller, source).public_path
+ StylesheetTag.new(self, @controller, source).public_path
end
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
@@ -359,6 +365,7 @@ module ActionView
# compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching
# is set to true (which is the case by default for the Rails production environment, but not for the development
# environment). Examples:
+
#
# ==== Examples
# stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false =>
@@ -411,7 +418,7 @@ module ActionView
# image_path("/icons/edit.png") # => /icons/edit.png
# image_path("http://www.railsapplication.com/img/edit.png") # => http://www.railsapplication.com/img/edit.png
def image_path(source)
- ImageTag.create(self, @controller, source).public_path
+ ImageTag.new(self, @controller, source).public_path
end
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
@@ -527,20 +534,6 @@ module ActionView
Cache = {}
CacheGuard = Mutex.new
- def self.create(template, controller, source, include_host = true)
- CacheGuard.synchronize do
- key = if controller.respond_to?(:request)
- [self, controller.request.protocol,
- ActionController::Base.asset_host,
- ActionController::Base.relative_url_root,
- source, include_host]
- else
- [self, ActionController::Base.asset_host, source, include_host]
- end
- Cache[key] ||= new(template, controller, source, include_host).freeze
- end
- end
-
ProtocolRegexp = %r{^[-a-z]+://}.freeze
def initialize(template, controller, source, include_host = true)
@@ -551,8 +544,16 @@ module ActionView
@controller = controller
@source = source
@include_host = include_host
+ @cache_key = if controller.respond_to?(:request)
+ [self.class.name,controller.request.protocol,
+ ActionController::Base.asset_host,
+ ActionController::Base.relative_url_root,
+ source, include_host]
+ else
+ [self.class.name,ActionController::Base.asset_host, source, include_host]
+ end
end
-
+
def public_path
compute_public_path(@source)
end
@@ -573,7 +574,7 @@ module ActionView
private
def request
- @controller.request
+ request? && @controller.request
end
def request?
@@ -585,20 +586,32 @@ module ActionView
# roots. Rewrite the asset path for cache-busting asset ids. Include
# asset host, if configured, with the correct request protocol.
def compute_public_path(source)
- source += ".#{extension}" if missing_extension?(source)
- unless source =~ ProtocolRegexp
- source = "/#{directory}/#{source}" unless source[0] == ?/
- source = rewrite_asset_path(source)
- source = prepend_relative_url_root(source)
+ if source =~ ProtocolRegexp
+ source += ".#{extension}" if missing_extension?(source)
+ source = prepend_asset_host(source)
+ source
+ else
+ CacheGuard.synchronize do
+ Cache[@cache_key + [source]] ||= begin
+ source += ".#{extension}" if missing_extension?(source) || file_exists_with_extension?(source)
+ source = "/#{directory}/#{source}" unless source[0] == ?/
+ source = rewrite_asset_path(source)
+ source = prepend_relative_url_root(source)
+ source = prepend_asset_host(source)
+ source
+ end
+ end
end
- source = prepend_asset_host(source)
- source
end
-
+
def missing_extension?(source)
- extension && (File.extname(source).blank? || File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}")))
+ extension && File.extname(source).blank?
end
-
+
+ def file_exists_with_extension?(source)
+ extension && File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}"))
+ end
+
def prepend_relative_url_root(source)
relative_url_root = ActionController::Base.relative_url_root
if request? && @include_host && source !~ %r{^#{relative_url_root}/}
@@ -623,11 +636,12 @@ module ActionView
# Pick an asset host for this source. Returns +nil+ if no host is set,
# the host if no wildcard is set, the host interpolated with the
# numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
- # or the value returned from invoking the proc if it's a proc.
+ # or the value returned from invoking the proc if it's a proc or the value from
+ # invoking call if it's an object responding to call.
def compute_asset_host(source)
if host = ActionController::Base.asset_host
- if host.is_a?(Proc)
- case host.arity
+ if host.is_a?(Proc) || host.respond_to?(:call)
+ case host.is_a?(Proc) ? host.arity : host.method(:call).arity
when 2
host.call(source, request)
else
@@ -735,7 +749,7 @@ module ActionView
end
def tag_sources
- expand_sources.collect { |source| tag_class.create(@template, @controller, source, false) }
+ expand_sources.collect { |source| tag_class.new(@template, @controller, source, false) }
end
def joined_contents
diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
index ccb7df212a..cd25684940 100644
--- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb
+++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
@@ -1,3 +1,5 @@
+require 'set'
+
# Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERb or any other
# template languages).
module ActionView
@@ -121,6 +123,8 @@ module ActionView
end
class AtomBuilder
+ XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set
+
def initialize(xml)
@xml = xml
end
@@ -140,14 +144,15 @@ module ActionView
@xml.__send__(method, *arguments, &block)
end
end
-
+
# True if the method name matches one of the five elements defined
# in the Atom spec as potentially containing XHTML content and
# if :type => 'xhtml' is, in fact, specified.
def xhtml_block?(method, arguments)
- %w( content rights title subtitle summary ).include?(method.to_s) &&
- arguments.last.respond_to?(:[]) &&
- arguments.last[:type].to_s == 'xhtml'
+ if XHTML_TAG_NAMES.include?(method.to_s)
+ last = arguments.last
+ last.is_a?(Hash) && last[:type].to_s == 'xhtml'
+ end
end
end
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index d4d2c6ef53..22108dd99d 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -131,7 +131,7 @@ module ActionView
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> do
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
# select will not be shown (like when you set <tt>:discard_xxx => true</tt>. Defaults to the order defined in
- # the respective locale (e.g. [:year, :month, :day] in the en-US locale that ships with Rails).
+ # the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
# dates.
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
@@ -539,7 +539,7 @@ module ActionView
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
- if @options[:discard_day] && !@options[:discard_month]
+ if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
@@ -567,7 +567,7 @@ module ActionView
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
- if @options[:discard_day] && !@options[:discard_month]
+ if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
end
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 7492348c50..4646bc118b 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -78,7 +78,7 @@ module ActionView
# # <option>Paris</option><option>Rome</option></select>
def select_tag(name, option_tags = nil, options = {})
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
- content_tag :select, option_tags, { "name" => html_name, "id" => name }.update(options.stringify_keys)
+ content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
end
# Creates a standard text field; use these text fields to input smaller chunks of text like a username
@@ -112,7 +112,7 @@ module ActionView
# text_field_tag 'ip', '0.0.0.0', :maxlength => 15, :size => 20, :class => "ip-input"
# # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
def text_field_tag(name, value = nil, options = {})
- tag :input, { "type" => "text", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys)
+ tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
end
# Creates a label field
@@ -130,7 +130,7 @@ module ActionView
# label_tag 'name', nil, :class => 'small_label'
# # => <label for="name" class="small_label">Name</label>
def label_tag(name, text = nil, options = {})
- content_tag :label, text || name.to_s.humanize, { "for" => name }.update(options.stringify_keys)
+ content_tag :label, text || name.to_s.humanize, { "for" => sanitize_to_id(name) }.update(options.stringify_keys)
end
# Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or
@@ -282,7 +282,7 @@ module ActionView
# check_box_tag 'eula', 'accepted', false, :disabled => true
# # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
def check_box_tag(name, value = "1", checked = false, options = {})
- html_options = { "type" => "checkbox", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys)
+ html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
html_options["checked"] = "checked" if checked
tag :input, html_options
end
@@ -470,6 +470,12 @@ module ActionView
tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
end
end
+
+ # see http://www.w3.org/TR/html4/types.html#type-name
+ def sanitize_to_id(name)
+ name.to_s.gsub(']','').gsub(/[^-a-zA-Z0-9:.]/, "_")
+ end
+
end
end
end
diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb
index 32089442b7..8f64acf102 100644
--- a/actionpack/lib/action_view/helpers/javascript_helper.rb
+++ b/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -31,9 +31,6 @@ module ActionView
# to use all basic AJAX functionality. For the Scriptaculous-based
# JavaScript helpers, like visual effects, autocompletion, drag and drop
# and so on, you should use the method described above.
- # * Use <tt><%= define_javascript_functions %></tt>: this will copy all the
- # JavaScript support functions within a single script block. Not
- # recommended.
#
# For documentation on +javascript_include_tag+ see
# ActionView::Helpers::AssetTagHelper.
diff --git a/actionpack/lib/action_view/helpers/javascripts/controls.js b/actionpack/lib/action_view/helpers/javascripts/controls.js
deleted file mode 100644
index 5aaf0bb2b7..0000000000
--- a/actionpack/lib/action_view/helpers/javascripts/controls.js
+++ /dev/null
@@ -1,963 +0,0 @@
-// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
-// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
-// Contributors:
-// Richard Livsey
-// Rahul Bhargava
-// Rob Wills
-//
-// script.aculo.us is freely distributable under the terms of an MIT-style license.
-// For details, see the script.aculo.us web site: http://script.aculo.us/
-
-// Autocompleter.Base handles all the autocompletion functionality
-// that's independent of the data source for autocompletion. This
-// includes drawing the autocompletion menu, observing keyboard
-// and mouse events, and similar.
-//
-// Specific autocompleters need to provide, at the very least,
-// a getUpdatedChoices function that will be invoked every time
-// the text inside the monitored textbox changes. This method
-// should get the text for which to provide autocompletion by
-// invoking this.getToken(), NOT by directly accessing
-// this.element.value. This is to allow incremental tokenized
-// autocompletion. Specific auto-completion logic (AJAX, etc)
-// belongs in getUpdatedChoices.
-//
-// Tokenized incremental autocompletion is enabled automatically
-// when an autocompleter is instantiated with the 'tokens' option
-// in the options parameter, e.g.:
-// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
-// will incrementally autocomplete with a comma as the token.
-// Additionally, ',' in the above example can be replaced with
-// a token array, e.g. { tokens: [',', '\n'] } which
-// enables autocompletion on multiple tokens. This is most
-// useful when one of the tokens is \n (a newline), as it
-// allows smart autocompletion after linebreaks.
-
-if(typeof Effect == 'undefined')
- throw("controls.js requires including script.aculo.us' effects.js library");
-
-var Autocompleter = { }
-Autocompleter.Base = Class.create({
- baseInitialize: function(element, update, options) {
- element = $(element)
- this.element = element;
- this.update = $(update);
- this.hasFocus = false;
- this.changed = false;
- this.active = false;
- this.index = 0;
- this.entryCount = 0;
- this.oldElementValue = this.element.value;
-
- if(this.setOptions)
- this.setOptions(options);
- else
- this.options = options || { };
-
- this.options.paramName = this.options.paramName || this.element.name;
- this.options.tokens = this.options.tokens || [];
- this.options.frequency = this.options.frequency || 0.4;
- this.options.minChars = this.options.minChars || 1;
- this.options.onShow = this.options.onShow ||
- function(element, update){
- if(!update.style.position || update.style.position=='absolute') {
- update.style.position = 'absolute';
- Position.clone(element, update, {
- setHeight: false,
- offsetTop: element.offsetHeight
- });
- }
- Effect.Appear(update,{duration:0.15});
- };
- this.options.onHide = this.options.onHide ||
- function(element, update){ new Effect.Fade(update,{duration:0.15}) };
-
- if(typeof(this.options.tokens) == 'string')
- this.options.tokens = new Array(this.options.tokens);
- // Force carriage returns as token delimiters anyway
- if (!this.options.tokens.include('\n'))
- this.options.tokens.push('\n');
-
- this.observer = null;
-
- this.element.setAttribute('autocomplete','off');
-
- Element.hide(this.update);
-
- Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
- Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
- },
-
- show: function() {
- if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
- if(!this.iefix &&
- (Prototype.Browser.IE) &&
- (Element.getStyle(this.update, 'position')=='absolute')) {
- new Insertion.After(this.update,
- '<iframe id="' + this.update.id + '_iefix" '+
- 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
- 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
- this.iefix = $(this.update.id+'_iefix');
- }
- if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
- },
-
- fixIEOverlapping: function() {
- Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
- this.iefix.style.zIndex = 1;
- this.update.style.zIndex = 2;
- Element.show(this.iefix);
- },
-
- hide: function() {
- this.stopIndicator();
- if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
- if(this.iefix) Element.hide(this.iefix);
- },
-
- startIndicator: function() {
- if(this.options.indicator) Element.show(this.options.indicator);
- },
-
- stopIndicator: function() {
- if(this.options.indicator) Element.hide(this.options.indicator);
- },
-
- onKeyPress: function(event) {
- if(this.active)
- switch(event.keyCode) {
- case Event.KEY_TAB:
- case Event.KEY_RETURN:
- this.selectEntry();
- Event.stop(event);
- case Event.KEY_ESC:
- this.hide();
- this.active = false;
- Event.stop(event);
- return;
- case Event.KEY_LEFT:
- case Event.KEY_RIGHT:
- return;
- case Event.KEY_UP:
- this.markPrevious();
- this.render();
- Event.stop(event);
- return;
- case Event.KEY_DOWN:
- this.markNext();
- this.render();
- Event.stop(event);
- return;
- }
- else
- if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
- (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
-
- this.changed = true;
- this.hasFocus = true;
-
- if(this.observer) clearTimeout(this.observer);
- this.observer =
- setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
- },
-
- activate: function() {
- this.changed = false;
- this.hasFocus = true;
- this.getUpdatedChoices();
- },
-
- onHover: function(event) {
- var element = Event.findElement(event, 'LI');
- if(this.index != element.autocompleteIndex)
- {
- this.index = element.autocompleteIndex;
- this.render();
- }
- Event.stop(event);
- },
-
- onClick: function(event) {
- var element = Event.findElement(event, 'LI');
- this.index = element.autocompleteIndex;
- this.selectEntry();
- this.hide();
- },
-
- onBlur: function(event) {
- // needed to make click events working
- setTimeout(this.hide.bind(this), 250);
- this.hasFocus = false;
- this.active = false;
- },
-
- render: function() {
- if(this.entryCount > 0) {
- for (var i = 0; i < this.entryCount; i++)
- this.index==i ?
- Element.addClassName(this.getEntry(i),"selected") :
- Element.removeClassName(this.getEntry(i),"selected");
- if(this.hasFocus) {
- this.show();
- this.active = true;
- }
- } else {
- this.active = false;
- this.hide();
- }
- },
-
- markPrevious: function() {
- if(this.index > 0) this.index--
- else this.index = this.entryCount-1;
- this.getEntry(this.index).scrollIntoView(true);
- },
-
- markNext: function() {
- if(this.index < this.entryCount-1) this.index++
- else this.index = 0;
- this.getEntry(this.index).scrollIntoView(false);
- },
-
- getEntry: function(index) {
- return this.update.firstChild.childNodes[index];
- },
-
- getCurrentEntry: function() {
- return this.getEntry(this.index);
- },
-
- selectEntry: function() {
- this.active = false;
- this.updateElement(this.getCurrentEntry());
- },
-
- updateElement: function(selectedElement) {
- if (this.options.updateElement) {
- this.options.updateElement(selectedElement);
- return;
- }
- var value = '';
- if (this.options.select) {
- var nodes = $(selectedElement).select('.' + this.options.select) || [];
- if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
- } else
- value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
-
- var bounds = this.getTokenBounds();
- if (bounds[0] != -1) {
- var newValue = this.element.value.substr(0, bounds[0]);
- var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
- if (whitespace)
- newValue += whitespace[0];
- this.element.value = newValue + value + this.element.value.substr(bounds[1]);
- } else {
- this.element.value = value;
- }
- this.oldElementValue = this.element.value;
- this.element.focus();
-
- if (this.options.afterUpdateElement)
- this.options.afterUpdateElement(this.element, selectedElement);
- },
-
- updateChoices: function(choices) {
- if(!this.changed && this.hasFocus) {
- this.update.innerHTML = choices;
- Element.cleanWhitespace(this.update);
- Element.cleanWhitespace(this.update.down());
-
- if(this.update.firstChild && this.update.down().childNodes) {
- this.entryCount =
- this.update.down().childNodes.length;
- for (var i = 0; i < this.entryCount; i++) {
- var entry = this.getEntry(i);
- entry.autocompleteIndex = i;
- this.addObservers(entry);
- }
- } else {
- this.entryCount = 0;
- }
-
- this.stopIndicator();
- this.index = 0;
-
- if(this.entryCount==1 && this.options.autoSelect) {
- this.selectEntry();
- this.hide();
- } else {
- this.render();
- }
- }
- },
-
- addObservers: function(element) {
- Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
- Event.observe(element, "click", this.onClick.bindAsEventListener(this));
- },
-
- onObserverEvent: function() {
- this.changed = false;
- this.tokenBounds = null;
- if(this.getToken().length>=this.options.minChars) {
- this.getUpdatedChoices();
- } else {
- this.active = false;
- this.hide();
- }
- this.oldElementValue = this.element.value;
- },
-
- getToken: function() {
- var bounds = this.getTokenBounds();
- return this.element.value.substring(bounds[0], bounds[1]).strip();
- },
-
- getTokenBounds: function() {
- if (null != this.tokenBounds) return this.tokenBounds;
- var value = this.element.value;
- if (value.strip().empty()) return [-1, 0];
- var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
- var offset = (diff == this.oldElementValue.length ? 1 : 0);
- var prevTokenPos = -1, nextTokenPos = value.length;
- var tp;
- for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
- tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
- if (tp > prevTokenPos) prevTokenPos = tp;
- tp = value.indexOf(this.options.tokens[index], diff + offset);
- if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
- }
- return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
- }
-});
-
-Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
- var boundary = Math.min(newS.length, oldS.length);
- for (var index = 0; index < boundary; ++index)
- if (newS[index] != oldS[index])
- return index;
- return boundary;
-};
-
-Ajax.Autocompleter = Class.create(Autocompleter.Base, {
- initialize: function(element, update, url, options) {
- this.baseInitialize(element, update, options);
- this.options.asynchronous = true;
- this.options.onComplete = this.onComplete.bind(this);
- this.options.defaultParams = this.options.parameters || null;
- this.url = url;
- },
-
- getUpdatedChoices: function() {
- this.startIndicator();
-
- var entry = encodeURIComponent(this.options.paramName) + '=' +
- encodeURIComponent(this.getToken());
-
- this.options.parameters = this.options.callback ?
- this.options.callback(this.element, entry) : entry;
-
- if(this.options.defaultParams)
- this.options.parameters += '&' + this.options.defaultParams;
-
- new Ajax.Request(this.url, this.options);
- },
-
- onComplete: function(request) {
- this.updateChoices(request.responseText);
- }
-});
-
-// The local array autocompleter. Used when you'd prefer to
-// inject an array of autocompletion options into the page, rather
-// than sending out Ajax queries, which can be quite slow sometimes.
-//
-// The constructor takes four parameters. The first two are, as usual,
-// the id of the monitored textbox, and id of the autocompletion menu.
-// The third is the array you want to autocomplete from, and the fourth
-// is the options block.
-//
-// Extra local autocompletion options:
-// - choices - How many autocompletion choices to offer
-//
-// - partialSearch - If false, the autocompleter will match entered
-// text only at the beginning of strings in the
-// autocomplete array. Defaults to true, which will
-// match text at the beginning of any *word* in the
-// strings in the autocomplete array. If you want to
-// search anywhere in the string, additionally set
-// the option fullSearch to true (default: off).
-//
-// - fullSsearch - Search anywhere in autocomplete array strings.
-//
-// - partialChars - How many characters to enter before triggering
-// a partial match (unlike minChars, which defines
-// how many characters are required to do any match
-// at all). Defaults to 2.
-//
-// - ignoreCase - Whether to ignore case when autocompleting.
-// Defaults to true.
-//
-// It's possible to pass in a custom function as the 'selector'
-// option, if you prefer to write your own autocompletion logic.
-// In that case, the other options above will not apply unless
-// you support them.
-
-Autocompleter.Local = Class.create(Autocompleter.Base, {
- initialize: function(element, update, array, options) {
- this.baseInitialize(element, update, options);
- this.options.array = array;
- },
-
- getUpdatedChoices: function() {
- this.updateChoices(this.options.selector(this));
- },
-
- setOptions: function(options) {
- this.options = Object.extend({
- choices: 10,
- partialSearch: true,
- partialChars: 2,
- ignoreCase: true,
- fullSearch: false,
- selector: function(instance) {
- var ret = []; // Beginning matches
- var partial = []; // Inside matches
- var entry = instance.getToken();
- var count = 0;
-
- for (var i = 0; i < instance.options.array.length &&
- ret.length < instance.options.choices ; i++) {
-
- var elem = instance.options.array[i];
- var foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase()) :
- elem.indexOf(entry);
-
- while (foundPos != -1) {
- if (foundPos == 0 && elem.length != entry.length) {
- ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
- elem.substr(entry.length) + "</li>");
- break;
- } else if (entry.length >= instance.options.partialChars &&
- instance.options.partialSearch && foundPos != -1) {
- if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
- partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
- elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
- foundPos + entry.length) + "</li>");
- break;
- }
- }
-
- foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
- elem.indexOf(entry, foundPos + 1);
-
- }
- }
- if (partial.length)
- ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
- return "<ul>" + ret.join('') + "</ul>";
- }
- }, options || { });
- }
-});
-
-// AJAX in-place editor and collection editor
-// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
-
-// Use this if you notice weird scrolling problems on some browsers,
-// the DOM might be a bit confused when this gets called so do this
-// waits 1 ms (with setTimeout) until it does the activation
-Field.scrollFreeActivate = function(field) {
- setTimeout(function() {
- Field.activate(field);
- }, 1);
-}
-
-Ajax.InPlaceEditor = Class.create({
- initialize: function(element, url, options) {
- this.url = url;
- this.element = element = $(element);
- this.prepareOptions();
- this._controls = { };
- arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
- Object.extend(this.options, options || { });
- if (!this.options.formId && this.element.id) {
- this.options.formId = this.element.id + '-inplaceeditor';
- if ($(this.options.formId))
- this.options.formId = '';
- }
- if (this.options.externalControl)
- this.options.externalControl = $(this.options.externalControl);
- if (!this.options.externalControl)
- this.options.externalControlOnly = false;
- this._originalBackground = this.element.getStyle('background-color') || 'transparent';
- this.element.title = this.options.clickToEditText;
- this._boundCancelHandler = this.handleFormCancellation.bind(this);
- this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
- this._boundFailureHandler = this.handleAJAXFailure.bind(this);
- this._boundSubmitHandler = this.handleFormSubmission.bind(this);
- this._boundWrapperHandler = this.wrapUp.bind(this);
- this.registerListeners();
- },
- checkForEscapeOrReturn: function(e) {
- if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
- if (Event.KEY_ESC == e.keyCode)
- this.handleFormCancellation(e);
- else if (Event.KEY_RETURN == e.keyCode)
- this.handleFormSubmission(e);
- },
- createControl: function(mode, handler, extraClasses) {
- var control = this.options[mode + 'Control'];
- var text = this.options[mode + 'Text'];
- if ('button' == control) {
- var btn = document.createElement('input');
- btn.type = 'submit';
- btn.value = text;
- btn.className = 'editor_' + mode + '_button';
- if ('cancel' == mode)
- btn.onclick = this._boundCancelHandler;
- this._form.appendChild(btn);
- this._controls[mode] = btn;
- } else if ('link' == control) {
- var link = document.createElement('a');
- link.href = '#';
- link.appendChild(document.createTextNode(text));
- link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
- link.className = 'editor_' + mode + '_link';
- if (extraClasses)
- link.className += ' ' + extraClasses;
- this._form.appendChild(link);
- this._controls[mode] = link;
- }
- },
- createEditField: function() {
- var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
- var fld;
- if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
- fld = document.createElement('input');
- fld.type = 'text';
- var size = this.options.size || this.options.cols || 0;
- if (0 < size) fld.size = size;
- } else {
- fld = document.createElement('textarea');
- fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
- fld.cols = this.options.cols || 40;
- }
- fld.name = this.options.paramName;
- fld.value = text; // No HTML breaks conversion anymore
- fld.className = 'editor_field';
- if (this.options.submitOnBlur)
- fld.onblur = this._boundSubmitHandler;
- this._controls.editor = fld;
- if (this.options.loadTextURL)
- this.loadExternalText();
- this._form.appendChild(this._controls.editor);
- },
- createForm: function() {
- var ipe = this;
- function addText(mode, condition) {
- var text = ipe.options['text' + mode + 'Controls'];
- if (!text || condition === false) return;
- ipe._form.appendChild(document.createTextNode(text));
- };
- this._form = $(document.createElement('form'));
- this._form.id = this.options.formId;
- this._form.addClassName(this.options.formClassName);
- this._form.onsubmit = this._boundSubmitHandler;
- this.createEditField();
- if ('textarea' == this._controls.editor.tagName.toLowerCase())
- this._form.appendChild(document.createElement('br'));
- if (this.options.onFormCustomization)
- this.options.onFormCustomization(this, this._form);
- addText('Before', this.options.okControl || this.options.cancelControl);
- this.createControl('ok', this._boundSubmitHandler);
- addText('Between', this.options.okControl && this.options.cancelControl);
- this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
- addText('After', this.options.okControl || this.options.cancelControl);
- },
- destroy: function() {
- if (this._oldInnerHTML)
- this.element.innerHTML = this._oldInnerHTML;
- this.leaveEditMode();
- this.unregisterListeners();
- },
- enterEditMode: function(e) {
- if (this._saving || this._editing) return;
- this._editing = true;
- this.triggerCallback('onEnterEditMode');
- if (this.options.externalControl)
- this.options.externalControl.hide();
- this.element.hide();
- this.createForm();
- this.element.parentNode.insertBefore(this._form, this.element);
- if (!this.options.loadTextURL)
- this.postProcessEditField();
- if (e) Event.stop(e);
- },
- enterHover: function(e) {
- if (this.options.hoverClassName)
- this.element.addClassName(this.options.hoverClassName);
- if (this._saving) return;
- this.triggerCallback('onEnterHover');
- },
- getText: function() {
- return this.element.innerHTML;
- },
- handleAJAXFailure: function(transport) {
- this.triggerCallback('onFailure', transport);
- if (this._oldInnerHTML) {
- this.element.innerHTML = this._oldInnerHTML;
- this._oldInnerHTML = null;
- }
- },
- handleFormCancellation: function(e) {
- this.wrapUp();
- if (e) Event.stop(e);
- },
- handleFormSubmission: function(e) {
- var form = this._form;
- var value = $F(this._controls.editor);
- this.prepareSubmission();
- var params = this.options.callback(form, value) || '';
- if (Object.isString(params))
- params = params.toQueryParams();
- params.editorId = this.element.id;
- if (this.options.htmlResponse) {
- var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: params,
- onComplete: this._boundWrapperHandler,
- onFailure: this._boundFailureHandler
- });
- new Ajax.Updater({ success: this.element }, this.url, options);
- } else {
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: params,
- onComplete: this._boundWrapperHandler,
- onFailure: this._boundFailureHandler
- });
- new Ajax.Request(this.url, options);
- }
- if (e) Event.stop(e);
- },
- leaveEditMode: function() {
- this.element.removeClassName(this.options.savingClassName);
- this.removeForm();
- this.leaveHover();
- this.element.style.backgroundColor = this._originalBackground;
- this.element.show();
- if (this.options.externalControl)
- this.options.externalControl.show();
- this._saving = false;
- this._editing = false;
- this._oldInnerHTML = null;
- this.triggerCallback('onLeaveEditMode');
- },
- leaveHover: function(e) {
- if (this.options.hoverClassName)
- this.element.removeClassName(this.options.hoverClassName);
- if (this._saving) return;
- this.triggerCallback('onLeaveHover');
- },
- loadExternalText: function() {
- this._form.addClassName(this.options.loadingClassName);
- this._controls.editor.disabled = true;
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: 'editorId=' + encodeURIComponent(this.element.id),
- onComplete: Prototype.emptyFunction,
- onSuccess: function(transport) {
- this._form.removeClassName(this.options.loadingClassName);
- var text = transport.responseText;
- if (this.options.stripLoadedTextTags)
- text = text.stripTags();
- this._controls.editor.value = text;
- this._controls.editor.disabled = false;
- this.postProcessEditField();
- }.bind(this),
- onFailure: this._boundFailureHandler
- });
- new Ajax.Request(this.options.loadTextURL, options);
- },
- postProcessEditField: function() {
- var fpc = this.options.fieldPostCreation;
- if (fpc)
- $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
- },
- prepareOptions: function() {
- this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
- Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
- [this._extraDefaultOptions].flatten().compact().each(function(defs) {
- Object.extend(this.options, defs);
- }.bind(this));
- },
- prepareSubmission: function() {
- this._saving = true;
- this.removeForm();
- this.leaveHover();
- this.showSaving();
- },
- registerListeners: function() {
- this._listeners = { };
- var listener;
- $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
- listener = this[pair.value].bind(this);
- this._listeners[pair.key] = listener;
- if (!this.options.externalControlOnly)
- this.element.observe(pair.key, listener);
- if (this.options.externalControl)
- this.options.externalControl.observe(pair.key, listener);
- }.bind(this));
- },
- removeForm: function() {
- if (!this._form) return;
- this._form.remove();
- this._form = null;
- this._controls = { };
- },
- showSaving: function() {
- this._oldInnerHTML = this.element.innerHTML;
- this.element.innerHTML = this.options.savingText;
- this.element.addClassName(this.options.savingClassName);
- this.element.style.backgroundColor = this._originalBackground;
- this.element.show();
- },
- triggerCallback: function(cbName, arg) {
- if ('function' == typeof this.options[cbName]) {
- this.options[cbName](this, arg);
- }
- },
- unregisterListeners: function() {
- $H(this._listeners).each(function(pair) {
- if (!this.options.externalControlOnly)
- this.element.stopObserving(pair.key, pair.value);
- if (this.options.externalControl)
- this.options.externalControl.stopObserving(pair.key, pair.value);
- }.bind(this));
- },
- wrapUp: function(transport) {
- this.leaveEditMode();
- // Can't use triggerCallback due to backward compatibility: requires
- // binding + direct element
- this._boundComplete(transport, this.element);
- }
-});
-
-Object.extend(Ajax.InPlaceEditor.prototype, {
- dispose: Ajax.InPlaceEditor.prototype.destroy
-});
-
-Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
- initialize: function($super, element, url, options) {
- this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
- $super(element, url, options);
- },
-
- createEditField: function() {
- var list = document.createElement('select');
- list.name = this.options.paramName;
- list.size = 1;
- this._controls.editor = list;
- this._collection = this.options.collection || [];
- if (this.options.loadCollectionURL)
- this.loadCollection();
- else
- this.checkForExternalText();
- this._form.appendChild(this._controls.editor);
- },
-
- loadCollection: function() {
- this._form.addClassName(this.options.loadingClassName);
- this.showLoadingText(this.options.loadingCollectionText);
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: 'editorId=' + encodeURIComponent(this.element.id),
- onComplete: Prototype.emptyFunction,
- onSuccess: function(transport) {
- var js = transport.responseText.strip();
- if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
- throw 'Server returned an invalid collection representation.';
- this._collection = eval(js);
- this.checkForExternalText();
- }.bind(this),
- onFailure: this.onFailure
- });
- new Ajax.Request(this.options.loadCollectionURL, options);
- },
-
- showLoadingText: function(text) {
- this._controls.editor.disabled = true;
- var tempOption = this._controls.editor.firstChild;
- if (!tempOption) {
- tempOption = document.createElement('option');
- tempOption.value = '';
- this._controls.editor.appendChild(tempOption);
- tempOption.selected = true;
- }
- tempOption.update((text || '').stripScripts().stripTags());
- },
-
- checkForExternalText: function() {
- this._text = this.getText();
- if (this.options.loadTextURL)
- this.loadExternalText();
- else
- this.buildOptionList();
- },
-
- loadExternalText: function() {
- this.showLoadingText(this.options.loadingText);
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: 'editorId=' + encodeURIComponent(this.element.id),
- onComplete: Prototype.emptyFunction,
- onSuccess: function(transport) {
- this._text = transport.responseText.strip();
- this.buildOptionList();
- }.bind(this),
- onFailure: this.onFailure
- });
- new Ajax.Request(this.options.loadTextURL, options);
- },
-
- buildOptionList: function() {
- this._form.removeClassName(this.options.loadingClassName);
- this._collection = this._collection.map(function(entry) {
- return 2 === entry.length ? entry : [entry, entry].flatten();
- });
- var marker = ('value' in this.options) ? this.options.value : this._text;
- var textFound = this._collection.any(function(entry) {
- return entry[0] == marker;
- }.bind(this));
- this._controls.editor.update('');
- var option;
- this._collection.each(function(entry, index) {
- option = document.createElement('option');
- option.value = entry[0];
- option.selected = textFound ? entry[0] == marker : 0 == index;
- option.appendChild(document.createTextNode(entry[1]));
- this._controls.editor.appendChild(option);
- }.bind(this));
- this._controls.editor.disabled = false;
- Field.scrollFreeActivate(this._controls.editor);
- }
-});
-
-//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
-//**** This only exists for a while, in order to let ****
-//**** users adapt to the new API. Read up on the new ****
-//**** API and convert your code to it ASAP! ****
-
-Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
- if (!options) return;
- function fallback(name, expr) {
- if (name in options || expr === undefined) return;
- options[name] = expr;
- };
- fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
- options.cancelLink == options.cancelButton == false ? false : undefined)));
- fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
- options.okLink == options.okButton == false ? false : undefined)));
- fallback('highlightColor', options.highlightcolor);
- fallback('highlightEndColor', options.highlightendcolor);
-};
-
-Object.extend(Ajax.InPlaceEditor, {
- DefaultOptions: {
- ajaxOptions: { },
- autoRows: 3, // Use when multi-line w/ rows == 1
- cancelControl: 'link', // 'link'|'button'|false
- cancelText: 'cancel',
- clickToEditText: 'Click to edit',
- externalControl: null, // id|elt
- externalControlOnly: false,
- fieldPostCreation: 'activate', // 'activate'|'focus'|false
- formClassName: 'inplaceeditor-form',
- formId: null, // id|elt
- highlightColor: '#ffff99',
- highlightEndColor: '#ffffff',
- hoverClassName: '',
- htmlResponse: true,
- loadingClassName: 'inplaceeditor-loading',
- loadingText: 'Loading...',
- okControl: 'button', // 'link'|'button'|false
- okText: 'ok',
- paramName: 'value',
- rows: 1, // If 1 and multi-line, uses autoRows
- savingClassName: 'inplaceeditor-saving',
- savingText: 'Saving...',
- size: 0,
- stripLoadedTextTags: false,
- submitOnBlur: false,
- textAfterControls: '',
- textBeforeControls: '',
- textBetweenControls: ''
- },
- DefaultCallbacks: {
- callback: function(form) {
- return Form.serialize(form);
- },
- onComplete: function(transport, element) {
- // For backward compatibility, this one is bound to the IPE, and passes
- // the element directly. It was too often customized, so we don't break it.
- new Effect.Highlight(element, {
- startcolor: this.options.highlightColor, keepBackgroundImage: true });
- },
- onEnterEditMode: null,
- onEnterHover: function(ipe) {
- ipe.element.style.backgroundColor = ipe.options.highlightColor;
- if (ipe._effect)
- ipe._effect.cancel();
- },
- onFailure: function(transport, ipe) {
- alert('Error communication with the server: ' + transport.responseText.stripTags());
- },
- onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
- onLeaveEditMode: null,
- onLeaveHover: function(ipe) {
- ipe._effect = new Effect.Highlight(ipe.element, {
- startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
- restorecolor: ipe._originalBackground, keepBackgroundImage: true
- });
- }
- },
- Listeners: {
- click: 'enterEditMode',
- keydown: 'checkForEscapeOrReturn',
- mouseover: 'enterHover',
- mouseout: 'leaveHover'
- }
-});
-
-Ajax.InPlaceCollectionEditor.DefaultOptions = {
- loadingCollectionText: 'Loading options...'
-};
-
-// Delayed observer, like Form.Element.Observer,
-// but waits for delay after last key input
-// Ideal for live-search fields
-
-Form.Element.DelayedObserver = Class.create({
- initialize: function(element, delay, callback) {
- this.delay = delay || 0.5;
- this.element = $(element);
- this.callback = callback;
- this.timer = null;
- this.lastValue = $F(this.element);
- Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
- },
- delayedListener: function(event) {
- if(this.lastValue == $F(this.element)) return;
- if(this.timer) clearTimeout(this.timer);
- this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
- this.lastValue = $F(this.element);
- },
- onTimerEvent: function() {
- this.timer = null;
- this.callback(this.element, $F(this.element));
- }
-});
diff --git a/actionpack/lib/action_view/helpers/javascripts/dragdrop.js b/actionpack/lib/action_view/helpers/javascripts/dragdrop.js
deleted file mode 100644
index bf5cfea66c..0000000000
--- a/actionpack/lib/action_view/helpers/javascripts/dragdrop.js
+++ /dev/null
@@ -1,972 +0,0 @@
-// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
-//
-// script.aculo.us is freely distributable under the terms of an MIT-style license.
-// For details, see the script.aculo.us web site: http://script.aculo.us/
-
-if(Object.isUndefined(Effect))
- throw("dragdrop.js requires including script.aculo.us' effects.js library");
-
-var Droppables = {
- drops: [],
-
- remove: function(element) {
- this.drops = this.drops.reject(function(d) { return d.element==$(element) });
- },
-
- add: function(element) {
- element = $(element);
- var options = Object.extend({
- greedy: true,
- hoverclass: null,
- tree: false
- }, arguments[1] || { });
-
- // cache containers
- if(options.containment) {
- options._containers = [];
- var containment = options.containment;
- if(Object.isArray(containment)) {
- containment.each( function(c) { options._containers.push($(c)) });
- } else {
- options._containers.push($(containment));
- }
- }
-
- if(options.accept) options.accept = [options.accept].flatten();
-
- Element.makePositioned(element); // fix IE
- options.element = element;
-
- this.drops.push(options);
- },
-
- findDeepestChild: function(drops) {
- deepest = drops[0];
-
- for (i = 1; i < drops.length; ++i)
- if (Element.isParent(drops[i].element, deepest.element))
- deepest = drops[i];
-
- return deepest;
- },
-
- isContained: function(element, drop) {
- var containmentNode;
- if(drop.tree) {
- containmentNode = element.treeNode;
- } else {
- containmentNode = element.parentNode;
- }
- return drop._containers.detect(function(c) { return containmentNode == c });
- },
-
- isAffected: function(point, element, drop) {
- return (
- (drop.element!=element) &&
- ((!drop._containers) ||
- this.isContained(element, drop)) &&
- ((!drop.accept) ||
- (Element.classNames(element).detect(
- function(v) { return drop.accept.include(v) } ) )) &&
- Position.within(drop.element, point[0], point[1]) );
- },
-
- deactivate: function(drop) {
- if(drop.hoverclass)
- Element.removeClassName(drop.element, drop.hoverclass);
- this.last_active = null;
- },
-
- activate: function(drop) {
- if(drop.hoverclass)
- Element.addClassName(drop.element, drop.hoverclass);
- this.last_active = drop;
- },
-
- show: function(point, element) {
- if(!this.drops.length) return;
- var drop, affected = [];
-
- this.drops.each( function(drop) {
- if(Droppables.isAffected(point, element, drop))
- affected.push(drop);
- });
-
- if(affected.length>0)
- drop = Droppables.findDeepestChild(affected);
-
- if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
- if (drop) {
- Position.within(drop.element, point[0], point[1]);
- if(drop.onHover)
- drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
-
- if (drop != this.last_active) Droppables.activate(drop);
- }
- },
-
- fire: function(event, element) {
- if(!this.last_active) return;
- Position.prepare();
-
- if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
- if (this.last_active.onDrop) {
- this.last_active.onDrop(element, this.last_active.element, event);
- return true;
- }
- },
-
- reset: function() {
- if(this.last_active)
- this.deactivate(this.last_active);
- }
-}
-
-var Draggables = {
- drags: [],
- observers: [],
-
- register: function(draggable) {
- if(this.drags.length == 0) {
- this.eventMouseUp = this.endDrag.bindAsEventListener(this);
- this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
- this.eventKeypress = this.keyPress.bindAsEventListener(this);
-
- Event.observe(document, "mouseup", this.eventMouseUp);
- Event.observe(document, "mousemove", this.eventMouseMove);
- Event.observe(document, "keypress", this.eventKeypress);
- }
- this.drags.push(draggable);
- },
-
- unregister: function(draggable) {
- this.drags = this.drags.reject(function(d) { return d==draggable });
- if(this.drags.length == 0) {
- Event.stopObserving(document, "mouseup", this.eventMouseUp);
- Event.stopObserving(document, "mousemove", this.eventMouseMove);
- Event.stopObserving(document, "keypress", this.eventKeypress);
- }
- },
-
- activate: function(draggable) {
- if(draggable.options.delay) {
- this._timeout = setTimeout(function() {
- Draggables._timeout = null;
- window.focus();
- Draggables.activeDraggable = draggable;
- }.bind(this), draggable.options.delay);
- } else {
- window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
- this.activeDraggable = draggable;
- }
- },
-
- deactivate: function() {
- this.activeDraggable = null;
- },
-
- updateDrag: function(event) {
- if(!this.activeDraggable) return;
- var pointer = [Event.pointerX(event), Event.pointerY(event)];
- // Mozilla-based browsers fire successive mousemove events with
- // the same coordinates, prevent needless redrawing (moz bug?)
- if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
- this._lastPointer = pointer;
-
- this.activeDraggable.updateDrag(event, pointer);
- },
-
- endDrag: function(event) {
- if(this._timeout) {
- clearTimeout(this._timeout);
- this._timeout = null;
- }
- if(!this.activeDraggable) return;
- this._lastPointer = null;
- this.activeDraggable.endDrag(event);
- this.activeDraggable = null;
- },
-
- keyPress: function(event) {
- if(this.activeDraggable)
- this.activeDraggable.keyPress(event);
- },
-
- addObserver: function(observer) {
- this.observers.push(observer);
- this._cacheObserverCallbacks();
- },
-
- removeObserver: function(element) { // element instead of observer fixes mem leaks
- this.observers = this.observers.reject( function(o) { return o.element==element });
- this._cacheObserverCallbacks();
- },
-
- notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
- if(this[eventName+'Count'] > 0)
- this.observers.each( function(o) {
- if(o[eventName]) o[eventName](eventName, draggable, event);
- });
- if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
- },
-
- _cacheObserverCallbacks: function() {
- ['onStart','onEnd','onDrag'].each( function(eventName) {
- Draggables[eventName+'Count'] = Draggables.observers.select(
- function(o) { return o[eventName]; }
- ).length;
- });
- }
-}
-
-/*--------------------------------------------------------------------------*/
-
-var Draggable = Class.create({
- initialize: function(element) {
- var defaults = {
- handle: false,
- reverteffect: function(element, top_offset, left_offset) {
- var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
- new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
- queue: {scope:'_draggable', position:'end'}
- });
- },
- endeffect: function(element) {
- var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
- new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
- queue: {scope:'_draggable', position:'end'},
- afterFinish: function(){
- Draggable._dragging[element] = false
- }
- });
- },
- zindex: 1000,
- revert: false,
- quiet: false,
- scroll: false,
- scrollSensitivity: 20,
- scrollSpeed: 15,
- snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
- delay: 0
- };
-
- if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
- Object.extend(defaults, {
- starteffect: function(element) {
- element._opacity = Element.getOpacity(element);
- Draggable._dragging[element] = true;
- new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
- }
- });
-
- var options = Object.extend(defaults, arguments[1] || { });
-
- this.element = $(element);
-
- if(options.handle && Object.isString(options.handle))
- this.handle = this.element.down('.'+options.handle, 0);
-
- if(!this.handle) this.handle = $(options.handle);
- if(!this.handle) this.handle = this.element;
-
- if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
- options.scroll = $(options.scroll);
- this._isScrollChild = Element.childOf(this.element, options.scroll);
- }
-
- Element.makePositioned(this.element); // fix IE
-
- this.options = options;
- this.dragging = false;
-
- this.eventMouseDown = this.initDrag.bindAsEventListener(this);
- Event.observe(this.handle, "mousedown", this.eventMouseDown);
-
- Draggables.register(this);
- },
-
- destroy: function() {
- Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
- Draggables.unregister(this);
- },
-
- currentDelta: function() {
- return([
- parseInt(Element.getStyle(this.element,'left') || '0'),
- parseInt(Element.getStyle(this.element,'top') || '0')]);
- },
-
- initDrag: function(event) {
- if(!Object.isUndefined(Draggable._dragging[this.element]) &&
- Draggable._dragging[this.element]) return;
- if(Event.isLeftClick(event)) {
- // abort on form elements, fixes a Firefox issue
- var src = Event.element(event);
- if((tag_name = src.tagName.toUpperCase()) && (
- tag_name=='INPUT' ||
- tag_name=='SELECT' ||
- tag_name=='OPTION' ||
- tag_name=='BUTTON' ||
- tag_name=='TEXTAREA')) return;
-
- var pointer = [Event.pointerX(event), Event.pointerY(event)];
- var pos = Position.cumulativeOffset(this.element);
- this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
-
- Draggables.activate(this);
- Event.stop(event);
- }
- },
-
- startDrag: function(event) {
- this.dragging = true;
- if(!this.delta)
- this.delta = this.currentDelta();
-
- if(this.options.zindex) {
- this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
- this.element.style.zIndex = this.options.zindex;
- }
-
- if(this.options.ghosting) {
- this._clone = this.element.cloneNode(true);
- this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
- if (!this.element._originallyAbsolute)
- Position.absolutize(this.element);
- this.element.parentNode.insertBefore(this._clone, this.element);
- }
-
- if(this.options.scroll) {
- if (this.options.scroll == window) {
- var where = this._getWindowScroll(this.options.scroll);
- this.originalScrollLeft = where.left;
- this.originalScrollTop = where.top;
- } else {
- this.originalScrollLeft = this.options.scroll.scrollLeft;
- this.originalScrollTop = this.options.scroll.scrollTop;
- }
- }
-
- Draggables.notify('onStart', this, event);
-
- if(this.options.starteffect) this.options.starteffect(this.element);
- },
-
- updateDrag: function(event, pointer) {
- if(!this.dragging) this.startDrag(event);
-
- if(!this.options.quiet){
- Position.prepare();
- Droppables.show(pointer, this.element);
- }
-
- Draggables.notify('onDrag', this, event);
-
- this.draw(pointer);
- if(this.options.change) this.options.change(this);
-
- if(this.options.scroll) {
- this.stopScrolling();
-
- var p;
- if (this.options.scroll == window) {
- with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
- } else {
- p = Position.page(this.options.scroll);
- p[0] += this.options.scroll.scrollLeft + Position.deltaX;
- p[1] += this.options.scroll.scrollTop + Position.deltaY;
- p.push(p[0]+this.options.scroll.offsetWidth);
- p.push(p[1]+this.options.scroll.offsetHeight);
- }
- var speed = [0,0];
- if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
- if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
- if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
- if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
- this.startScrolling(speed);
- }
-
- // fix AppleWebKit rendering
- if(Prototype.Browser.WebKit) window.scrollBy(0,0);
-
- Event.stop(event);
- },
-
- finishDrag: function(event, success) {
- this.dragging = false;
-
- if(this.options.quiet){
- Position.prepare();
- var pointer = [Event.pointerX(event), Event.pointerY(event)];
- Droppables.show(pointer, this.element);
- }
-
- if(this.options.ghosting) {
- if (!this.element._originallyAbsolute)
- Position.relativize(this.element);
- delete this.element._originallyAbsolute;
- Element.remove(this._clone);
- this._clone = null;
- }
-
- var dropped = false;
- if(success) {
- dropped = Droppables.fire(event, this.element);
- if (!dropped) dropped = false;
- }
- if(dropped && this.options.onDropped) this.options.onDropped(this.element);
- Draggables.notify('onEnd', this, event);
-
- var revert = this.options.revert;
- if(revert && Object.isFunction(revert)) revert = revert(this.element);
-
- var d = this.currentDelta();
- if(revert && this.options.reverteffect) {
- if (dropped == 0 || revert != 'failure')
- this.options.reverteffect(this.element,
- d[1]-this.delta[1], d[0]-this.delta[0]);
- } else {
- this.delta = d;
- }
-
- if(this.options.zindex)
- this.element.style.zIndex = this.originalZ;
-
- if(this.options.endeffect)
- this.options.endeffect(this.element);
-
- Draggables.deactivate(this);
- Droppables.reset();
- },
-
- keyPress: function(event) {
- if(event.keyCode!=Event.KEY_ESC) return;
- this.finishDrag(event, false);
- Event.stop(event);
- },
-
- endDrag: function(event) {
- if(!this.dragging) return;
- this.stopScrolling();
- this.finishDrag(event, true);
- Event.stop(event);
- },
-
- draw: function(point) {
- var pos = Position.cumulativeOffset(this.element);
- if(this.options.ghosting) {
- var r = Position.realOffset(this.element);
- pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
- }
-
- var d = this.currentDelta();
- pos[0] -= d[0]; pos[1] -= d[1];
-
- if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
- pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
- pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
- }
-
- var p = [0,1].map(function(i){
- return (point[i]-pos[i]-this.offset[i])
- }.bind(this));
-
- if(this.options.snap) {
- if(Object.isFunction(this.options.snap)) {
- p = this.options.snap(p[0],p[1],this);
- } else {
- if(Object.isArray(this.options.snap)) {
- p = p.map( function(v, i) {
- return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
- } else {
- p = p.map( function(v) {
- return (v/this.options.snap).round()*this.options.snap }.bind(this))
- }
- }}
-
- var style = this.element.style;
- if((!this.options.constraint) || (this.options.constraint=='horizontal'))
- style.left = p[0] + "px";
- if((!this.options.constraint) || (this.options.constraint=='vertical'))
- style.top = p[1] + "px";
-
- if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
- },
-
- stopScrolling: function() {
- if(this.scrollInterval) {
- clearInterval(this.scrollInterval);
- this.scrollInterval = null;
- Draggables._lastScrollPointer = null;
- }
- },
-
- startScrolling: function(speed) {
- if(!(speed[0] || speed[1])) return;
- this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
- this.lastScrolled = new Date();
- this.scrollInterval = setInterval(this.scroll.bind(this), 10);
- },
-
- scroll: function() {
- var current = new Date();
- var delta = current - this.lastScrolled;
- this.lastScrolled = current;
- if(this.options.scroll == window) {
- with (this._getWindowScroll(this.options.scroll)) {
- if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
- var d = delta / 1000;
- this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
- }
- }
- } else {
- this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
- this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
- }
-
- Position.prepare();
- Droppables.show(Draggables._lastPointer, this.element);
- Draggables.notify('onDrag', this);
- if (this._isScrollChild) {
- Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
- Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
- Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
- if (Draggables._lastScrollPointer[0] < 0)
- Draggables._lastScrollPointer[0] = 0;
- if (Draggables._lastScrollPointer[1] < 0)
- Draggables._lastScrollPointer[1] = 0;
- this.draw(Draggables._lastScrollPointer);
- }
-
- if(this.options.change) this.options.change(this);
- },
-
- _getWindowScroll: function(w) {
- var T, L, W, H;
- with (w.document) {
- if (w.document.documentElement && documentElement.scrollTop) {
- T = documentElement.scrollTop;
- L = documentElement.scrollLeft;
- } else if (w.document.body) {
- T = body.scrollTop;
- L = body.scrollLeft;
- }
- if (w.innerWidth) {
- W = w.innerWidth;
- H = w.innerHeight;
- } else if (w.document.documentElement && documentElement.clientWidth) {
- W = documentElement.clientWidth;
- H = documentElement.clientHeight;
- } else {
- W = body.offsetWidth;
- H = body.offsetHeight
- }
- }
- return { top: T, left: L, width: W, height: H };
- }
-});
-
-Draggable._dragging = { };
-
-/*--------------------------------------------------------------------------*/
-
-var SortableObserver = Class.create({
- initialize: function(element, observer) {
- this.element = $(element);
- this.observer = observer;
- this.lastValue = Sortable.serialize(this.element);
- },
-
- onStart: function() {
- this.lastValue = Sortable.serialize(this.element);
- },
-
- onEnd: function() {
- Sortable.unmark();
- if(this.lastValue != Sortable.serialize(this.element))
- this.observer(this.element)
- }
-});
-
-var Sortable = {
- SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
-
- sortables: { },
-
- _findRootElement: function(element) {
- while (element.tagName.toUpperCase() != "BODY") {
- if(element.id && Sortable.sortables[element.id]) return element;
- element = element.parentNode;
- }
- },
-
- options: function(element) {
- element = Sortable._findRootElement($(element));
- if(!element) return;
- return Sortable.sortables[element.id];
- },
-
- destroy: function(element){
- var s = Sortable.options(element);
-
- if(s) {
- Draggables.removeObserver(s.element);
- s.droppables.each(function(d){ Droppables.remove(d) });
- s.draggables.invoke('destroy');
-
- delete Sortable.sortables[s.element.id];
- }
- },
-
- create: function(element) {
- element = $(element);
- var options = Object.extend({
- element: element,
- tag: 'li', // assumes li children, override with tag: 'tagname'
- dropOnEmpty: false,
- tree: false,
- treeTag: 'ul',
- overlap: 'vertical', // one of 'vertical', 'horizontal'
- constraint: 'vertical', // one of 'vertical', 'horizontal', false
- containment: element, // also takes array of elements (or id's); or false
- handle: false, // or a CSS class
- only: false,
- delay: 0,
- hoverclass: null,
- ghosting: false,
- quiet: false,
- scroll: false,
- scrollSensitivity: 20,
- scrollSpeed: 15,
- format: this.SERIALIZE_RULE,
-
- // these take arrays of elements or ids and can be
- // used for better initialization performance
- elements: false,
- handles: false,
-
- onChange: Prototype.emptyFunction,
- onUpdate: Prototype.emptyFunction
- }, arguments[1] || { });
-
- // clear any old sortable with same element
- this.destroy(element);
-
- // build options for the draggables
- var options_for_draggable = {
- revert: true,
- quiet: options.quiet,
- scroll: options.scroll,
- scrollSpeed: options.scrollSpeed,
- scrollSensitivity: options.scrollSensitivity,
- delay: options.delay,
- ghosting: options.ghosting,
- constraint: options.constraint,
- handle: options.handle };
-
- if(options.starteffect)
- options_for_draggable.starteffect = options.starteffect;
-
- if(options.reverteffect)
- options_for_draggable.reverteffect = options.reverteffect;
- else
- if(options.ghosting) options_for_draggable.reverteffect = function(element) {
- element.style.top = 0;
- element.style.left = 0;
- };
-
- if(options.endeffect)
- options_for_draggable.endeffect = options.endeffect;
-
- if(options.zindex)
- options_for_draggable.zindex = options.zindex;
-
- // build options for the droppables
- var options_for_droppable = {
- overlap: options.overlap,
- containment: options.containment,
- tree: options.tree,
- hoverclass: options.hoverclass,
- onHover: Sortable.onHover
- }
-
- var options_for_tree = {
- onHover: Sortable.onEmptyHover,
- overlap: options.overlap,
- containment: options.containment,
- hoverclass: options.hoverclass
- }
-
- // fix for gecko engine
- Element.cleanWhitespace(element);
-
- options.draggables = [];
- options.droppables = [];
-
- // drop on empty handling
- if(options.dropOnEmpty || options.tree) {
- Droppables.add(element, options_for_tree);
- options.droppables.push(element);
- }
-
- (options.elements || this.findElements(element, options) || []).each( function(e,i) {
- var handle = options.handles ? $(options.handles[i]) :
- (options.handle ? $(e).select('.' + options.handle)[0] : e);
- options.draggables.push(
- new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
- Droppables.add(e, options_for_droppable);
- if(options.tree) e.treeNode = element;
- options.droppables.push(e);
- });
-
- if(options.tree) {
- (Sortable.findTreeElements(element, options) || []).each( function(e) {
- Droppables.add(e, options_for_tree);
- e.treeNode = element;
- options.droppables.push(e);
- });
- }
-
- // keep reference
- this.sortables[element.id] = options;
-
- // for onupdate
- Draggables.addObserver(new SortableObserver(element, options.onUpdate));
-
- },
-
- // return all suitable-for-sortable elements in a guaranteed order
- findElements: function(element, options) {
- return Element.findChildren(
- element, options.only, options.tree ? true : false, options.tag);
- },
-
- findTreeElements: function(element, options) {
- return Element.findChildren(
- element, options.only, options.tree ? true : false, options.treeTag);
- },
-
- onHover: function(element, dropon, overlap) {
- if(Element.isParent(dropon, element)) return;
-
- if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
- return;
- } else if(overlap>0.5) {
- Sortable.mark(dropon, 'before');
- if(dropon.previousSibling != element) {
- var oldParentNode = element.parentNode;
- element.style.visibility = "hidden"; // fix gecko rendering
- dropon.parentNode.insertBefore(element, dropon);
- if(dropon.parentNode!=oldParentNode)
- Sortable.options(oldParentNode).onChange(element);
- Sortable.options(dropon.parentNode).onChange(element);
- }
- } else {
- Sortable.mark(dropon, 'after');
- var nextElement = dropon.nextSibling || null;
- if(nextElement != element) {
- var oldParentNode = element.parentNode;
- element.style.visibility = "hidden"; // fix gecko rendering
- dropon.parentNode.insertBefore(element, nextElement);
- if(dropon.parentNode!=oldParentNode)
- Sortable.options(oldParentNode).onChange(element);
- Sortable.options(dropon.parentNode).onChange(element);
- }
- }
- },
-
- onEmptyHover: function(element, dropon, overlap) {
- var oldParentNode = element.parentNode;
- var droponOptions = Sortable.options(dropon);
-
- if(!Element.isParent(dropon, element)) {
- var index;
-
- var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
- var child = null;
-
- if(children) {
- var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
-
- for (index = 0; index < children.length; index += 1) {
- if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
- offset -= Element.offsetSize (children[index], droponOptions.overlap);
- } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
- child = index + 1 < children.length ? children[index + 1] : null;
- break;
- } else {
- child = children[index];
- break;
- }
- }
- }
-
- dropon.insertBefore(element, child);
-
- Sortable.options(oldParentNode).onChange(element);
- droponOptions.onChange(element);
- }
- },
-
- unmark: function() {
- if(Sortable._marker) Sortable._marker.hide();
- },
-
- mark: function(dropon, position) {
- // mark on ghosting only
- var sortable = Sortable.options(dropon.parentNode);
- if(sortable && !sortable.ghosting) return;
-
- if(!Sortable._marker) {
- Sortable._marker =
- ($('dropmarker') || Element.extend(document.createElement('DIV'))).
- hide().addClassName('dropmarker').setStyle({position:'absolute'});
- document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
- }
- var offsets = Position.cumulativeOffset(dropon);
- Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
-
- if(position=='after')
- if(sortable.overlap == 'horizontal')
- Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
- else
- Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
-
- Sortable._marker.show();
- },
-
- _tree: function(element, options, parent) {
- var children = Sortable.findElements(element, options) || [];
-
- for (var i = 0; i < children.length; ++i) {
- var match = children[i].id.match(options.format);
-
- if (!match) continue;
-
- var child = {
- id: encodeURIComponent(match ? match[1] : null),
- element: element,
- parent: parent,
- children: [],
- position: parent.children.length,
- container: $(children[i]).down(options.treeTag)
- }
-
- /* Get the element containing the children and recurse over it */
- if (child.container)
- this._tree(child.container, options, child)
-
- parent.children.push (child);
- }
-
- return parent;
- },
-
- tree: function(element) {
- element = $(element);
- var sortableOptions = this.options(element);
- var options = Object.extend({
- tag: sortableOptions.tag,
- treeTag: sortableOptions.treeTag,
- only: sortableOptions.only,
- name: element.id,
- format: sortableOptions.format
- }, arguments[1] || { });
-
- var root = {
- id: null,
- parent: null,
- children: [],
- container: element,
- position: 0
- }
-
- return Sortable._tree(element, options, root);
- },
-
- /* Construct a [i] index for a particular node */
- _constructIndex: function(node) {
- var index = '';
- do {
- if (node.id) index = '[' + node.position + ']' + index;
- } while ((node = node.parent) != null);
- return index;
- },
-
- sequence: function(element) {
- element = $(element);
- var options = Object.extend(this.options(element), arguments[1] || { });
-
- return $(this.findElements(element, options) || []).map( function(item) {
- return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
- });
- },
-
- setSequence: function(element, new_sequence) {
- element = $(element);
- var options = Object.extend(this.options(element), arguments[2] || { });
-
- var nodeMap = { };
- this.findElements(element, options).each( function(n) {
- if (n.id.match(options.format))
- nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
- n.parentNode.removeChild(n);
- });
-
- new_sequence.each(function(ident) {
- var n = nodeMap[ident];
- if (n) {
- n[1].appendChild(n[0]);
- delete nodeMap[ident];
- }
- });
- },
-
- serialize: function(element) {
- element = $(element);
- var options = Object.extend(Sortable.options(element), arguments[1] || { });
- var name = encodeURIComponent(
- (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
-
- if (options.tree) {
- return Sortable.tree(element, arguments[1]).children.map( function (item) {
- return [name + Sortable._constructIndex(item) + "[id]=" +
- encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
- }).flatten().join('&');
- } else {
- return Sortable.sequence(element, arguments[1]).map( function(item) {
- return name + "[]=" + encodeURIComponent(item);
- }).join('&');
- }
- }
-}
-
-// Returns true if child is contained within element
-Element.isParent = function(child, element) {
- if (!child.parentNode || child == element) return false;
- if (child.parentNode == element) return true;
- return Element.isParent(child.parentNode, element);
-}
-
-Element.findChildren = function(element, only, recursive, tagName) {
- if(!element.hasChildNodes()) return null;
- tagName = tagName.toUpperCase();
- if(only) only = [only].flatten();
- var elements = [];
- $A(element.childNodes).each( function(e) {
- if(e.tagName && e.tagName.toUpperCase()==tagName &&
- (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
- elements.push(e);
- if(recursive) {
- var grandchildren = Element.findChildren(e, only, recursive, tagName);
- if(grandchildren) elements.push(grandchildren);
- }
- });
-
- return (elements.length>0 ? elements.flatten() : []);
-}
-
-Element.offsetSize = function (element, type) {
- return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
-}
diff --git a/actionpack/lib/action_view/helpers/javascripts/effects.js b/actionpack/lib/action_view/helpers/javascripts/effects.js
deleted file mode 100644
index f030b5dbe9..0000000000
--- a/actionpack/lib/action_view/helpers/javascripts/effects.js
+++ /dev/null
@@ -1,1120 +0,0 @@
-// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// Contributors:
-// Justin Palmer (http://encytemedia.com/)
-// Mark Pilgrim (http://diveintomark.org/)
-// Martin Bialasinki
-//
-// script.aculo.us is freely distributable under the terms of an MIT-style license.
-// For details, see the script.aculo.us web site: http://script.aculo.us/
-
-// converts rgb() and #xxx to #xxxxxx format,
-// returns self (or first argument) if not convertable
-String.prototype.parseColor = function() {
- var color = '#';
- if (this.slice(0,4) == 'rgb(') {
- var cols = this.slice(4,this.length-1).split(',');
- var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
- } else {
- if (this.slice(0,1) == '#') {
- if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
- if (this.length==7) color = this.toLowerCase();
- }
- }
- return (color.length==7 ? color : (arguments[0] || this));
-};
-
-/*--------------------------------------------------------------------------*/
-
-Element.collectTextNodes = function(element) {
- return $A($(element).childNodes).collect( function(node) {
- return (node.nodeType==3 ? node.nodeValue :
- (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
- }).flatten().join('');
-};
-
-Element.collectTextNodesIgnoreClass = function(element, className) {
- return $A($(element).childNodes).collect( function(node) {
- return (node.nodeType==3 ? node.nodeValue :
- ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
- Element.collectTextNodesIgnoreClass(node, className) : ''));
- }).flatten().join('');
-};
-
-Element.setContentZoom = function(element, percent) {
- element = $(element);
- element.setStyle({fontSize: (percent/100) + 'em'});
- if (Prototype.Browser.WebKit) window.scrollBy(0,0);
- return element;
-};
-
-Element.getInlineOpacity = function(element){
- return $(element).style.opacity || '';
-};
-
-Element.forceRerendering = function(element) {
- try {
- element = $(element);
- var n = document.createTextNode(' ');
- element.appendChild(n);
- element.removeChild(n);
- } catch(e) { }
-};
-
-/*--------------------------------------------------------------------------*/
-
-var Effect = {
- _elementDoesNotExistError: {
- name: 'ElementDoesNotExistError',
- message: 'The specified DOM element does not exist, but is required for this effect to operate'
- },
- Transitions: {
- linear: Prototype.K,
- sinoidal: function(pos) {
- return (-Math.cos(pos*Math.PI)/2) + 0.5;
- },
- reverse: function(pos) {
- return 1-pos;
- },
- flicker: function(pos) {
- var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
- return pos > 1 ? 1 : pos;
- },
- wobble: function(pos) {
- return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
- },
- pulse: function(pos, pulses) {
- pulses = pulses || 5;
- return (
- ((pos % (1/pulses)) * pulses).round() == 0 ?
- ((pos * pulses * 2) - (pos * pulses * 2).floor()) :
- 1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
- );
- },
- spring: function(pos) {
- return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
- },
- none: function(pos) {
- return 0;
- },
- full: function(pos) {
- return 1;
- }
- },
- DefaultOptions: {
- duration: 1.0, // seconds
- fps: 100, // 100= assume 66fps max.
- sync: false, // true for combining
- from: 0.0,
- to: 1.0,
- delay: 0.0,
- queue: 'parallel'
- },
- tagifyText: function(element) {
- var tagifyStyle = 'position:relative';
- if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
-
- element = $(element);
- $A(element.childNodes).each( function(child) {
- if (child.nodeType==3) {
- child.nodeValue.toArray().each( function(character) {
- element.insertBefore(
- new Element('span', {style: tagifyStyle}).update(
- character == ' ' ? String.fromCharCode(160) : character),
- child);
- });
- Element.remove(child);
- }
- });
- },
- multiple: function(element, effect) {
- var elements;
- if (((typeof element == 'object') ||
- Object.isFunction(element)) &&
- (element.length))
- elements = element;
- else
- elements = $(element).childNodes;
-
- var options = Object.extend({
- speed: 0.1,
- delay: 0.0
- }, arguments[2] || { });
- var masterDelay = options.delay;
-
- $A(elements).each( function(element, index) {
- new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
- });
- },
- PAIRS: {
- 'slide': ['SlideDown','SlideUp'],
- 'blind': ['BlindDown','BlindUp'],
- 'appear': ['Appear','Fade']
- },
- toggle: function(element, effect) {
- element = $(element);
- effect = (effect || 'appear').toLowerCase();
- var options = Object.extend({
- queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
- }, arguments[2] || { });
- Effect[element.visible() ?
- Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
- }
-};
-
-Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
-
-/* ------------- core effects ------------- */
-
-Effect.ScopedQueue = Class.create(Enumerable, {
- initialize: function() {
- this.effects = [];
- this.interval = null;
- },
- _each: function(iterator) {
- this.effects._each(iterator);
- },
- add: function(effect) {
- var timestamp = new Date().getTime();
-
- var position = Object.isString(effect.options.queue) ?
- effect.options.queue : effect.options.queue.position;
-
- switch(position) {
- case 'front':
- // move unstarted effects after this effect
- this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
- e.startOn += effect.finishOn;
- e.finishOn += effect.finishOn;
- });
- break;
- case 'with-last':
- timestamp = this.effects.pluck('startOn').max() || timestamp;
- break;
- case 'end':
- // start effect after last queued effect has finished
- timestamp = this.effects.pluck('finishOn').max() || timestamp;
- break;
- }
-
- effect.startOn += timestamp;
- effect.finishOn += timestamp;
-
- if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
- this.effects.push(effect);
-
- if (!this.interval)
- this.interval = setInterval(this.loop.bind(this), 15);
- },
- remove: function(effect) {
- this.effects = this.effects.reject(function(e) { return e==effect });
- if (this.effects.length == 0) {
- clearInterval(this.interval);
- this.interval = null;
- }
- },
- loop: function() {
- var timePos = new Date().getTime();
- for(var i=0, len=this.effects.length;i<len;i++)
- this.effects[i] && this.effects[i].loop(timePos);
- }
-});
-
-Effect.Queues = {
- instances: $H(),
- get: function(queueName) {
- if (!Object.isString(queueName)) return queueName;
-
- return this.instances.get(queueName) ||
- this.instances.set(queueName, new Effect.ScopedQueue());
- }
-};
-Effect.Queue = Effect.Queues.get('global');
-
-Effect.Base = Class.create({
- position: null,
- start: function(options) {
- function codeForEvent(options,eventName){
- return (
- (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
- (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
- );
- }
- if (options && options.transition === false) options.transition = Effect.Transitions.linear;
- this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
- this.currentFrame = 0;
- this.state = 'idle';
- this.startOn = this.options.delay*1000;
- this.finishOn = this.startOn+(this.options.duration*1000);
- this.fromToDelta = this.options.to-this.options.from;
- this.totalTime = this.finishOn-this.startOn;
- this.totalFrames = this.options.fps*this.options.duration;
-
- eval('this.render = function(pos){ '+
- 'if (this.state=="idle"){this.state="running";'+
- codeForEvent(this.options,'beforeSetup')+
- (this.setup ? 'this.setup();':'')+
- codeForEvent(this.options,'afterSetup')+
- '};if (this.state=="running"){'+
- 'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
- 'this.position=pos;'+
- codeForEvent(this.options,'beforeUpdate')+
- (this.update ? 'this.update(pos);':'')+
- codeForEvent(this.options,'afterUpdate')+
- '}}');
-
- this.event('beforeStart');
- if (!this.options.sync)
- Effect.Queues.get(Object.isString(this.options.queue) ?
- 'global' : this.options.queue.scope).add(this);
- },
- loop: function(timePos) {
- if (timePos >= this.startOn) {
- if (timePos >= this.finishOn) {
- this.render(1.0);
- this.cancel();
- this.event('beforeFinish');
- if (this.finish) this.finish();
- this.event('afterFinish');
- return;
- }
- var pos = (timePos - this.startOn) / this.totalTime,
- frame = (pos * this.totalFrames).round();
- if (frame > this.currentFrame) {
- this.render(pos);
- this.currentFrame = frame;
- }
- }
- },
- cancel: function() {
- if (!this.options.sync)
- Effect.Queues.get(Object.isString(this.options.queue) ?
- 'global' : this.options.queue.scope).remove(this);
- this.state = 'finished';
- },
- event: function(eventName) {
- if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
- if (this.options[eventName]) this.options[eventName](this);
- },
- inspect: function() {
- var data = $H();
- for(property in this)
- if (!Object.isFunction(this[property])) data.set(property, this[property]);
- return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
- }
-});
-
-Effect.Parallel = Class.create(Effect.Base, {
- initialize: function(effects) {
- this.effects = effects || [];
- this.start(arguments[1]);
- },
- update: function(position) {
- this.effects.invoke('render', position);
- },
- finish: function(position) {
- this.effects.each( function(effect) {
- effect.render(1.0);
- effect.cancel();
- effect.event('beforeFinish');
- if (effect.finish) effect.finish(position);
- effect.event('afterFinish');
- });
- }
-});
-
-Effect.Tween = Class.create(Effect.Base, {
- initialize: function(object, from, to) {
- object = Object.isString(object) ? $(object) : object;
- var args = $A(arguments), method = args.last(),
- options = args.length == 5 ? args[3] : null;
- this.method = Object.isFunction(method) ? method.bind(object) :
- Object.isFunction(object[method]) ? object[method].bind(object) :
- function(value) { object[method] = value };
- this.start(Object.extend({ from: from, to: to }, options || { }));
- },
- update: function(position) {
- this.method(position);
- }
-});
-
-Effect.Event = Class.create(Effect.Base, {
- initialize: function() {
- this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
- },
- update: Prototype.emptyFunction
-});
-
-Effect.Opacity = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- // make this work on IE on elements without 'layout'
- if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
- this.element.setStyle({zoom: 1});
- var options = Object.extend({
- from: this.element.getOpacity() || 0.0,
- to: 1.0
- }, arguments[1] || { });
- this.start(options);
- },
- update: function(position) {
- this.element.setOpacity(position);
- }
-});
-
-Effect.Move = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({
- x: 0,
- y: 0,
- mode: 'relative'
- }, arguments[1] || { });
- this.start(options);
- },
- setup: function() {
- this.element.makePositioned();
- this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
- this.originalTop = parseFloat(this.element.getStyle('top') || '0');
- if (this.options.mode == 'absolute') {
- this.options.x = this.options.x - this.originalLeft;
- this.options.y = this.options.y - this.originalTop;
- }
- },
- update: function(position) {
- this.element.setStyle({
- left: (this.options.x * position + this.originalLeft).round() + 'px',
- top: (this.options.y * position + this.originalTop).round() + 'px'
- });
- }
-});
-
-// for backwards compatibility
-Effect.MoveBy = function(element, toTop, toLeft) {
- return new Effect.Move(element,
- Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
-};
-
-Effect.Scale = Class.create(Effect.Base, {
- initialize: function(element, percent) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({
- scaleX: true,
- scaleY: true,
- scaleContent: true,
- scaleFromCenter: false,
- scaleMode: 'box', // 'box' or 'contents' or { } with provided values
- scaleFrom: 100.0,
- scaleTo: percent
- }, arguments[2] || { });
- this.start(options);
- },
- setup: function() {
- this.restoreAfterFinish = this.options.restoreAfterFinish || false;
- this.elementPositioning = this.element.getStyle('position');
-
- this.originalStyle = { };
- ['top','left','width','height','fontSize'].each( function(k) {
- this.originalStyle[k] = this.element.style[k];
- }.bind(this));
-
- this.originalTop = this.element.offsetTop;
- this.originalLeft = this.element.offsetLeft;
-
- var fontSize = this.element.getStyle('font-size') || '100%';
- ['em','px','%','pt'].each( function(fontSizeType) {
- if (fontSize.indexOf(fontSizeType)>0) {
- this.fontSize = parseFloat(fontSize);
- this.fontSizeType = fontSizeType;
- }
- }.bind(this));
-
- this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
-
- this.dims = null;
- if (this.options.scaleMode=='box')
- this.dims = [this.element.offsetHeight, this.element.offsetWidth];
- if (/^content/.test(this.options.scaleMode))
- this.dims = [this.element.scrollHeight, this.element.scrollWidth];
- if (!this.dims)
- this.dims = [this.options.scaleMode.originalHeight,
- this.options.scaleMode.originalWidth];
- },
- update: function(position) {
- var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
- if (this.options.scaleContent && this.fontSize)
- this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
- this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
- },
- finish: function(position) {
- if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
- },
- setDimensions: function(height, width) {
- var d = { };
- if (this.options.scaleX) d.width = width.round() + 'px';
- if (this.options.scaleY) d.height = height.round() + 'px';
- if (this.options.scaleFromCenter) {
- var topd = (height - this.dims[0])/2;
- var leftd = (width - this.dims[1])/2;
- if (this.elementPositioning == 'absolute') {
- if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
- if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
- } else {
- if (this.options.scaleY) d.top = -topd + 'px';
- if (this.options.scaleX) d.left = -leftd + 'px';
- }
- }
- this.element.setStyle(d);
- }
-});
-
-Effect.Highlight = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
- this.start(options);
- },
- setup: function() {
- // Prevent executing on elements not in the layout flow
- if (this.element.getStyle('display')=='none') { this.cancel(); return; }
- // Disable background image during the effect
- this.oldStyle = { };
- if (!this.options.keepBackgroundImage) {
- this.oldStyle.backgroundImage = this.element.getStyle('background-image');
- this.element.setStyle({backgroundImage: 'none'});
- }
- if (!this.options.endcolor)
- this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
- if (!this.options.restorecolor)
- this.options.restorecolor = this.element.getStyle('background-color');
- // init color calculations
- this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
- this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
- },
- update: function(position) {
- this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
- return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
- },
- finish: function() {
- this.element.setStyle(Object.extend(this.oldStyle, {
- backgroundColor: this.options.restorecolor
- }));
- }
-});
-
-Effect.ScrollTo = function(element) {
- var options = arguments[1] || { },
- scrollOffsets = document.viewport.getScrollOffsets(),
- elementOffsets = $(element).cumulativeOffset(),
- max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();
-
- if (options.offset) elementOffsets[1] += options.offset;
-
- return new Effect.Tween(null,
- scrollOffsets.top,
- elementOffsets[1] > max ? max : elementOffsets[1],
- options,
- function(p){ scrollTo(scrollOffsets.left, p.round()) }
- );
-};
-
-/* ------------- combination effects ------------- */
-
-Effect.Fade = function(element) {
- element = $(element);
- var oldOpacity = element.getInlineOpacity();
- var options = Object.extend({
- from: element.getOpacity() || 1.0,
- to: 0.0,
- afterFinishInternal: function(effect) {
- if (effect.options.to!=0) return;
- effect.element.hide().setStyle({opacity: oldOpacity});
- }
- }, arguments[1] || { });
- return new Effect.Opacity(element,options);
-};
-
-Effect.Appear = function(element) {
- element = $(element);
- var options = Object.extend({
- from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
- to: 1.0,
- // force Safari to render floated elements properly
- afterFinishInternal: function(effect) {
- effect.element.forceRerendering();
- },
- beforeSetup: function(effect) {
- effect.element.setOpacity(effect.options.from).show();
- }}, arguments[1] || { });
- return new Effect.Opacity(element,options);
-};
-
-Effect.Puff = function(element) {
- element = $(element);
- var oldStyle = {
- opacity: element.getInlineOpacity(),
- position: element.getStyle('position'),
- top: element.style.top,
- left: element.style.left,
- width: element.style.width,
- height: element.style.height
- };
- return new Effect.Parallel(
- [ new Effect.Scale(element, 200,
- { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
- new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
- Object.extend({ duration: 1.0,
- beforeSetupInternal: function(effect) {
- Position.absolutize(effect.effects[0].element)
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.hide().setStyle(oldStyle); }
- }, arguments[1] || { })
- );
-};
-
-Effect.BlindUp = function(element) {
- element = $(element);
- element.makeClipping();
- return new Effect.Scale(element, 0,
- Object.extend({ scaleContent: false,
- scaleX: false,
- restoreAfterFinish: true,
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping();
- }
- }, arguments[1] || { })
- );
-};
-
-Effect.BlindDown = function(element) {
- element = $(element);
- var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, 100, Object.extend({
- scaleContent: false,
- scaleX: false,
- scaleFrom: 0,
- scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
- restoreAfterFinish: true,
- afterSetup: function(effect) {
- effect.element.makeClipping().setStyle({height: '0px'}).show();
- },
- afterFinishInternal: function(effect) {
- effect.element.undoClipping();
- }
- }, arguments[1] || { }));
-};
-
-Effect.SwitchOff = function(element) {
- element = $(element);
- var oldOpacity = element.getInlineOpacity();
- return new Effect.Appear(element, Object.extend({
- duration: 0.4,
- from: 0,
- transition: Effect.Transitions.flicker,
- afterFinishInternal: function(effect) {
- new Effect.Scale(effect.element, 1, {
- duration: 0.3, scaleFromCenter: true,
- scaleX: false, scaleContent: false, restoreAfterFinish: true,
- beforeSetup: function(effect) {
- effect.element.makePositioned().makeClipping();
- },
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
- }
- })
- }
- }, arguments[1] || { }));
-};
-
-Effect.DropOut = function(element) {
- element = $(element);
- var oldStyle = {
- top: element.getStyle('top'),
- left: element.getStyle('left'),
- opacity: element.getInlineOpacity() };
- return new Effect.Parallel(
- [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
- new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
- Object.extend(
- { duration: 0.5,
- beforeSetup: function(effect) {
- effect.effects[0].element.makePositioned();
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
- }
- }, arguments[1] || { }));
-};
-
-Effect.Shake = function(element) {
- element = $(element);
- var options = Object.extend({
- distance: 20,
- duration: 0.5
- }, arguments[1] || {});
- var distance = parseFloat(options.distance);
- var split = parseFloat(options.duration) / 10.0;
- var oldStyle = {
- top: element.getStyle('top'),
- left: element.getStyle('left') };
- return new Effect.Move(element,
- { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
- effect.element.undoPositioned().setStyle(oldStyle);
- }}) }}) }}) }}) }}) }});
-};
-
-Effect.SlideDown = function(element) {
- element = $(element).cleanWhitespace();
- // SlideDown need to have the content of the element wrapped in a container element with fixed height!
- var oldInnerBottom = element.down().getStyle('bottom');
- var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, 100, Object.extend({
- scaleContent: false,
- scaleX: false,
- scaleFrom: window.opera ? 0 : 1,
- scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
- restoreAfterFinish: true,
- afterSetup: function(effect) {
- effect.element.makePositioned();
- effect.element.down().makePositioned();
- if (window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping().setStyle({height: '0px'}).show();
- },
- afterUpdateInternal: function(effect) {
- effect.element.down().setStyle({bottom:
- (effect.dims[0] - effect.element.clientHeight) + 'px' });
- },
- afterFinishInternal: function(effect) {
- effect.element.undoClipping().undoPositioned();
- effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
- }, arguments[1] || { })
- );
-};
-
-Effect.SlideUp = function(element) {
- element = $(element).cleanWhitespace();
- var oldInnerBottom = element.down().getStyle('bottom');
- var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, window.opera ? 0 : 1,
- Object.extend({ scaleContent: false,
- scaleX: false,
- scaleMode: 'box',
- scaleFrom: 100,
- scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
- restoreAfterFinish: true,
- afterSetup: function(effect) {
- effect.element.makePositioned();
- effect.element.down().makePositioned();
- if (window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping().show();
- },
- afterUpdateInternal: function(effect) {
- effect.element.down().setStyle({bottom:
- (effect.dims[0] - effect.element.clientHeight) + 'px' });
- },
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping().undoPositioned();
- effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
- }
- }, arguments[1] || { })
- );
-};
-
-// Bug in opera makes the TD containing this element expand for a instance after finish
-Effect.Squish = function(element) {
- return new Effect.Scale(element, window.opera ? 1 : 0, {
- restoreAfterFinish: true,
- beforeSetup: function(effect) {
- effect.element.makeClipping();
- },
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping();
- }
- });
-};
-
-Effect.Grow = function(element) {
- element = $(element);
- var options = Object.extend({
- direction: 'center',
- moveTransition: Effect.Transitions.sinoidal,
- scaleTransition: Effect.Transitions.sinoidal,
- opacityTransition: Effect.Transitions.full
- }, arguments[1] || { });
- var oldStyle = {
- top: element.style.top,
- left: element.style.left,
- height: element.style.height,
- width: element.style.width,
- opacity: element.getInlineOpacity() };
-
- var dims = element.getDimensions();
- var initialMoveX, initialMoveY;
- var moveX, moveY;
-
- switch (options.direction) {
- case 'top-left':
- initialMoveX = initialMoveY = moveX = moveY = 0;
- break;
- case 'top-right':
- initialMoveX = dims.width;
- initialMoveY = moveY = 0;
- moveX = -dims.width;
- break;
- case 'bottom-left':
- initialMoveX = moveX = 0;
- initialMoveY = dims.height;
- moveY = -dims.height;
- break;
- case 'bottom-right':
- initialMoveX = dims.width;
- initialMoveY = dims.height;
- moveX = -dims.width;
- moveY = -dims.height;
- break;
- case 'center':
- initialMoveX = dims.width / 2;
- initialMoveY = dims.height / 2;
- moveX = -dims.width / 2;
- moveY = -dims.height / 2;
- break;
- }
-
- return new Effect.Move(element, {
- x: initialMoveX,
- y: initialMoveY,
- duration: 0.01,
- beforeSetup: function(effect) {
- effect.element.hide().makeClipping().makePositioned();
- },
- afterFinishInternal: function(effect) {
- new Effect.Parallel(
- [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
- new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
- new Effect.Scale(effect.element, 100, {
- scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
- sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
- ], Object.extend({
- beforeSetup: function(effect) {
- effect.effects[0].element.setStyle({height: '0px'}).show();
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
- }
- }, options)
- )
- }
- });
-};
-
-Effect.Shrink = function(element) {
- element = $(element);
- var options = Object.extend({
- direction: 'center',
- moveTransition: Effect.Transitions.sinoidal,
- scaleTransition: Effect.Transitions.sinoidal,
- opacityTransition: Effect.Transitions.none
- }, arguments[1] || { });
- var oldStyle = {
- top: element.style.top,
- left: element.style.left,
- height: element.style.height,
- width: element.style.width,
- opacity: element.getInlineOpacity() };
-
- var dims = element.getDimensions();
- var moveX, moveY;
-
- switch (options.direction) {
- case 'top-left':
- moveX = moveY = 0;
- break;
- case 'top-right':
- moveX = dims.width;
- moveY = 0;
- break;
- case 'bottom-left':
- moveX = 0;
- moveY = dims.height;
- break;
- case 'bottom-right':
- moveX = dims.width;
- moveY = dims.height;
- break;
- case 'center':
- moveX = dims.width / 2;
- moveY = dims.height / 2;
- break;
- }
-
- return new Effect.Parallel(
- [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
- new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
- new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
- ], Object.extend({
- beforeStartInternal: function(effect) {
- effect.effects[0].element.makePositioned().makeClipping();
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
- }, options)
- );
-};
-
-Effect.Pulsate = function(element) {
- element = $(element);
- var options = arguments[1] || { };
- var oldOpacity = element.getInlineOpacity();
- var transition = options.transition || Effect.Transitions.sinoidal;
- var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
- reverser.bind(transition);
- return new Effect.Opacity(element,
- Object.extend(Object.extend({ duration: 2.0, from: 0,
- afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
- }, options), {transition: reverser}));
-};
-
-Effect.Fold = function(element) {
- element = $(element);
- var oldStyle = {
- top: element.style.top,
- left: element.style.left,
- width: element.style.width,
- height: element.style.height };
- element.makeClipping();
- return new Effect.Scale(element, 5, Object.extend({
- scaleContent: false,
- scaleX: false,
- afterFinishInternal: function(effect) {
- new Effect.Scale(element, 1, {
- scaleContent: false,
- scaleY: false,
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping().setStyle(oldStyle);
- } });
- }}, arguments[1] || { }));
-};
-
-Effect.Morph = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({
- style: { }
- }, arguments[1] || { });
-
- if (!Object.isString(options.style)) this.style = $H(options.style);
- else {
- if (options.style.include(':'))
- this.style = options.style.parseStyle();
- else {
- this.element.addClassName(options.style);
- this.style = $H(this.element.getStyles());
- this.element.removeClassName(options.style);
- var css = this.element.getStyles();
- this.style = this.style.reject(function(style) {
- return style.value == css[style.key];
- });
- options.afterFinishInternal = function(effect) {
- effect.element.addClassName(effect.options.style);
- effect.transforms.each(function(transform) {
- effect.element.style[transform.style] = '';
- });
- }
- }
- }
- this.start(options);
- },
-
- setup: function(){
- function parseColor(color){
- if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
- color = color.parseColor();
- return $R(0,2).map(function(i){
- return parseInt( color.slice(i*2+1,i*2+3), 16 )
- });
- }
- this.transforms = this.style.map(function(pair){
- var property = pair[0], value = pair[1], unit = null;
-
- if (value.parseColor('#zzzzzz') != '#zzzzzz') {
- value = value.parseColor();
- unit = 'color';
- } else if (property == 'opacity') {
- value = parseFloat(value);
- if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
- this.element.setStyle({zoom: 1});
- } else if (Element.CSS_LENGTH.test(value)) {
- var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
- value = parseFloat(components[1]);
- unit = (components.length == 3) ? components[2] : null;
- }
-
- var originalValue = this.element.getStyle(property);
- return {
- style: property.camelize(),
- originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
- targetValue: unit=='color' ? parseColor(value) : value,
- unit: unit
- };
- }.bind(this)).reject(function(transform){
- return (
- (transform.originalValue == transform.targetValue) ||
- (
- transform.unit != 'color' &&
- (isNaN(transform.originalValue) || isNaN(transform.targetValue))
- )
- )
- });
- },
- update: function(position) {
- var style = { }, transform, i = this.transforms.length;
- while(i--)
- style[(transform = this.transforms[i]).style] =
- transform.unit=='color' ? '#'+
- (Math.round(transform.originalValue[0]+
- (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
- (Math.round(transform.originalValue[1]+
- (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
- (Math.round(transform.originalValue[2]+
- (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
- (transform.originalValue +
- (transform.targetValue - transform.originalValue) * position).toFixed(3) +
- (transform.unit === null ? '' : transform.unit);
- this.element.setStyle(style, true);
- }
-});
-
-Effect.Transform = Class.create({
- initialize: function(tracks){
- this.tracks = [];
- this.options = arguments[1] || { };
- this.addTracks(tracks);
- },
- addTracks: function(tracks){
- tracks.each(function(track){
- track = $H(track);
- var data = track.values().first();
- this.tracks.push($H({
- ids: track.keys().first(),
- effect: Effect.Morph,
- options: { style: data }
- }));
- }.bind(this));
- return this;
- },
- play: function(){
- return new Effect.Parallel(
- this.tracks.map(function(track){
- var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
- var elements = [$(ids) || $$(ids)].flatten();
- return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
- }).flatten(),
- this.options
- );
- }
-});
-
-Element.CSS_PROPERTIES = $w(
- 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
- 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
- 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
- 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
- 'fontSize fontWeight height left letterSpacing lineHeight ' +
- 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
- 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
- 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
- 'right textIndent top width wordSpacing zIndex');
-
-Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
-
-String.__parseStyleElement = document.createElement('div');
-String.prototype.parseStyle = function(){
- var style, styleRules = $H();
- if (Prototype.Browser.WebKit)
- style = new Element('div',{style:this}).style;
- else {
- String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
- style = String.__parseStyleElement.childNodes[0].style;
- }
-
- Element.CSS_PROPERTIES.each(function(property){
- if (style[property]) styleRules.set(property, style[property]);
- });
-
- if (Prototype.Browser.IE && this.include('opacity'))
- styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
-
- return styleRules;
-};
-
-if (document.defaultView && document.defaultView.getComputedStyle) {
- Element.getStyles = function(element) {
- var css = document.defaultView.getComputedStyle($(element), null);
- return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
- styles[property] = css[property];
- return styles;
- });
- };
-} else {
- Element.getStyles = function(element) {
- element = $(element);
- var css = element.currentStyle, styles;
- styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) {
- hash.set(property, css[property]);
- return hash;
- });
- if (!styles.opacity) styles.set('opacity', element.getOpacity());
- return styles;
- };
-};
-
-Effect.Methods = {
- morph: function(element, style) {
- element = $(element);
- new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
- return element;
- },
- visualEffect: function(element, effect, options) {
- element = $(element)
- var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
- new Effect[klass](element, options);
- return element;
- },
- highlight: function(element, options) {
- element = $(element);
- new Effect.Highlight(element, options);
- return element;
- }
-};
-
-$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
- 'pulsate shake puff squish switchOff dropOut').each(
- function(effect) {
- Effect.Methods[effect] = function(element, options){
- element = $(element);
- Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
- return element;
- }
- }
-);
-
-$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
- function(f) { Effect.Methods[f] = Element[f]; }
-);
-
-Element.addMethods(Effect.Methods);
diff --git a/actionpack/lib/action_view/helpers/javascripts/prototype.js b/actionpack/lib/action_view/helpers/javascripts/prototype.js
deleted file mode 100644
index 2c70b8a7e8..0000000000
--- a/actionpack/lib/action_view/helpers/javascripts/prototype.js
+++ /dev/null
@@ -1,4221 +0,0 @@
-/* Prototype JavaScript framework, version 1.6.0.2
- * (c) 2005-2008 Sam Stephenson
- *
- * Prototype is freely distributable under the terms of an MIT-style license.
- * For details, see the Prototype web site: http://www.prototypejs.org/
- *
- *--------------------------------------------------------------------------*/
-
-var Prototype = {
- Version: '1.6.0.2',
-
- Browser: {
- IE: !!(window.attachEvent && !window.opera),
- Opera: !!window.opera,
- WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
- Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
- MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
- },
-
- BrowserFeatures: {
- XPath: !!document.evaluate,
- ElementExtensions: !!window.HTMLElement,
- SpecificElementExtensions:
- document.createElement('div').__proto__ &&
- document.createElement('div').__proto__ !==
- document.createElement('form').__proto__
- },
-
- ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
- JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
-
- emptyFunction: function() { },
- K: function(x) { return x }
-};
-
-if (Prototype.Browser.MobileSafari)
- Prototype.BrowserFeatures.SpecificElementExtensions = false;
-
-
-/* Based on Alex Arnell's inheritance implementation. */
-var Class = {
- create: function() {
- var parent = null, properties = $A(arguments);
- if (Object.isFunction(properties[0]))
- parent = properties.shift();
-
- function klass() {
- this.initialize.apply(this, arguments);
- }
-
- Object.extend(klass, Class.Methods);
- klass.superclass = parent;
- klass.subclasses = [];
-
- if (parent) {
- var subclass = function() { };
- subclass.prototype = parent.prototype;
- klass.prototype = new subclass;
- parent.subclasses.push(klass);
- }
-
- for (var i = 0; i < properties.length; i++)
- klass.addMethods(properties[i]);
-
- if (!klass.prototype.initialize)
- klass.prototype.initialize = Prototype.emptyFunction;
-
- klass.prototype.constructor = klass;
-
- return klass;
- }
-};
-
-Class.Methods = {
- addMethods: function(source) {
- var ancestor = this.superclass && this.superclass.prototype;
- var properties = Object.keys(source);
-
- if (!Object.keys({ toString: true }).length)
- properties.push("toString", "valueOf");
-
- for (var i = 0, length = properties.length; i < length; i++) {
- var property = properties[i], value = source[property];
- if (ancestor && Object.isFunction(value) &&
- value.argumentNames().first() == "$super") {
- var method = value, value = Object.extend((function(m) {
- return function() { return ancestor[m].apply(this, arguments) };
- })(property).wrap(method), {
- valueOf: function() { return method },
- toString: function() { return method.toString() }
- });
- }
- this.prototype[property] = value;
- }
-
- return this;
- }
-};
-
-var Abstract = { };
-
-Object.extend = function(destination, source) {
- for (var property in source)
- destination[property] = source[property];
- return destination;
-};
-
-Object.extend(Object, {
- inspect: function(object) {
- try {
- if (Object.isUndefined(object)) return 'undefined';
- if (object === null) return 'null';
- return object.inspect ? object.inspect() : String(object);
- } catch (e) {
- if (e instanceof RangeError) return '...';
- throw e;
- }
- },
-
- toJSON: function(object) {
- var type = typeof object;
- switch (type) {
- case 'undefined':
- case 'function':
- case 'unknown': return;
- case 'boolean': return object.toString();
- }
-
- if (object === null) return 'null';
- if (object.toJSON) return object.toJSON();
- if (Object.isElement(object)) return;
-
- var results = [];
- for (var property in object) {
- var value = Object.toJSON(object[property]);
- if (!Object.isUndefined(value))
- results.push(property.toJSON() + ': ' + value);
- }
-
- return '{' + results.join(', ') + '}';
- },
-
- toQueryString: function(object) {
- return $H(object).toQueryString();
- },
-
- toHTML: function(object) {
- return object && object.toHTML ? object.toHTML() : String.interpret(object);
- },
-
- keys: function(object) {
- var keys = [];
- for (var property in object)
- keys.push(property);
- return keys;
- },
-
- values: function(object) {
- var values = [];
- for (var property in object)
- values.push(object[property]);
- return values;
- },
-
- clone: function(object) {
- return Object.extend({ }, object);
- },
-
- isElement: function(object) {
- return object && object.nodeType == 1;
- },
-
- isArray: function(object) {
- return object != null && typeof object == "object" &&
- 'splice' in object && 'join' in object;
- },
-
- isHash: function(object) {
- return object instanceof Hash;
- },
-
- isFunction: function(object) {
- return typeof object == "function";
- },
-
- isString: function(object) {
- return typeof object == "string";
- },
-
- isNumber: function(object) {
- return typeof object == "number";
- },
-
- isUndefined: function(object) {
- return typeof object == "undefined";
- }
-});
-
-Object.extend(Function.prototype, {
- argumentNames: function() {
- var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
- return names.length == 1 && !names[0] ? [] : names;
- },
-
- bind: function() {
- if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
- var __method = this, args = $A(arguments), object = args.shift();
- return function() {
- return __method.apply(object, args.concat($A(arguments)));
- }
- },
-
- bindAsEventListener: function() {
- var __method = this, args = $A(arguments), object = args.shift();
- return function(event) {
- return __method.apply(object, [event || window.event].concat(args));
- }
- },
-
- curry: function() {
- if (!arguments.length) return this;
- var __method = this, args = $A(arguments);
- return function() {
- return __method.apply(this, args.concat($A(arguments)));
- }
- },
-
- delay: function() {
- var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
- return window.setTimeout(function() {
- return __method.apply(__method, args);
- }, timeout);
- },
-
- wrap: function(wrapper) {
- var __method = this;
- return function() {
- return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
- }
- },
-
- methodize: function() {
- if (this._methodized) return this._methodized;
- var __method = this;
- return this._methodized = function() {
- return __method.apply(null, [this].concat($A(arguments)));
- };
- }
-});
-
-Function.prototype.defer = Function.prototype.delay.curry(0.01);
-
-Date.prototype.toJSON = function() {
- return '"' + this.getUTCFullYear() + '-' +
- (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
- this.getUTCDate().toPaddedString(2) + 'T' +
- this.getUTCHours().toPaddedString(2) + ':' +
- this.getUTCMinutes().toPaddedString(2) + ':' +
- this.getUTCSeconds().toPaddedString(2) + 'Z"';
-};
-
-var Try = {
- these: function() {
- var returnValue;
-
- for (var i = 0, length = arguments.length; i < length; i++) {
- var lambda = arguments[i];
- try {
- returnValue = lambda();
- break;
- } catch (e) { }
- }
-
- return returnValue;
- }
-};
-
-RegExp.prototype.match = RegExp.prototype.test;
-
-RegExp.escape = function(str) {
- return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
-};
-
-/*--------------------------------------------------------------------------*/
-
-var PeriodicalExecuter = Class.create({
- initialize: function(callback, frequency) {
- this.callback = callback;
- this.frequency = frequency;
- this.currentlyExecuting = false;
-
- this.registerCallback();
- },
-
- registerCallback: function() {
- this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
- },
-
- execute: function() {
- this.callback(this);
- },
-
- stop: function() {
- if (!this.timer) return;
- clearInterval(this.timer);
- this.timer = null;
- },
-
- onTimerEvent: function() {
- if (!this.currentlyExecuting) {
- try {
- this.currentlyExecuting = true;
- this.execute();
- } finally {
- this.currentlyExecuting = false;
- }
- }
- }
-});
-Object.extend(String, {
- interpret: function(value) {
- return value == null ? '' : String(value);
- },
- specialChar: {
- '\b': '\\b',
- '\t': '\\t',
- '\n': '\\n',
- '\f': '\\f',
- '\r': '\\r',
- '\\': '\\\\'
- }
-});
-
-Object.extend(String.prototype, {
- gsub: function(pattern, replacement) {
- var result = '', source = this, match;
- replacement = arguments.callee.prepareReplacement(replacement);
-
- while (source.length > 0) {
- if (match = source.match(pattern)) {
- result += source.slice(0, match.index);
- result += String.interpret(replacement(match));
- source = source.slice(match.index + match[0].length);
- } else {
- result += source, source = '';
- }
- }
- return result;
- },
-
- sub: function(pattern, replacement, count) {
- replacement = this.gsub.prepareReplacement(replacement);
- count = Object.isUndefined(count) ? 1 : count;
-
- return this.gsub(pattern, function(match) {
- if (--count < 0) return match[0];
- return replacement(match);
- });
- },
-
- scan: function(pattern, iterator) {
- this.gsub(pattern, iterator);
- return String(this);
- },
-
- truncate: function(length, truncation) {
- length = length || 30;
- truncation = Object.isUndefined(truncation) ? '...' : truncation;
- return this.length > length ?
- this.slice(0, length - truncation.length) + truncation : String(this);
- },
-
- strip: function() {
- return this.replace(/^\s+/, '').replace(/\s+$/, '');
- },
-
- stripTags: function() {
- return this.replace(/<\/?[^>]+>/gi, '');
- },
-
- stripScripts: function() {
- return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
- },
-
- extractScripts: function() {
- var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
- var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
- return (this.match(matchAll) || []).map(function(scriptTag) {
- return (scriptTag.match(matchOne) || ['', ''])[1];
- });
- },
-
- evalScripts: function() {
- return this.extractScripts().map(function(script) { return eval(script) });
- },
-
- escapeHTML: function() {
- var self = arguments.callee;
- self.text.data = this;
- return self.div.innerHTML;
- },
-
- unescapeHTML: function() {
- var div = new Element('div');
- div.innerHTML = this.stripTags();
- return div.childNodes[0] ? (div.childNodes.length > 1 ?
- $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
- div.childNodes[0].nodeValue) : '';
- },
-
- toQueryParams: function(separator) {
- var match = this.strip().match(/([^?#]*)(#.*)?$/);
- if (!match) return { };
-
- return match[1].split(separator || '&').inject({ }, function(hash, pair) {
- if ((pair = pair.split('='))[0]) {
- var key = decodeURIComponent(pair.shift());
- var value = pair.length > 1 ? pair.join('=') : pair[0];
- if (value != undefined) value = decodeURIComponent(value);
-
- if (key in hash) {
- if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
- hash[key].push(value);
- }
- else hash[key] = value;
- }
- return hash;
- });
- },
-
- toArray: function() {
- return this.split('');
- },
-
- succ: function() {
- return this.slice(0, this.length - 1) +
- String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
- },
-
- times: function(count) {
- return count < 1 ? '' : new Array(count + 1).join(this);
- },
-
- camelize: function() {
- var parts = this.split('-'), len = parts.length;
- if (len == 1) return parts[0];
-
- var camelized = this.charAt(0) == '-'
- ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
- : parts[0];
-
- for (var i = 1; i < len; i++)
- camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
-
- return camelized;
- },
-
- capitalize: function() {
- return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
- },
-
- underscore: function() {
- return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
- },
-
- dasherize: function() {
- return this.gsub(/_/,'-');
- },
-
- inspect: function(useDoubleQuotes) {
- var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
- var character = String.specialChar[match[0]];
- return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
- });
- if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
- return "'" + escapedString.replace(/'/g, '\\\'') + "'";
- },
-
- toJSON: function() {
- return this.inspect(true);
- },
-
- unfilterJSON: function(filter) {
- return this.sub(filter || Prototype.JSONFilter, '#{1}');
- },
-
- isJSON: function() {
- var str = this;
- if (str.blank()) return false;
- str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
- return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
- },
-
- evalJSON: function(sanitize) {
- var json = this.unfilterJSON();
- try {
- if (!sanitize || json.isJSON()) return eval('(' + json + ')');
- } catch (e) { }
- throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
- },
-
- include: function(pattern) {
- return this.indexOf(pattern) > -1;
- },
-
- startsWith: function(pattern) {
- return this.indexOf(pattern) === 0;
- },
-
- endsWith: function(pattern) {
- var d = this.length - pattern.length;
- return d >= 0 && this.lastIndexOf(pattern) === d;
- },
-
- empty: function() {
- return this == '';
- },
-
- blank: function() {
- return /^\s*$/.test(this);
- },
-
- interpolate: function(object, pattern) {
- return new Template(this, pattern).evaluate(object);
- }
-});
-
-if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
- escapeHTML: function() {
- return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
- },
- unescapeHTML: function() {
- return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
- }
-});
-
-String.prototype.gsub.prepareReplacement = function(replacement) {
- if (Object.isFunction(replacement)) return replacement;
- var template = new Template(replacement);
- return function(match) { return template.evaluate(match) };
-};
-
-String.prototype.parseQuery = String.prototype.toQueryParams;
-
-Object.extend(String.prototype.escapeHTML, {
- div: document.createElement('div'),
- text: document.createTextNode('')
-});
-
-with (String.prototype.escapeHTML) div.appendChild(text);
-
-var Template = Class.create({
- initialize: function(template, pattern) {
- this.template = template.toString();
- this.pattern = pattern || Template.Pattern;
- },
-
- evaluate: function(object) {
- if (Object.isFunction(object.toTemplateReplacements))
- object = object.toTemplateReplacements();
-
- return this.template.gsub(this.pattern, function(match) {
- if (object == null) return '';
-
- var before = match[1] || '';
- if (before == '\\') return match[2];
-
- var ctx = object, expr = match[3];
- var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
- match = pattern.exec(expr);
- if (match == null) return before;
-
- while (match != null) {
- var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
- ctx = ctx[comp];
- if (null == ctx || '' == match[3]) break;
- expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
- match = pattern.exec(expr);
- }
-
- return before + String.interpret(ctx);
- });
- }
-});
-Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
-
-var $break = { };
-
-var Enumerable = {
- each: function(iterator, context) {
- var index = 0;
- iterator = iterator.bind(context);
- try {
- this._each(function(value) {
- iterator(value, index++);
- });
- } catch (e) {
- if (e != $break) throw e;
- }
- return this;
- },
-
- eachSlice: function(number, iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var index = -number, slices = [], array = this.toArray();
- while ((index += number) < array.length)
- slices.push(array.slice(index, index+number));
- return slices.collect(iterator, context);
- },
-
- all: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result = true;
- this.each(function(value, index) {
- result = result && !!iterator(value, index);
- if (!result) throw $break;
- });
- return result;
- },
-
- any: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result = false;
- this.each(function(value, index) {
- if (result = !!iterator(value, index))
- throw $break;
- });
- return result;
- },
-
- collect: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var results = [];
- this.each(function(value, index) {
- results.push(iterator(value, index));
- });
- return results;
- },
-
- detect: function(iterator, context) {
- iterator = iterator.bind(context);
- var result;
- this.each(function(value, index) {
- if (iterator(value, index)) {
- result = value;
- throw $break;
- }
- });
- return result;
- },
-
- findAll: function(iterator, context) {
- iterator = iterator.bind(context);
- var results = [];
- this.each(function(value, index) {
- if (iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- grep: function(filter, iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var results = [];
-
- if (Object.isString(filter))
- filter = new RegExp(filter);
-
- this.each(function(value, index) {
- if (filter.match(value))
- results.push(iterator(value, index));
- });
- return results;
- },
-
- include: function(object) {
- if (Object.isFunction(this.indexOf))
- if (this.indexOf(object) != -1) return true;
-
- var found = false;
- this.each(function(value) {
- if (value == object) {
- found = true;
- throw $break;
- }
- });
- return found;
- },
-
- inGroupsOf: function(number, fillWith) {
- fillWith = Object.isUndefined(fillWith) ? null : fillWith;
- return this.eachSlice(number, function(slice) {
- while(slice.length < number) slice.push(fillWith);
- return slice;
- });
- },
-
- inject: function(memo, iterator, context) {
- iterator = iterator.bind(context);
- this.each(function(value, index) {
- memo = iterator(memo, value, index);
- });
- return memo;
- },
-
- invoke: function(method) {
- var args = $A(arguments).slice(1);
- return this.map(function(value) {
- return value[method].apply(value, args);
- });
- },
-
- max: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result;
- this.each(function(value, index) {
- value = iterator(value, index);
- if (result == null || value >= result)
- result = value;
- });
- return result;
- },
-
- min: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result;
- this.each(function(value, index) {
- value = iterator(value, index);
- if (result == null || value < result)
- result = value;
- });
- return result;
- },
-
- partition: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var trues = [], falses = [];
- this.each(function(value, index) {
- (iterator(value, index) ?
- trues : falses).push(value);
- });
- return [trues, falses];
- },
-
- pluck: function(property) {
- var results = [];
- this.each(function(value) {
- results.push(value[property]);
- });
- return results;
- },
-
- reject: function(iterator, context) {
- iterator = iterator.bind(context);
- var results = [];
- this.each(function(value, index) {
- if (!iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- sortBy: function(iterator, context) {
- iterator = iterator.bind(context);
- return this.map(function(value, index) {
- return {value: value, criteria: iterator(value, index)};
- }).sort(function(left, right) {
- var a = left.criteria, b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
- }).pluck('value');
- },
-
- toArray: function() {
- return this.map();
- },
-
- zip: function() {
- var iterator = Prototype.K, args = $A(arguments);
- if (Object.isFunction(args.last()))
- iterator = args.pop();
-
- var collections = [this].concat(args).map($A);
- return this.map(function(value, index) {
- return iterator(collections.pluck(index));
- });
- },
-
- size: function() {
- return this.toArray().length;
- },
-
- inspect: function() {
- return '#<Enumerable:' + this.toArray().inspect() + '>';
- }
-};
-
-Object.extend(Enumerable, {
- map: Enumerable.collect,
- find: Enumerable.detect,
- select: Enumerable.findAll,
- filter: Enumerable.findAll,
- member: Enumerable.include,
- entries: Enumerable.toArray,
- every: Enumerable.all,
- some: Enumerable.any
-});
-function $A(iterable) {
- if (!iterable) return [];
- if (iterable.toArray) return iterable.toArray();
- var length = iterable.length || 0, results = new Array(length);
- while (length--) results[length] = iterable[length];
- return results;
-}
-
-if (Prototype.Browser.WebKit) {
- $A = function(iterable) {
- if (!iterable) return [];
- if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
- iterable.toArray) return iterable.toArray();
- var length = iterable.length || 0, results = new Array(length);
- while (length--) results[length] = iterable[length];
- return results;
- };
-}
-
-Array.from = $A;
-
-Object.extend(Array.prototype, Enumerable);
-
-if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
-
-Object.extend(Array.prototype, {
- _each: function(iterator) {
- for (var i = 0, length = this.length; i < length; i++)
- iterator(this[i]);
- },
-
- clear: function() {
- this.length = 0;
- return this;
- },
-
- first: function() {
- return this[0];
- },
-
- last: function() {
- return this[this.length - 1];
- },
-
- compact: function() {
- return this.select(function(value) {
- return value != null;
- });
- },
-
- flatten: function() {
- return this.inject([], function(array, value) {
- return array.concat(Object.isArray(value) ?
- value.flatten() : [value]);
- });
- },
-
- without: function() {
- var values = $A(arguments);
- return this.select(function(value) {
- return !values.include(value);
- });
- },
-
- reverse: function(inline) {
- return (inline !== false ? this : this.toArray())._reverse();
- },
-
- reduce: function() {
- return this.length > 1 ? this : this[0];
- },
-
- uniq: function(sorted) {
- return this.inject([], function(array, value, index) {
- if (0 == index || (sorted ? array.last() != value : !array.include(value)))
- array.push(value);
- return array;
- });
- },
-
- intersect: function(array) {
- return this.uniq().findAll(function(item) {
- return array.detect(function(value) { return item === value });
- });
- },
-
- clone: function() {
- return [].concat(this);
- },
-
- size: function() {
- return this.length;
- },
-
- inspect: function() {
- return '[' + this.map(Object.inspect).join(', ') + ']';
- },
-
- toJSON: function() {
- var results = [];
- this.each(function(object) {
- var value = Object.toJSON(object);
- if (!Object.isUndefined(value)) results.push(value);
- });
- return '[' + results.join(', ') + ']';
- }
-});
-
-// use native browser JS 1.6 implementation if available
-if (Object.isFunction(Array.prototype.forEach))
- Array.prototype._each = Array.prototype.forEach;
-
-if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
- i || (i = 0);
- var length = this.length;
- if (i < 0) i = length + i;
- for (; i < length; i++)
- if (this[i] === item) return i;
- return -1;
-};
-
-if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
- i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
- var n = this.slice(0, i).reverse().indexOf(item);
- return (n < 0) ? n : i - n - 1;
-};
-
-Array.prototype.toArray = Array.prototype.clone;
-
-function $w(string) {
- if (!Object.isString(string)) return [];
- string = string.strip();
- return string ? string.split(/\s+/) : [];
-}
-
-if (Prototype.Browser.Opera){
- Array.prototype.concat = function() {
- var array = [];
- for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
- for (var i = 0, length = arguments.length; i < length; i++) {
- if (Object.isArray(arguments[i])) {
- for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
- array.push(arguments[i][j]);
- } else {
- array.push(arguments[i]);
- }
- }
- return array;
- };
-}
-Object.extend(Number.prototype, {
- toColorPart: function() {
- return this.toPaddedString(2, 16);
- },
-
- succ: function() {
- return this + 1;
- },
-
- times: function(iterator) {
- $R(0, this, true).each(iterator);
- return this;
- },
-
- toPaddedString: function(length, radix) {
- var string = this.toString(radix || 10);
- return '0'.times(length - string.length) + string;
- },
-
- toJSON: function() {
- return isFinite(this) ? this.toString() : 'null';
- }
-});
-
-$w('abs round ceil floor').each(function(method){
- Number.prototype[method] = Math[method].methodize();
-});
-function $H(object) {
- return new Hash(object);
-};
-
-var Hash = Class.create(Enumerable, (function() {
-
- function toQueryPair(key, value) {
- if (Object.isUndefined(value)) return key;
- return key + '=' + encodeURIComponent(String.interpret(value));
- }
-
- return {
- initialize: function(object) {
- this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
- },
-
- _each: function(iterator) {
- for (var key in this._object) {
- var value = this._object[key], pair = [key, value];
- pair.key = key;
- pair.value = value;
- iterator(pair);
- }
- },
-
- set: function(key, value) {
- return this._object[key] = value;
- },
-
- get: function(key) {
- return this._object[key];
- },
-
- unset: function(key) {
- var value = this._object[key];
- delete this._object[key];
- return value;
- },
-
- toObject: function() {
- return Object.clone(this._object);
- },
-
- keys: function() {
- return this.pluck('key');
- },
-
- values: function() {
- return this.pluck('value');
- },
-
- index: function(value) {
- var match = this.detect(function(pair) {
- return pair.value === value;
- });
- return match && match.key;
- },
-
- merge: function(object) {
- return this.clone().update(object);
- },
-
- update: function(object) {
- return new Hash(object).inject(this, function(result, pair) {
- result.set(pair.key, pair.value);
- return result;
- });
- },
-
- toQueryString: function() {
- return this.map(function(pair) {
- var key = encodeURIComponent(pair.key), values = pair.value;
-
- if (values && typeof values == 'object') {
- if (Object.isArray(values))
- return values.map(toQueryPair.curry(key)).join('&');
- }
- return toQueryPair(key, values);
- }).join('&');
- },
-
- inspect: function() {
- return '#<Hash:{' + this.map(function(pair) {
- return pair.map(Object.inspect).join(': ');
- }).join(', ') + '}>';
- },
-
- toJSON: function() {
- return Object.toJSON(this.toObject());
- },
-
- clone: function() {
- return new Hash(this);
- }
- }
-})());
-
-Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
-Hash.from = $H;
-var ObjectRange = Class.create(Enumerable, {
- initialize: function(start, end, exclusive) {
- this.start = start;
- this.end = end;
- this.exclusive = exclusive;
- },
-
- _each: function(iterator) {
- var value = this.start;
- while (this.include(value)) {
- iterator(value);
- value = value.succ();
- }
- },
-
- include: function(value) {
- if (value < this.start)
- return false;
- if (this.exclusive)
- return value < this.end;
- return value <= this.end;
- }
-});
-
-var $R = function(start, end, exclusive) {
- return new ObjectRange(start, end, exclusive);
-};
-
-var Ajax = {
- getTransport: function() {
- return Try.these(
- function() {return new XMLHttpRequest()},
- function() {return new ActiveXObject('Msxml2.XMLHTTP')},
- function() {return new ActiveXObject('Microsoft.XMLHTTP')}
- ) || false;
- },
-
- activeRequestCount: 0
-};
-
-Ajax.Responders = {
- responders: [],
-
- _each: function(iterator) {
- this.responders._each(iterator);
- },
-
- register: function(responder) {
- if (!this.include(responder))
- this.responders.push(responder);
- },
-
- unregister: function(responder) {
- this.responders = this.responders.without(responder);
- },
-
- dispatch: function(callback, request, transport, json) {
- this.each(function(responder) {
- if (Object.isFunction(responder[callback])) {
- try {
- responder[callback].apply(responder, [request, transport, json]);
- } catch (e) { }
- }
- });
- }
-};
-
-Object.extend(Ajax.Responders, Enumerable);
-
-Ajax.Responders.register({
- onCreate: function() { Ajax.activeRequestCount++ },
- onComplete: function() { Ajax.activeRequestCount-- }
-});
-
-Ajax.Base = Class.create({
- initialize: function(options) {
- this.options = {
- method: 'post',
- asynchronous: true,
- contentType: 'application/x-www-form-urlencoded',
- encoding: 'UTF-8',
- parameters: '',
- evalJSON: true,
- evalJS: true
- };
- Object.extend(this.options, options || { });
-
- this.options.method = this.options.method.toLowerCase();
-
- if (Object.isString(this.options.parameters))
- this.options.parameters = this.options.parameters.toQueryParams();
- else if (Object.isHash(this.options.parameters))
- this.options.parameters = this.options.parameters.toObject();
- }
-});
-
-Ajax.Request = Class.create(Ajax.Base, {
- _complete: false,
-
- initialize: function($super, url, options) {
- $super(options);
- this.transport = Ajax.getTransport();
- this.request(url);
- },
-
- request: function(url) {
- this.url = url;
- this.method = this.options.method;
- var params = Object.clone(this.options.parameters);
-
- if (!['get', 'post'].include(this.method)) {
- // simulate other verbs over post
- params['_method'] = this.method;
- this.method = 'post';
- }
-
- this.parameters = params;
-
- if (params = Object.toQueryString(params)) {
- // when GET, append parameters to URL
- if (this.method == 'get')
- this.url += (this.url.include('?') ? '&' : '?') + params;
- else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
- params += '&_=';
- }
-
- try {
- var response = new Ajax.Response(this);
- if (this.options.onCreate) this.options.onCreate(response);
- Ajax.Responders.dispatch('onCreate', this, response);
-
- this.transport.open(this.method.toUpperCase(), this.url,
- this.options.asynchronous);
-
- if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
-
- this.transport.onreadystatechange = this.onStateChange.bind(this);
- this.setRequestHeaders();
-
- this.body = this.method == 'post' ? (this.options.postBody || params) : null;
- this.transport.send(this.body);
-
- /* Force Firefox to handle ready state 4 for synchronous requests */
- if (!this.options.asynchronous && this.transport.overrideMimeType)
- this.onStateChange();
-
- }
- catch (e) {
- this.dispatchException(e);
- }
- },
-
- onStateChange: function() {
- var readyState = this.transport.readyState;
- if (readyState > 1 && !((readyState == 4) && this._complete))
- this.respondToReadyState(this.transport.readyState);
- },
-
- setRequestHeaders: function() {
- var headers = {
- 'X-Requested-With': 'XMLHttpRequest',
- 'X-Prototype-Version': Prototype.Version,
- 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
- };
-
- if (this.method == 'post') {
- headers['Content-type'] = this.options.contentType +
- (this.options.encoding ? '; charset=' + this.options.encoding : '');
-
- /* Force "Connection: close" for older Mozilla browsers to work
- * around a bug where XMLHttpRequest sends an incorrect
- * Content-length header. See Mozilla Bugzilla #246651.
- */
- if (this.transport.overrideMimeType &&
- (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
- headers['Connection'] = 'close';
- }
-
- // user-defined headers
- if (typeof this.options.requestHeaders == 'object') {
- var extras = this.options.requestHeaders;
-
- if (Object.isFunction(extras.push))
- for (var i = 0, length = extras.length; i < length; i += 2)
- headers[extras[i]] = extras[i+1];
- else
- $H(extras).each(function(pair) { headers[pair.key] = pair.value });
- }
-
- for (var name in headers)
- this.transport.setRequestHeader(name, headers[name]);
- },
-
- success: function() {
- var status = this.getStatus();
- return !status || (status >= 200 && status < 300);
- },
-
- getStatus: function() {
- try {
- return this.transport.status || 0;
- } catch (e) { return 0 }
- },
-
- respondToReadyState: function(readyState) {
- var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
-
- if (state == 'Complete') {
- try {
- this._complete = true;
- (this.options['on' + response.status]
- || this.options['on' + (this.success() ? 'Success' : 'Failure')]
- || Prototype.emptyFunction)(response, response.headerJSON);
- } catch (e) {
- this.dispatchException(e);
- }
-
- var contentType = response.getHeader('Content-type');
- if (this.options.evalJS == 'force'
- || (this.options.evalJS && this.isSameOrigin() && contentType
- && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
- this.evalResponse();
- }
-
- try {
- (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
- Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
- } catch (e) {
- this.dispatchException(e);
- }
-
- if (state == 'Complete') {
- // avoid memory leak in MSIE: clean up
- this.transport.onreadystatechange = Prototype.emptyFunction;
- }
- },
-
- isSameOrigin: function() {
- var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
- return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
- protocol: location.protocol,
- domain: document.domain,
- port: location.port ? ':' + location.port : ''
- }));
- },
-
- getHeader: function(name) {
- try {
- return this.transport.getResponseHeader(name) || null;
- } catch (e) { return null }
- },
-
- evalResponse: function() {
- try {
- return eval((this.transport.responseText || '').unfilterJSON());
- } catch (e) {
- this.dispatchException(e);
- }
- },
-
- dispatchException: function(exception) {
- (this.options.onException || Prototype.emptyFunction)(this, exception);
- Ajax.Responders.dispatch('onException', this, exception);
- }
-});
-
-Ajax.Request.Events =
- ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
-
-Ajax.Response = Class.create({
- initialize: function(request){
- this.request = request;
- var transport = this.transport = request.transport,
- readyState = this.readyState = transport.readyState;
-
- if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
- this.status = this.getStatus();
- this.statusText = this.getStatusText();
- this.responseText = String.interpret(transport.responseText);
- this.headerJSON = this._getHeaderJSON();
- }
-
- if(readyState == 4) {
- var xml = transport.responseXML;
- this.responseXML = Object.isUndefined(xml) ? null : xml;
- this.responseJSON = this._getResponseJSON();
- }
- },
-
- status: 0,
- statusText: '',
-
- getStatus: Ajax.Request.prototype.getStatus,
-
- getStatusText: function() {
- try {
- return this.transport.statusText || '';
- } catch (e) { return '' }
- },
-
- getHeader: Ajax.Request.prototype.getHeader,
-
- getAllHeaders: function() {
- try {
- return this.getAllResponseHeaders();
- } catch (e) { return null }
- },
-
- getResponseHeader: function(name) {
- return this.transport.getResponseHeader(name);
- },
-
- getAllResponseHeaders: function() {
- return this.transport.getAllResponseHeaders();
- },
-
- _getHeaderJSON: function() {
- var json = this.getHeader('X-JSON');
- if (!json) return null;
- json = decodeURIComponent(escape(json));
- try {
- return json.evalJSON(this.request.options.sanitizeJSON ||
- !this.request.isSameOrigin());
- } catch (e) {
- this.request.dispatchException(e);
- }
- },
-
- _getResponseJSON: function() {
- var options = this.request.options;
- if (!options.evalJSON || (options.evalJSON != 'force' &&
- !(this.getHeader('Content-type') || '').include('application/json')) ||
- this.responseText.blank())
- return null;
- try {
- return this.responseText.evalJSON(options.sanitizeJSON ||
- !this.request.isSameOrigin());
- } catch (e) {
- this.request.dispatchException(e);
- }
- }
-});
-
-Ajax.Updater = Class.create(Ajax.Request, {
- initialize: function($super, container, url, options) {
- this.container = {
- success: (container.success || container),
- failure: (container.failure || (container.success ? null : container))
- };
-
- options = Object.clone(options);
- var onComplete = options.onComplete;
- options.onComplete = (function(response, json) {
- this.updateContent(response.responseText);
- if (Object.isFunction(onComplete)) onComplete(response, json);
- }).bind(this);
-
- $super(url, options);
- },
-
- updateContent: function(responseText) {
- var receiver = this.container[this.success() ? 'success' : 'failure'],
- options = this.options;
-
- if (!options.evalScripts) responseText = responseText.stripScripts();
-
- if (receiver = $(receiver)) {
- if (options.insertion) {
- if (Object.isString(options.insertion)) {
- var insertion = { }; insertion[options.insertion] = responseText;
- receiver.insert(insertion);
- }
- else options.insertion(receiver, responseText);
- }
- else receiver.update(responseText);
- }
- }
-});
-
-Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
- initialize: function($super, container, url, options) {
- $super(options);
- this.onComplete = this.options.onComplete;
-
- this.frequency = (this.options.frequency || 2);
- this.decay = (this.options.decay || 1);
-
- this.updater = { };
- this.container = container;
- this.url = url;
-
- this.start();
- },
-
- start: function() {
- this.options.onComplete = this.updateComplete.bind(this);
- this.onTimerEvent();
- },
-
- stop: function() {
- this.updater.options.onComplete = undefined;
- clearTimeout(this.timer);
- (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
- },
-
- updateComplete: function(response) {
- if (this.options.decay) {
- this.decay = (response.responseText == this.lastText ?
- this.decay * this.options.decay : 1);
-
- this.lastText = response.responseText;
- }
- this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
- },
-
- onTimerEvent: function() {
- this.updater = new Ajax.Updater(this.container, this.url, this.options);
- }
-});
-function $(element) {
- if (arguments.length > 1) {
- for (var i = 0, elements = [], length = arguments.length; i < length; i++)
- elements.push($(arguments[i]));
- return elements;
- }
- if (Object.isString(element))
- element = document.getElementById(element);
- return Element.extend(element);
-}
-
-if (Prototype.BrowserFeatures.XPath) {
- document._getElementsByXPath = function(expression, parentElement) {
- var results = [];
- var query = document.evaluate(expression, $(parentElement) || document,
- null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
- for (var i = 0, length = query.snapshotLength; i < length; i++)
- results.push(Element.extend(query.snapshotItem(i)));
- return results;
- };
-}
-
-/*--------------------------------------------------------------------------*/
-
-if (!window.Node) var Node = { };
-
-if (!Node.ELEMENT_NODE) {
- // DOM level 2 ECMAScript Language Binding
- Object.extend(Node, {
- ELEMENT_NODE: 1,
- ATTRIBUTE_NODE: 2,
- TEXT_NODE: 3,
- CDATA_SECTION_NODE: 4,
- ENTITY_REFERENCE_NODE: 5,
- ENTITY_NODE: 6,
- PROCESSING_INSTRUCTION_NODE: 7,
- COMMENT_NODE: 8,
- DOCUMENT_NODE: 9,
- DOCUMENT_TYPE_NODE: 10,
- DOCUMENT_FRAGMENT_NODE: 11,
- NOTATION_NODE: 12
- });
-}
-
-(function() {
- var element = this.Element;
- this.Element = function(tagName, attributes) {
- attributes = attributes || { };
- tagName = tagName.toLowerCase();
- var cache = Element.cache;
- if (Prototype.Browser.IE && attributes.name) {
- tagName = '<' + tagName + ' name="' + attributes.name + '">';
- delete attributes.name;
- return Element.writeAttribute(document.createElement(tagName), attributes);
- }
- if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
- return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
- };
- Object.extend(this.Element, element || { });
-}).call(window);
-
-Element.cache = { };
-
-Element.Methods = {
- visible: function(element) {
- return $(element).style.display != 'none';
- },
-
- toggle: function(element) {
- element = $(element);
- Element[Element.visible(element) ? 'hide' : 'show'](element);
- return element;
- },
-
- hide: function(element) {
- $(element).style.display = 'none';
- return element;
- },
-
- show: function(element) {
- $(element).style.display = '';
- return element;
- },
-
- remove: function(element) {
- element = $(element);
- element.parentNode.removeChild(element);
- return element;
- },
-
- update: function(element, content) {
- element = $(element);
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) return element.update().insert(content);
- content = Object.toHTML(content);
- element.innerHTML = content.stripScripts();
- content.evalScripts.bind(content).defer();
- return element;
- },
-
- replace: function(element, content) {
- element = $(element);
- if (content && content.toElement) content = content.toElement();
- else if (!Object.isElement(content)) {
- content = Object.toHTML(content);
- var range = element.ownerDocument.createRange();
- range.selectNode(element);
- content.evalScripts.bind(content).defer();
- content = range.createContextualFragment(content.stripScripts());
- }
- element.parentNode.replaceChild(content, element);
- return element;
- },
-
- insert: function(element, insertions) {
- element = $(element);
-
- if (Object.isString(insertions) || Object.isNumber(insertions) ||
- Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
- insertions = {bottom:insertions};
-
- var content, insert, tagName, childNodes;
-
- for (var position in insertions) {
- content = insertions[position];
- position = position.toLowerCase();
- insert = Element._insertionTranslations[position];
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) {
- insert(element, content);
- continue;
- }
-
- content = Object.toHTML(content);
-
- tagName = ((position == 'before' || position == 'after')
- ? element.parentNode : element).tagName.toUpperCase();
-
- childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
-
- if (position == 'top' || position == 'after') childNodes.reverse();
- childNodes.each(insert.curry(element));
-
- content.evalScripts.bind(content).defer();
- }
-
- return element;
- },
-
- wrap: function(element, wrapper, attributes) {
- element = $(element);
- if (Object.isElement(wrapper))
- $(wrapper).writeAttribute(attributes || { });
- else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
- else wrapper = new Element('div', wrapper);
- if (element.parentNode)
- element.parentNode.replaceChild(wrapper, element);
- wrapper.appendChild(element);
- return wrapper;
- },
-
- inspect: function(element) {
- element = $(element);
- var result = '<' + element.tagName.toLowerCase();
- $H({'id': 'id', 'className': 'class'}).each(function(pair) {
- var property = pair.first(), attribute = pair.last();
- var value = (element[property] || '').toString();
- if (value) result += ' ' + attribute + '=' + value.inspect(true);
- });
- return result + '>';
- },
-
- recursivelyCollect: function(element, property) {
- element = $(element);
- var elements = [];
- while (element = element[property])
- if (element.nodeType == 1)
- elements.push(Element.extend(element));
- return elements;
- },
-
- ancestors: function(element) {
- return $(element).recursivelyCollect('parentNode');
- },
-
- descendants: function(element) {
- return $(element).select("*");
- },
-
- firstDescendant: function(element) {
- element = $(element).firstChild;
- while (element && element.nodeType != 1) element = element.nextSibling;
- return $(element);
- },
-
- immediateDescendants: function(element) {
- if (!(element = $(element).firstChild)) return [];
- while (element && element.nodeType != 1) element = element.nextSibling;
- if (element) return [element].concat($(element).nextSiblings());
- return [];
- },
-
- previousSiblings: function(element) {
- return $(element).recursivelyCollect('previousSibling');
- },
-
- nextSiblings: function(element) {
- return $(element).recursivelyCollect('nextSibling');
- },
-
- siblings: function(element) {
- element = $(element);
- return element.previousSiblings().reverse().concat(element.nextSiblings());
- },
-
- match: function(element, selector) {
- if (Object.isString(selector))
- selector = new Selector(selector);
- return selector.match($(element));
- },
-
- up: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(element.parentNode);
- var ancestors = element.ancestors();
- return Object.isNumber(expression) ? ancestors[expression] :
- Selector.findElement(ancestors, expression, index);
- },
-
- down: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return element.firstDescendant();
- return Object.isNumber(expression) ? element.descendants()[expression] :
- element.select(expression)[index || 0];
- },
-
- previous: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
- var previousSiblings = element.previousSiblings();
- return Object.isNumber(expression) ? previousSiblings[expression] :
- Selector.findElement(previousSiblings, expression, index);
- },
-
- next: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
- var nextSiblings = element.nextSiblings();
- return Object.isNumber(expression) ? nextSiblings[expression] :
- Selector.findElement(nextSiblings, expression, index);
- },
-
- select: function() {
- var args = $A(arguments), element = $(args.shift());
- return Selector.findChildElements(element, args);
- },
-
- adjacent: function() {
- var args = $A(arguments), element = $(args.shift());
- return Selector.findChildElements(element.parentNode, args).without(element);
- },
-
- identify: function(element) {
- element = $(element);
- var id = element.readAttribute('id'), self = arguments.callee;
- if (id) return id;
- do { id = 'anonymous_element_' + self.counter++ } while ($(id));
- element.writeAttribute('id', id);
- return id;
- },
-
- readAttribute: function(element, name) {
- element = $(element);
- if (Prototype.Browser.IE) {
- var t = Element._attributeTranslations.read;
- if (t.values[name]) return t.values[name](element, name);
- if (t.names[name]) name = t.names[name];
- if (name.include(':')) {
- return (!element.attributes || !element.attributes[name]) ? null :
- element.attributes[name].value;
- }
- }
- return element.getAttribute(name);
- },
-
- writeAttribute: function(element, name, value) {
- element = $(element);
- var attributes = { }, t = Element._attributeTranslations.write;
-
- if (typeof name == 'object') attributes = name;
- else attributes[name] = Object.isUndefined(value) ? true : value;
-
- for (var attr in attributes) {
- name = t.names[attr] || attr;
- value = attributes[attr];
- if (t.values[attr]) name = t.values[attr](element, value);
- if (value === false || value === null)
- element.removeAttribute(name);
- else if (value === true)
- element.setAttribute(name, name);
- else element.setAttribute(name, value);
- }
- return element;
- },
-
- getHeight: function(element) {
- return $(element).getDimensions().height;
- },
-
- getWidth: function(element) {
- return $(element).getDimensions().width;
- },
-
- classNames: function(element) {
- return new Element.ClassNames(element);
- },
-
- hasClassName: function(element, className) {
- if (!(element = $(element))) return;
- var elementClassName = element.className;
- return (elementClassName.length > 0 && (elementClassName == className ||
- new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
- },
-
- addClassName: function(element, className) {
- if (!(element = $(element))) return;
- if (!element.hasClassName(className))
- element.className += (element.className ? ' ' : '') + className;
- return element;
- },
-
- removeClassName: function(element, className) {
- if (!(element = $(element))) return;
- element.className = element.className.replace(
- new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
- return element;
- },
-
- toggleClassName: function(element, className) {
- if (!(element = $(element))) return;
- return element[element.hasClassName(className) ?
- 'removeClassName' : 'addClassName'](className);
- },
-
- // removes whitespace-only text node children
- cleanWhitespace: function(element) {
- element = $(element);
- var node = element.firstChild;
- while (node) {
- var nextNode = node.nextSibling;
- if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
- element.removeChild(node);
- node = nextNode;
- }
- return element;
- },
-
- empty: function(element) {
- return $(element).innerHTML.blank();
- },
-
- descendantOf: function(element, ancestor) {
- element = $(element), ancestor = $(ancestor);
- var originalAncestor = ancestor;
-
- if (element.compareDocumentPosition)
- return (element.compareDocumentPosition(ancestor) & 8) === 8;
-
- if (element.sourceIndex && !Prototype.Browser.Opera) {
- var e = element.sourceIndex, a = ancestor.sourceIndex,
- nextAncestor = ancestor.nextSibling;
- if (!nextAncestor) {
- do { ancestor = ancestor.parentNode; }
- while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
- }
- if (nextAncestor && nextAncestor.sourceIndex)
- return (e > a && e < nextAncestor.sourceIndex);
- }
-
- while (element = element.parentNode)
- if (element == originalAncestor) return true;
- return false;
- },
-
- scrollTo: function(element) {
- element = $(element);
- var pos = element.cumulativeOffset();
- window.scrollTo(pos[0], pos[1]);
- return element;
- },
-
- getStyle: function(element, style) {
- element = $(element);
- style = style == 'float' ? 'cssFloat' : style.camelize();
- var value = element.style[style];
- if (!value) {
- var css = document.defaultView.getComputedStyle(element, null);
- value = css ? css[style] : null;
- }
- if (style == 'opacity') return value ? parseFloat(value) : 1.0;
- return value == 'auto' ? null : value;
- },
-
- getOpacity: function(element) {
- return $(element).getStyle('opacity');
- },
-
- setStyle: function(element, styles) {
- element = $(element);
- var elementStyle = element.style, match;
- if (Object.isString(styles)) {
- element.style.cssText += ';' + styles;
- return styles.include('opacity') ?
- element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
- }
- for (var property in styles)
- if (property == 'opacity') element.setOpacity(styles[property]);
- else
- elementStyle[(property == 'float' || property == 'cssFloat') ?
- (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
- property] = styles[property];
-
- return element;
- },
-
- setOpacity: function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1 || value === '') ? '' :
- (value < 0.00001) ? 0 : value;
- return element;
- },
-
- getDimensions: function(element) {
- element = $(element);
- var display = $(element).getStyle('display');
- if (display != 'none' && display != null) // Safari bug
- return {width: element.offsetWidth, height: element.offsetHeight};
-
- // All *Width and *Height properties give 0 on elements with display none,
- // so enable the element temporarily
- var els = element.style;
- var originalVisibility = els.visibility;
- var originalPosition = els.position;
- var originalDisplay = els.display;
- els.visibility = 'hidden';
- els.position = 'absolute';
- els.display = 'block';
- var originalWidth = element.clientWidth;
- var originalHeight = element.clientHeight;
- els.display = originalDisplay;
- els.position = originalPosition;
- els.visibility = originalVisibility;
- return {width: originalWidth, height: originalHeight};
- },
-
- makePositioned: function(element) {
- element = $(element);
- var pos = Element.getStyle(element, 'position');
- if (pos == 'static' || !pos) {
- element._madePositioned = true;
- element.style.position = 'relative';
- // Opera returns the offset relative to the positioning context, when an
- // element is position relative but top and left have not been defined
- if (window.opera) {
- element.style.top = 0;
- element.style.left = 0;
- }
- }
- return element;
- },
-
- undoPositioned: function(element) {
- element = $(element);
- if (element._madePositioned) {
- element._madePositioned = undefined;
- element.style.position =
- element.style.top =
- element.style.left =
- element.style.bottom =
- element.style.right = '';
- }
- return element;
- },
-
- makeClipping: function(element) {
- element = $(element);
- if (element._overflow) return element;
- element._overflow = Element.getStyle(element, 'overflow') || 'auto';
- if (element._overflow !== 'hidden')
- element.style.overflow = 'hidden';
- return element;
- },
-
- undoClipping: function(element) {
- element = $(element);
- if (!element._overflow) return element;
- element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
- element._overflow = null;
- return element;
- },
-
- cumulativeOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- positionedOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- if (element) {
- if (element.tagName == 'BODY') break;
- var p = Element.getStyle(element, 'position');
- if (p !== 'static') break;
- }
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- absolutize: function(element) {
- element = $(element);
- if (element.getStyle('position') == 'absolute') return;
- // Position.prepare(); // To be done manually by Scripty when it needs it.
-
- var offsets = element.positionedOffset();
- var top = offsets[1];
- var left = offsets[0];
- var width = element.clientWidth;
- var height = element.clientHeight;
-
- element._originalLeft = left - parseFloat(element.style.left || 0);
- element._originalTop = top - parseFloat(element.style.top || 0);
- element._originalWidth = element.style.width;
- element._originalHeight = element.style.height;
-
- element.style.position = 'absolute';
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.width = width + 'px';
- element.style.height = height + 'px';
- return element;
- },
-
- relativize: function(element) {
- element = $(element);
- if (element.getStyle('position') == 'relative') return;
- // Position.prepare(); // To be done manually by Scripty when it needs it.
-
- element.style.position = 'relative';
- var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
- var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
-
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.height = element._originalHeight;
- element.style.width = element._originalWidth;
- return element;
- },
-
- cumulativeScrollOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.scrollTop || 0;
- valueL += element.scrollLeft || 0;
- element = element.parentNode;
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- getOffsetParent: function(element) {
- if (element.offsetParent) return $(element.offsetParent);
- if (element == document.body) return $(element);
-
- while ((element = element.parentNode) && element != document.body)
- if (Element.getStyle(element, 'position') != 'static')
- return $(element);
-
- return $(document.body);
- },
-
- viewportOffset: function(forElement) {
- var valueT = 0, valueL = 0;
-
- var element = forElement;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
-
- // Safari fix
- if (element.offsetParent == document.body &&
- Element.getStyle(element, 'position') == 'absolute') break;
-
- } while (element = element.offsetParent);
-
- element = forElement;
- do {
- if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
- valueT -= element.scrollTop || 0;
- valueL -= element.scrollLeft || 0;
- }
- } while (element = element.parentNode);
-
- return Element._returnOffset(valueL, valueT);
- },
-
- clonePosition: function(element, source) {
- var options = Object.extend({
- setLeft: true,
- setTop: true,
- setWidth: true,
- setHeight: true,
- offsetTop: 0,
- offsetLeft: 0
- }, arguments[2] || { });
-
- // find page position of source
- source = $(source);
- var p = source.viewportOffset();
-
- // find coordinate system to use
- element = $(element);
- var delta = [0, 0];
- var parent = null;
- // delta [0,0] will do fine with position: fixed elements,
- // position:absolute needs offsetParent deltas
- if (Element.getStyle(element, 'position') == 'absolute') {
- parent = element.getOffsetParent();
- delta = parent.viewportOffset();
- }
-
- // correct by body offsets (fixes Safari)
- if (parent == document.body) {
- delta[0] -= document.body.offsetLeft;
- delta[1] -= document.body.offsetTop;
- }
-
- // set position
- if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
- if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
- if (options.setWidth) element.style.width = source.offsetWidth + 'px';
- if (options.setHeight) element.style.height = source.offsetHeight + 'px';
- return element;
- }
-};
-
-Element.Methods.identify.counter = 1;
-
-Object.extend(Element.Methods, {
- getElementsBySelector: Element.Methods.select,
- childElements: Element.Methods.immediateDescendants
-});
-
-Element._attributeTranslations = {
- write: {
- names: {
- className: 'class',
- htmlFor: 'for'
- },
- values: { }
- }
-};
-
-if (Prototype.Browser.Opera) {
- Element.Methods.getStyle = Element.Methods.getStyle.wrap(
- function(proceed, element, style) {
- switch (style) {
- case 'left': case 'top': case 'right': case 'bottom':
- if (proceed(element, 'position') === 'static') return null;
- case 'height': case 'width':
- // returns '0px' for hidden elements; we want it to return null
- if (!Element.visible(element)) return null;
-
- // returns the border-box dimensions rather than the content-box
- // dimensions, so we subtract padding and borders from the value
- var dim = parseInt(proceed(element, style), 10);
-
- if (dim !== element['offset' + style.capitalize()])
- return dim + 'px';
-
- var properties;
- if (style === 'height') {
- properties = ['border-top-width', 'padding-top',
- 'padding-bottom', 'border-bottom-width'];
- }
- else {
- properties = ['border-left-width', 'padding-left',
- 'padding-right', 'border-right-width'];
- }
- return properties.inject(dim, function(memo, property) {
- var val = proceed(element, property);
- return val === null ? memo : memo - parseInt(val, 10);
- }) + 'px';
- default: return proceed(element, style);
- }
- }
- );
-
- Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
- function(proceed, element, attribute) {
- if (attribute === 'title') return element.title;
- return proceed(element, attribute);
- }
- );
-}
-
-else if (Prototype.Browser.IE) {
- // IE doesn't report offsets correctly for static elements, so we change them
- // to "relative" to get the values, then change them back.
- Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
- function(proceed, element) {
- element = $(element);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
-
- $w('positionedOffset viewportOffset').each(function(method) {
- Element.Methods[method] = Element.Methods[method].wrap(
- function(proceed, element) {
- element = $(element);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- // Trigger hasLayout on the offset parent so that IE6 reports
- // accurate offsetTop and offsetLeft values for position: fixed.
- var offsetParent = element.getOffsetParent();
- if (offsetParent && offsetParent.getStyle('position') === 'fixed')
- offsetParent.setStyle({ zoom: 1 });
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
- });
-
- Element.Methods.getStyle = function(element, style) {
- element = $(element);
- style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
- var value = element.style[style];
- if (!value && element.currentStyle) value = element.currentStyle[style];
-
- if (style == 'opacity') {
- if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
- if (value[1]) return parseFloat(value[1]) / 100;
- return 1.0;
- }
-
- if (value == 'auto') {
- if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
- return element['offset' + style.capitalize()] + 'px';
- return null;
- }
- return value;
- };
-
- Element.Methods.setOpacity = function(element, value) {
- function stripAlpha(filter){
- return filter.replace(/alpha\([^\)]*\)/gi,'');
- }
- element = $(element);
- var currentStyle = element.currentStyle;
- if ((currentStyle && !currentStyle.hasLayout) ||
- (!currentStyle && element.style.zoom == 'normal'))
- element.style.zoom = 1;
-
- var filter = element.getStyle('filter'), style = element.style;
- if (value == 1 || value === '') {
- (filter = stripAlpha(filter)) ?
- style.filter = filter : style.removeAttribute('filter');
- return element;
- } else if (value < 0.00001) value = 0;
- style.filter = stripAlpha(filter) +
- 'alpha(opacity=' + (value * 100) + ')';
- return element;
- };
-
- Element._attributeTranslations = {
- read: {
- names: {
- 'class': 'className',
- 'for': 'htmlFor'
- },
- values: {
- _getAttr: function(element, attribute) {
- return element.getAttribute(attribute, 2);
- },
- _getAttrNode: function(element, attribute) {
- var node = element.getAttributeNode(attribute);
- return node ? node.value : "";
- },
- _getEv: function(element, attribute) {
- attribute = element.getAttribute(attribute);
- return attribute ? attribute.toString().slice(23, -2) : null;
- },
- _flag: function(element, attribute) {
- return $(element).hasAttribute(attribute) ? attribute : null;
- },
- style: function(element) {
- return element.style.cssText.toLowerCase();
- },
- title: function(element) {
- return element.title;
- }
- }
- }
- };
-
- Element._attributeTranslations.write = {
- names: Object.extend({
- cellpadding: 'cellPadding',
- cellspacing: 'cellSpacing'
- }, Element._attributeTranslations.read.names),
- values: {
- checked: function(element, value) {
- element.checked = !!value;
- },
-
- style: function(element, value) {
- element.style.cssText = value ? value : '';
- }
- }
- };
-
- Element._attributeTranslations.has = {};
-
- $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
- 'encType maxLength readOnly longDesc').each(function(attr) {
- Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
- Element._attributeTranslations.has[attr.toLowerCase()] = attr;
- });
-
- (function(v) {
- Object.extend(v, {
- href: v._getAttr,
- src: v._getAttr,
- type: v._getAttr,
- action: v._getAttrNode,
- disabled: v._flag,
- checked: v._flag,
- readonly: v._flag,
- multiple: v._flag,
- onload: v._getEv,
- onunload: v._getEv,
- onclick: v._getEv,
- ondblclick: v._getEv,
- onmousedown: v._getEv,
- onmouseup: v._getEv,
- onmouseover: v._getEv,
- onmousemove: v._getEv,
- onmouseout: v._getEv,
- onfocus: v._getEv,
- onblur: v._getEv,
- onkeypress: v._getEv,
- onkeydown: v._getEv,
- onkeyup: v._getEv,
- onsubmit: v._getEv,
- onreset: v._getEv,
- onselect: v._getEv,
- onchange: v._getEv
- });
- })(Element._attributeTranslations.read.values);
-}
-
-else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
- Element.Methods.setOpacity = function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1) ? 0.999999 :
- (value === '') ? '' : (value < 0.00001) ? 0 : value;
- return element;
- };
-}
-
-else if (Prototype.Browser.WebKit) {
- Element.Methods.setOpacity = function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1 || value === '') ? '' :
- (value < 0.00001) ? 0 : value;
-
- if (value == 1)
- if(element.tagName == 'IMG' && element.width) {
- element.width++; element.width--;
- } else try {
- var n = document.createTextNode(' ');
- element.appendChild(n);
- element.removeChild(n);
- } catch (e) { }
-
- return element;
- };
-
- // Safari returns margins on body which is incorrect if the child is absolutely
- // positioned. For performance reasons, redefine Element#cumulativeOffset for
- // KHTML/WebKit only.
- Element.Methods.cumulativeOffset = function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- if (element.offsetParent == document.body)
- if (Element.getStyle(element, 'position') == 'absolute') break;
-
- element = element.offsetParent;
- } while (element);
-
- return Element._returnOffset(valueL, valueT);
- };
-}
-
-if (Prototype.Browser.IE || Prototype.Browser.Opera) {
- // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
- Element.Methods.update = function(element, content) {
- element = $(element);
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) return element.update().insert(content);
-
- content = Object.toHTML(content);
- var tagName = element.tagName.toUpperCase();
-
- if (tagName in Element._insertionTranslations.tags) {
- $A(element.childNodes).each(function(node) { element.removeChild(node) });
- Element._getContentFromAnonymousElement(tagName, content.stripScripts())
- .each(function(node) { element.appendChild(node) });
- }
- else element.innerHTML = content.stripScripts();
-
- content.evalScripts.bind(content).defer();
- return element;
- };
-}
-
-if ('outerHTML' in document.createElement('div')) {
- Element.Methods.replace = function(element, content) {
- element = $(element);
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) {
- element.parentNode.replaceChild(content, element);
- return element;
- }
-
- content = Object.toHTML(content);
- var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
-
- if (Element._insertionTranslations.tags[tagName]) {
- var nextSibling = element.next();
- var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
- parent.removeChild(element);
- if (nextSibling)
- fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
- else
- fragments.each(function(node) { parent.appendChild(node) });
- }
- else element.outerHTML = content.stripScripts();
-
- content.evalScripts.bind(content).defer();
- return element;
- };
-}
-
-Element._returnOffset = function(l, t) {
- var result = [l, t];
- result.left = l;
- result.top = t;
- return result;
-};
-
-Element._getContentFromAnonymousElement = function(tagName, html) {
- var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
- if (t) {
- div.innerHTML = t[0] + html + t[1];
- t[2].times(function() { div = div.firstChild });
- } else div.innerHTML = html;
- return $A(div.childNodes);
-};
-
-Element._insertionTranslations = {
- before: function(element, node) {
- element.parentNode.insertBefore(node, element);
- },
- top: function(element, node) {
- element.insertBefore(node, element.firstChild);
- },
- bottom: function(element, node) {
- element.appendChild(node);
- },
- after: function(element, node) {
- element.parentNode.insertBefore(node, element.nextSibling);
- },
- tags: {
- TABLE: ['<table>', '</table>', 1],
- TBODY: ['<table><tbody>', '</tbody></table>', 2],
- TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
- TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
- SELECT: ['<select>', '</select>', 1]
- }
-};
-
-(function() {
- Object.extend(this.tags, {
- THEAD: this.tags.TBODY,
- TFOOT: this.tags.TBODY,
- TH: this.tags.TD
- });
-}).call(Element._insertionTranslations);
-
-Element.Methods.Simulated = {
- hasAttribute: function(element, attribute) {
- attribute = Element._attributeTranslations.has[attribute] || attribute;
- var node = $(element).getAttributeNode(attribute);
- return node && node.specified;
- }
-};
-
-Element.Methods.ByTag = { };
-
-Object.extend(Element, Element.Methods);
-
-if (!Prototype.BrowserFeatures.ElementExtensions &&
- document.createElement('div').__proto__) {
- window.HTMLElement = { };
- window.HTMLElement.prototype = document.createElement('div').__proto__;
- Prototype.BrowserFeatures.ElementExtensions = true;
-}
-
-Element.extend = (function() {
- if (Prototype.BrowserFeatures.SpecificElementExtensions)
- return Prototype.K;
-
- var Methods = { }, ByTag = Element.Methods.ByTag;
-
- var extend = Object.extend(function(element) {
- if (!element || element._extendedByPrototype ||
- element.nodeType != 1 || element == window) return element;
-
- var methods = Object.clone(Methods),
- tagName = element.tagName, property, value;
-
- // extend methods for specific tags
- if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
-
- for (property in methods) {
- value = methods[property];
- if (Object.isFunction(value) && !(property in element))
- element[property] = value.methodize();
- }
-
- element._extendedByPrototype = Prototype.emptyFunction;
- return element;
-
- }, {
- refresh: function() {
- // extend methods for all tags (Safari doesn't need this)
- if (!Prototype.BrowserFeatures.ElementExtensions) {
- Object.extend(Methods, Element.Methods);
- Object.extend(Methods, Element.Methods.Simulated);
- }
- }
- });
-
- extend.refresh();
- return extend;
-})();
-
-Element.hasAttribute = function(element, attribute) {
- if (element.hasAttribute) return element.hasAttribute(attribute);
- return Element.Methods.Simulated.hasAttribute(element, attribute);
-};
-
-Element.addMethods = function(methods) {
- var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
-
- if (!methods) {
- Object.extend(Form, Form.Methods);
- Object.extend(Form.Element, Form.Element.Methods);
- Object.extend(Element.Methods.ByTag, {
- "FORM": Object.clone(Form.Methods),
- "INPUT": Object.clone(Form.Element.Methods),
- "SELECT": Object.clone(Form.Element.Methods),
- "TEXTAREA": Object.clone(Form.Element.Methods)
- });
- }
-
- if (arguments.length == 2) {
- var tagName = methods;
- methods = arguments[1];
- }
-
- if (!tagName) Object.extend(Element.Methods, methods || { });
- else {
- if (Object.isArray(tagName)) tagName.each(extend);
- else extend(tagName);
- }
-
- function extend(tagName) {
- tagName = tagName.toUpperCase();
- if (!Element.Methods.ByTag[tagName])
- Element.Methods.ByTag[tagName] = { };
- Object.extend(Element.Methods.ByTag[tagName], methods);
- }
-
- function copy(methods, destination, onlyIfAbsent) {
- onlyIfAbsent = onlyIfAbsent || false;
- for (var property in methods) {
- var value = methods[property];
- if (!Object.isFunction(value)) continue;
- if (!onlyIfAbsent || !(property in destination))
- destination[property] = value.methodize();
- }
- }
-
- function findDOMClass(tagName) {
- var klass;
- var trans = {
- "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
- "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
- "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
- "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
- "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
- "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
- "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
- "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
- "FrameSet", "IFRAME": "IFrame"
- };
- if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
- if (window[klass]) return window[klass];
- klass = 'HTML' + tagName + 'Element';
- if (window[klass]) return window[klass];
- klass = 'HTML' + tagName.capitalize() + 'Element';
- if (window[klass]) return window[klass];
-
- window[klass] = { };
- window[klass].prototype = document.createElement(tagName).__proto__;
- return window[klass];
- }
-
- if (F.ElementExtensions) {
- copy(Element.Methods, HTMLElement.prototype);
- copy(Element.Methods.Simulated, HTMLElement.prototype, true);
- }
-
- if (F.SpecificElementExtensions) {
- for (var tag in Element.Methods.ByTag) {
- var klass = findDOMClass(tag);
- if (Object.isUndefined(klass)) continue;
- copy(T[tag], klass.prototype);
- }
- }
-
- Object.extend(Element, Element.Methods);
- delete Element.ByTag;
-
- if (Element.extend.refresh) Element.extend.refresh();
- Element.cache = { };
-};
-
-document.viewport = {
- getDimensions: function() {
- var dimensions = { };
- var B = Prototype.Browser;
- $w('width height').each(function(d) {
- var D = d.capitalize();
- dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
- (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
- });
- return dimensions;
- },
-
- getWidth: function() {
- return this.getDimensions().width;
- },
-
- getHeight: function() {
- return this.getDimensions().height;
- },
-
- getScrollOffsets: function() {
- return Element._returnOffset(
- window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
- window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
- }
-};
-/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
- * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
- * license. Please see http://www.yui-ext.com/ for more information. */
-
-var Selector = Class.create({
- initialize: function(expression) {
- this.expression = expression.strip();
- this.compileMatcher();
- },
-
- shouldUseXPath: function() {
- if (!Prototype.BrowserFeatures.XPath) return false;
-
- var e = this.expression;
-
- // Safari 3 chokes on :*-of-type and :empty
- if (Prototype.Browser.WebKit &&
- (e.include("-of-type") || e.include(":empty")))
- return false;
-
- // XPath can't do namespaced attributes, nor can it read
- // the "checked" property from DOM nodes
- if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
- return false;
-
- return true;
- },
-
- compileMatcher: function() {
- if (this.shouldUseXPath())
- return this.compileXPathMatcher();
-
- var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
- c = Selector.criteria, le, p, m;
-
- if (Selector._cache[e]) {
- this.matcher = Selector._cache[e];
- return;
- }
-
- this.matcher = ["this.matcher = function(root) {",
- "var r = root, h = Selector.handlers, c = false, n;"];
-
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- p = ps[i];
- if (m = e.match(p)) {
- this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
- new Template(c[i]).evaluate(m));
- e = e.replace(m[0], '');
- break;
- }
- }
- }
-
- this.matcher.push("return h.unique(n);\n}");
- eval(this.matcher.join('\n'));
- Selector._cache[this.expression] = this.matcher;
- },
-
- compileXPathMatcher: function() {
- var e = this.expression, ps = Selector.patterns,
- x = Selector.xpath, le, m;
-
- if (Selector._cache[e]) {
- this.xpath = Selector._cache[e]; return;
- }
-
- this.matcher = ['.//*'];
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- if (m = e.match(ps[i])) {
- this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
- new Template(x[i]).evaluate(m));
- e = e.replace(m[0], '');
- break;
- }
- }
- }
-
- this.xpath = this.matcher.join('');
- Selector._cache[this.expression] = this.xpath;
- },
-
- findElements: function(root) {
- root = root || document;
- if (this.xpath) return document._getElementsByXPath(this.xpath, root);
- return this.matcher(root);
- },
-
- match: function(element) {
- this.tokens = [];
-
- var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
- var le, p, m;
-
- while (e && le !== e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- p = ps[i];
- if (m = e.match(p)) {
- // use the Selector.assertions methods unless the selector
- // is too complex.
- if (as[i]) {
- this.tokens.push([i, Object.clone(m)]);
- e = e.replace(m[0], '');
- } else {
- // reluctantly do a document-wide search
- // and look for a match in the array
- return this.findElements(document).include(element);
- }
- }
- }
- }
-
- var match = true, name, matches;
- for (var i = 0, token; token = this.tokens[i]; i++) {
- name = token[0], matches = token[1];
- if (!Selector.assertions[name](element, matches)) {
- match = false; break;
- }
- }
-
- return match;
- },
-
- toString: function() {
- return this.expression;
- },
-
- inspect: function() {
- return "#<Selector:" + this.expression.inspect() + ">";
- }
-});
-
-Object.extend(Selector, {
- _cache: { },
-
- xpath: {
- descendant: "//*",
- child: "/*",
- adjacent: "/following-sibling::*[1]",
- laterSibling: '/following-sibling::*',
- tagName: function(m) {
- if (m[1] == '*') return '';
- return "[local-name()='" + m[1].toLowerCase() +
- "' or local-name()='" + m[1].toUpperCase() + "']";
- },
- className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
- id: "[@id='#{1}']",
- attrPresence: function(m) {
- m[1] = m[1].toLowerCase();
- return new Template("[@#{1}]").evaluate(m);
- },
- attr: function(m) {
- m[1] = m[1].toLowerCase();
- m[3] = m[5] || m[6];
- return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
- },
- pseudo: function(m) {
- var h = Selector.xpath.pseudos[m[1]];
- if (!h) return '';
- if (Object.isFunction(h)) return h(m);
- return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
- },
- operators: {
- '=': "[@#{1}='#{3}']",
- '!=': "[@#{1}!='#{3}']",
- '^=': "[starts-with(@#{1}, '#{3}')]",
- '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
- '*=': "[contains(@#{1}, '#{3}')]",
- '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
- '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
- },
- pseudos: {
- 'first-child': '[not(preceding-sibling::*)]',
- 'last-child': '[not(following-sibling::*)]',
- 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
- 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
- 'checked': "[@checked]",
- 'disabled': "[@disabled]",
- 'enabled': "[not(@disabled)]",
- 'not': function(m) {
- var e = m[6], p = Selector.patterns,
- x = Selector.xpath, le, v;
-
- var exclusion = [];
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in p) {
- if (m = e.match(p[i])) {
- v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
- exclusion.push("(" + v.substring(1, v.length - 1) + ")");
- e = e.replace(m[0], '');
- break;
- }
- }
- }
- return "[not(" + exclusion.join(" and ") + ")]";
- },
- 'nth-child': function(m) {
- return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
- },
- 'nth-last-child': function(m) {
- return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
- },
- 'nth-of-type': function(m) {
- return Selector.xpath.pseudos.nth("position() ", m);
- },
- 'nth-last-of-type': function(m) {
- return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
- },
- 'first-of-type': function(m) {
- m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
- },
- 'last-of-type': function(m) {
- m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
- },
- 'only-of-type': function(m) {
- var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
- },
- nth: function(fragment, m) {
- var mm, formula = m[6], predicate;
- if (formula == 'even') formula = '2n+0';
- if (formula == 'odd') formula = '2n+1';
- if (mm = formula.match(/^(\d+)$/)) // digit only
- return '[' + fragment + "= " + mm[1] + ']';
- if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
- if (mm[1] == "-") mm[1] = -1;
- var a = mm[1] ? Number(mm[1]) : 1;
- var b = mm[2] ? Number(mm[2]) : 0;
- predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
- "((#{fragment} - #{b}) div #{a} >= 0)]";
- return new Template(predicate).evaluate({
- fragment: fragment, a: a, b: b });
- }
- }
- }
- },
-
- criteria: {
- tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
- className: 'n = h.className(n, r, "#{1}", c); c = false;',
- id: 'n = h.id(n, r, "#{1}", c); c = false;',
- attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
- attr: function(m) {
- m[3] = (m[5] || m[6]);
- return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
- },
- pseudo: function(m) {
- if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
- return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
- },
- descendant: 'c = "descendant";',
- child: 'c = "child";',
- adjacent: 'c = "adjacent";',
- laterSibling: 'c = "laterSibling";'
- },
-
- patterns: {
- // combinators must be listed first
- // (and descendant needs to be last combinator)
- laterSibling: /^\s*~\s*/,
- child: /^\s*>\s*/,
- adjacent: /^\s*\+\s*/,
- descendant: /^\s/,
-
- // selectors follow
- tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
- id: /^#([\w\-\*]+)(\b|$)/,
- className: /^\.([\w\-\*]+)(\b|$)/,
- pseudo:
-/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
- attrPresence: /^\[([\w]+)\]/,
- attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
- },
-
- // for Selector.match and Element#match
- assertions: {
- tagName: function(element, matches) {
- return matches[1].toUpperCase() == element.tagName.toUpperCase();
- },
-
- className: function(element, matches) {
- return Element.hasClassName(element, matches[1]);
- },
-
- id: function(element, matches) {
- return element.id === matches[1];
- },
-
- attrPresence: function(element, matches) {
- return Element.hasAttribute(element, matches[1]);
- },
-
- attr: function(element, matches) {
- var nodeValue = Element.readAttribute(element, matches[1]);
- return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
- }
- },
-
- handlers: {
- // UTILITY FUNCTIONS
- // joins two collections
- concat: function(a, b) {
- for (var i = 0, node; node = b[i]; i++)
- a.push(node);
- return a;
- },
-
- // marks an array of nodes for counting
- mark: function(nodes) {
- var _true = Prototype.emptyFunction;
- for (var i = 0, node; node = nodes[i]; i++)
- node._countedByPrototype = _true;
- return nodes;
- },
-
- unmark: function(nodes) {
- for (var i = 0, node; node = nodes[i]; i++)
- node._countedByPrototype = undefined;
- return nodes;
- },
-
- // mark each child node with its position (for nth calls)
- // "ofType" flag indicates whether we're indexing for nth-of-type
- // rather than nth-child
- index: function(parentNode, reverse, ofType) {
- parentNode._countedByPrototype = Prototype.emptyFunction;
- if (reverse) {
- for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
- var node = nodes[i];
- if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
- }
- } else {
- for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
- if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
- }
- },
-
- // filters out duplicates and extends all nodes
- unique: function(nodes) {
- if (nodes.length == 0) return nodes;
- var results = [], n;
- for (var i = 0, l = nodes.length; i < l; i++)
- if (!(n = nodes[i])._countedByPrototype) {
- n._countedByPrototype = Prototype.emptyFunction;
- results.push(Element.extend(n));
- }
- return Selector.handlers.unmark(results);
- },
-
- // COMBINATOR FUNCTIONS
- descendant: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- h.concat(results, node.getElementsByTagName('*'));
- return results;
- },
-
- child: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- for (var j = 0, child; child = node.childNodes[j]; j++)
- if (child.nodeType == 1 && child.tagName != '!') results.push(child);
- }
- return results;
- },
-
- adjacent: function(nodes) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- var next = this.nextElementSibling(node);
- if (next) results.push(next);
- }
- return results;
- },
-
- laterSibling: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- h.concat(results, Element.nextSiblings(node));
- return results;
- },
-
- nextElementSibling: function(node) {
- while (node = node.nextSibling)
- if (node.nodeType == 1) return node;
- return null;
- },
-
- previousElementSibling: function(node) {
- while (node = node.previousSibling)
- if (node.nodeType == 1) return node;
- return null;
- },
-
- // TOKEN FUNCTIONS
- tagName: function(nodes, root, tagName, combinator) {
- var uTagName = tagName.toUpperCase();
- var results = [], h = Selector.handlers;
- if (nodes) {
- if (combinator) {
- // fastlane for ordinary descendant combinators
- if (combinator == "descendant") {
- for (var i = 0, node; node = nodes[i]; i++)
- h.concat(results, node.getElementsByTagName(tagName));
- return results;
- } else nodes = this[combinator](nodes);
- if (tagName == "*") return nodes;
- }
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.tagName.toUpperCase() === uTagName) results.push(node);
- return results;
- } else return root.getElementsByTagName(tagName);
- },
-
- id: function(nodes, root, id, combinator) {
- var targetNode = $(id), h = Selector.handlers;
- if (!targetNode) return [];
- if (!nodes && root == document) return [targetNode];
- if (nodes) {
- if (combinator) {
- if (combinator == 'child') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (targetNode.parentNode == node) return [targetNode];
- } else if (combinator == 'descendant') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (Element.descendantOf(targetNode, node)) return [targetNode];
- } else if (combinator == 'adjacent') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (Selector.handlers.previousElementSibling(targetNode) == node)
- return [targetNode];
- } else nodes = h[combinator](nodes);
- }
- for (var i = 0, node; node = nodes[i]; i++)
- if (node == targetNode) return [targetNode];
- return [];
- }
- return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
- },
-
- className: function(nodes, root, className, combinator) {
- if (nodes && combinator) nodes = this[combinator](nodes);
- return Selector.handlers.byClassName(nodes, root, className);
- },
-
- byClassName: function(nodes, root, className) {
- if (!nodes) nodes = Selector.handlers.descendant([root]);
- var needle = ' ' + className + ' ';
- for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
- nodeClassName = node.className;
- if (nodeClassName.length == 0) continue;
- if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
- results.push(node);
- }
- return results;
- },
-
- attrPresence: function(nodes, root, attr, combinator) {
- if (!nodes) nodes = root.getElementsByTagName("*");
- if (nodes && combinator) nodes = this[combinator](nodes);
- var results = [];
- for (var i = 0, node; node = nodes[i]; i++)
- if (Element.hasAttribute(node, attr)) results.push(node);
- return results;
- },
-
- attr: function(nodes, root, attr, value, operator, combinator) {
- if (!nodes) nodes = root.getElementsByTagName("*");
- if (nodes && combinator) nodes = this[combinator](nodes);
- var handler = Selector.operators[operator], results = [];
- for (var i = 0, node; node = nodes[i]; i++) {
- var nodeValue = Element.readAttribute(node, attr);
- if (nodeValue === null) continue;
- if (handler(nodeValue, value)) results.push(node);
- }
- return results;
- },
-
- pseudo: function(nodes, name, value, root, combinator) {
- if (nodes && combinator) nodes = this[combinator](nodes);
- if (!nodes) nodes = root.getElementsByTagName("*");
- return Selector.pseudos[name](nodes, value, root);
- }
- },
-
- pseudos: {
- 'first-child': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- if (Selector.handlers.previousElementSibling(node)) continue;
- results.push(node);
- }
- return results;
- },
- 'last-child': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- if (Selector.handlers.nextElementSibling(node)) continue;
- results.push(node);
- }
- return results;
- },
- 'only-child': function(nodes, value, root) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
- results.push(node);
- return results;
- },
- 'nth-child': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root);
- },
- 'nth-last-child': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, true);
- },
- 'nth-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, false, true);
- },
- 'nth-last-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, true, true);
- },
- 'first-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, "1", root, false, true);
- },
- 'last-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, "1", root, true, true);
- },
- 'only-of-type': function(nodes, formula, root) {
- var p = Selector.pseudos;
- return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
- },
-
- // handles the an+b logic
- getIndices: function(a, b, total) {
- if (a == 0) return b > 0 ? [b] : [];
- return $R(1, total).inject([], function(memo, i) {
- if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
- return memo;
- });
- },
-
- // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
- nth: function(nodes, formula, root, reverse, ofType) {
- if (nodes.length == 0) return [];
- if (formula == 'even') formula = '2n+0';
- if (formula == 'odd') formula = '2n+1';
- var h = Selector.handlers, results = [], indexed = [], m;
- h.mark(nodes);
- for (var i = 0, node; node = nodes[i]; i++) {
- if (!node.parentNode._countedByPrototype) {
- h.index(node.parentNode, reverse, ofType);
- indexed.push(node.parentNode);
- }
- }
- if (formula.match(/^\d+$/)) { // just a number
- formula = Number(formula);
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.nodeIndex == formula) results.push(node);
- } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
- if (m[1] == "-") m[1] = -1;
- var a = m[1] ? Number(m[1]) : 1;
- var b = m[2] ? Number(m[2]) : 0;
- var indices = Selector.pseudos.getIndices(a, b, nodes.length);
- for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
- for (var j = 0; j < l; j++)
- if (node.nodeIndex == indices[j]) results.push(node);
- }
- }
- h.unmark(nodes);
- h.unmark(indexed);
- return results;
- },
-
- 'empty': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- // IE treats comments as element nodes
- if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
- results.push(node);
- }
- return results;
- },
-
- 'not': function(nodes, selector, root) {
- var h = Selector.handlers, selectorType, m;
- var exclusions = new Selector(selector).findElements(root);
- h.mark(exclusions);
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!node._countedByPrototype) results.push(node);
- h.unmark(exclusions);
- return results;
- },
-
- 'enabled': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!node.disabled) results.push(node);
- return results;
- },
-
- 'disabled': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (node.disabled) results.push(node);
- return results;
- },
-
- 'checked': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (node.checked) results.push(node);
- return results;
- }
- },
-
- operators: {
- '=': function(nv, v) { return nv == v; },
- '!=': function(nv, v) { return nv != v; },
- '^=': function(nv, v) { return nv.startsWith(v); },
- '$=': function(nv, v) { return nv.endsWith(v); },
- '*=': function(nv, v) { return nv.include(v); },
- '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
- '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
- },
-
- split: function(expression) {
- var expressions = [];
- expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
- expressions.push(m[1].strip());
- });
- return expressions;
- },
-
- matchElements: function(elements, expression) {
- var matches = $$(expression), h = Selector.handlers;
- h.mark(matches);
- for (var i = 0, results = [], element; element = elements[i]; i++)
- if (element._countedByPrototype) results.push(element);
- h.unmark(matches);
- return results;
- },
-
- findElement: function(elements, expression, index) {
- if (Object.isNumber(expression)) {
- index = expression; expression = false;
- }
- return Selector.matchElements(elements, expression || '*')[index || 0];
- },
-
- findChildElements: function(element, expressions) {
- expressions = Selector.split(expressions.join(','));
- var results = [], h = Selector.handlers;
- for (var i = 0, l = expressions.length, selector; i < l; i++) {
- selector = new Selector(expressions[i].strip());
- h.concat(results, selector.findElements(element));
- }
- return (l > 1) ? h.unique(results) : results;
- }
-});
-
-if (Prototype.Browser.IE) {
- Object.extend(Selector.handlers, {
- // IE returns comment nodes on getElementsByTagName("*").
- // Filter them out.
- concat: function(a, b) {
- for (var i = 0, node; node = b[i]; i++)
- if (node.tagName !== "!") a.push(node);
- return a;
- },
-
- // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
- unmark: function(nodes) {
- for (var i = 0, node; node = nodes[i]; i++)
- node.removeAttribute('_countedByPrototype');
- return nodes;
- }
- });
-}
-
-function $$() {
- return Selector.findChildElements(document, $A(arguments));
-}
-var Form = {
- reset: function(form) {
- $(form).reset();
- return form;
- },
-
- serializeElements: function(elements, options) {
- if (typeof options != 'object') options = { hash: !!options };
- else if (Object.isUndefined(options.hash)) options.hash = true;
- var key, value, submitted = false, submit = options.submit;
-
- var data = elements.inject({ }, function(result, element) {
- if (!element.disabled && element.name) {
- key = element.name; value = $(element).getValue();
- if (value != null && (element.type != 'submit' || (!submitted &&
- submit !== false && (!submit || key == submit) && (submitted = true)))) {
- if (key in result) {
- // a key is already present; construct an array of values
- if (!Object.isArray(result[key])) result[key] = [result[key]];
- result[key].push(value);
- }
- else result[key] = value;
- }
- }
- return result;
- });
-
- return options.hash ? data : Object.toQueryString(data);
- }
-};
-
-Form.Methods = {
- serialize: function(form, options) {
- return Form.serializeElements(Form.getElements(form), options);
- },
-
- getElements: function(form) {
- return $A($(form).getElementsByTagName('*')).inject([],
- function(elements, child) {
- if (Form.Element.Serializers[child.tagName.toLowerCase()])
- elements.push(Element.extend(child));
- return elements;
- }
- );
- },
-
- getInputs: function(form, typeName, name) {
- form = $(form);
- var inputs = form.getElementsByTagName('input');
-
- if (!typeName && !name) return $A(inputs).map(Element.extend);
-
- for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
- var input = inputs[i];
- if ((typeName && input.type != typeName) || (name && input.name != name))
- continue;
- matchingInputs.push(Element.extend(input));
- }
-
- return matchingInputs;
- },
-
- disable: function(form) {
- form = $(form);
- Form.getElements(form).invoke('disable');
- return form;
- },
-
- enable: function(form) {
- form = $(form);
- Form.getElements(form).invoke('enable');
- return form;
- },
-
- findFirstElement: function(form) {
- var elements = $(form).getElements().findAll(function(element) {
- return 'hidden' != element.type && !element.disabled;
- });
- var firstByIndex = elements.findAll(function(element) {
- return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
- }).sortBy(function(element) { return element.tabIndex }).first();
-
- return firstByIndex ? firstByIndex : elements.find(function(element) {
- return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
- });
- },
-
- focusFirstElement: function(form) {
- form = $(form);
- form.findFirstElement().activate();
- return form;
- },
-
- request: function(form, options) {
- form = $(form), options = Object.clone(options || { });
-
- var params = options.parameters, action = form.readAttribute('action') || '';
- if (action.blank()) action = window.location.href;
- options.parameters = form.serialize(true);
-
- if (params) {
- if (Object.isString(params)) params = params.toQueryParams();
- Object.extend(options.parameters, params);
- }
-
- if (form.hasAttribute('method') && !options.method)
- options.method = form.method;
-
- return new Ajax.Request(action, options);
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-Form.Element = {
- focus: function(element) {
- $(element).focus();
- return element;
- },
-
- select: function(element) {
- $(element).select();
- return element;
- }
-};
-
-Form.Element.Methods = {
- serialize: function(element) {
- element = $(element);
- if (!element.disabled && element.name) {
- var value = element.getValue();
- if (value != undefined) {
- var pair = { };
- pair[element.name] = value;
- return Object.toQueryString(pair);
- }
- }
- return '';
- },
-
- getValue: function(element) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- return Form.Element.Serializers[method](element);
- },
-
- setValue: function(element, value) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- Form.Element.Serializers[method](element, value);
- return element;
- },
-
- clear: function(element) {
- $(element).value = '';
- return element;
- },
-
- present: function(element) {
- return $(element).value != '';
- },
-
- activate: function(element) {
- element = $(element);
- try {
- element.focus();
- if (element.select && (element.tagName.toLowerCase() != 'input' ||
- !['button', 'reset', 'submit'].include(element.type)))
- element.select();
- } catch (e) { }
- return element;
- },
-
- disable: function(element) {
- element = $(element);
- element.blur();
- element.disabled = true;
- return element;
- },
-
- enable: function(element) {
- element = $(element);
- element.disabled = false;
- return element;
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-var Field = Form.Element;
-var $F = Form.Element.Methods.getValue;
-
-/*--------------------------------------------------------------------------*/
-
-Form.Element.Serializers = {
- input: function(element, value) {
- switch (element.type.toLowerCase()) {
- case 'checkbox':
- case 'radio':
- return Form.Element.Serializers.inputSelector(element, value);
- default:
- return Form.Element.Serializers.textarea(element, value);
- }
- },
-
- inputSelector: function(element, value) {
- if (Object.isUndefined(value)) return element.checked ? element.value : null;
- else element.checked = !!value;
- },
-
- textarea: function(element, value) {
- if (Object.isUndefined(value)) return element.value;
- else element.value = value;
- },
-
- select: function(element, index) {
- if (Object.isUndefined(index))
- return this[element.type == 'select-one' ?
- 'selectOne' : 'selectMany'](element);
- else {
- var opt, value, single = !Object.isArray(index);
- for (var i = 0, length = element.length; i < length; i++) {
- opt = element.options[i];
- value = this.optionValue(opt);
- if (single) {
- if (value == index) {
- opt.selected = true;
- return;
- }
- }
- else opt.selected = index.include(value);
- }
- }
- },
-
- selectOne: function(element) {
- var index = element.selectedIndex;
- return index >= 0 ? this.optionValue(element.options[index]) : null;
- },
-
- selectMany: function(element) {
- var values, length = element.length;
- if (!length) return null;
-
- for (var i = 0, values = []; i < length; i++) {
- var opt = element.options[i];
- if (opt.selected) values.push(this.optionValue(opt));
- }
- return values;
- },
-
- optionValue: function(opt) {
- // extend element because hasAttribute may not be native
- return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
- initialize: function($super, element, frequency, callback) {
- $super(callback, frequency);
- this.element = $(element);
- this.lastValue = this.getValue();
- },
-
- execute: function() {
- var value = this.getValue();
- if (Object.isString(this.lastValue) && Object.isString(value) ?
- this.lastValue != value : String(this.lastValue) != String(value)) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- }
-});
-
-Form.Element.Observer = Class.create(Abstract.TimedObserver, {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.Observer = Class.create(Abstract.TimedObserver, {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.EventObserver = Class.create({
- initialize: function(element, callback) {
- this.element = $(element);
- this.callback = callback;
-
- this.lastValue = this.getValue();
- if (this.element.tagName.toLowerCase() == 'form')
- this.registerFormCallbacks();
- else
- this.registerCallback(this.element);
- },
-
- onElementEvent: function() {
- var value = this.getValue();
- if (this.lastValue != value) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- },
-
- registerFormCallbacks: function() {
- Form.getElements(this.element).each(this.registerCallback, this);
- },
-
- registerCallback: function(element) {
- if (element.type) {
- switch (element.type.toLowerCase()) {
- case 'checkbox':
- case 'radio':
- Event.observe(element, 'click', this.onElementEvent.bind(this));
- break;
- default:
- Event.observe(element, 'change', this.onElementEvent.bind(this));
- break;
- }
- }
- }
-});
-
-Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.EventObserver = Class.create(Abstract.EventObserver, {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-if (!window.Event) var Event = { };
-
-Object.extend(Event, {
- KEY_BACKSPACE: 8,
- KEY_TAB: 9,
- KEY_RETURN: 13,
- KEY_ESC: 27,
- KEY_LEFT: 37,
- KEY_UP: 38,
- KEY_RIGHT: 39,
- KEY_DOWN: 40,
- KEY_DELETE: 46,
- KEY_HOME: 36,
- KEY_END: 35,
- KEY_PAGEUP: 33,
- KEY_PAGEDOWN: 34,
- KEY_INSERT: 45,
-
- cache: { },
-
- relatedTarget: function(event) {
- var element;
- switch(event.type) {
- case 'mouseover': element = event.fromElement; break;
- case 'mouseout': element = event.toElement; break;
- default: return null;
- }
- return Element.extend(element);
- }
-});
-
-Event.Methods = (function() {
- var isButton;
-
- if (Prototype.Browser.IE) {
- var buttonMap = { 0: 1, 1: 4, 2: 2 };
- isButton = function(event, code) {
- return event.button == buttonMap[code];
- };
-
- } else if (Prototype.Browser.WebKit) {
- isButton = function(event, code) {
- switch (code) {
- case 0: return event.which == 1 && !event.metaKey;
- case 1: return event.which == 1 && event.metaKey;
- default: return false;
- }
- };
-
- } else {
- isButton = function(event, code) {
- return event.which ? (event.which === code + 1) : (event.button === code);
- };
- }
-
- return {
- isLeftClick: function(event) { return isButton(event, 0) },
- isMiddleClick: function(event) { return isButton(event, 1) },
- isRightClick: function(event) { return isButton(event, 2) },
-
- element: function(event) {
- var node = Event.extend(event).target;
- return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
- },
-
- findElement: function(event, expression) {
- var element = Event.element(event);
- if (!expression) return element;
- var elements = [element].concat(element.ancestors());
- return Selector.findElement(elements, expression, 0);
- },
-
- pointer: function(event) {
- return {
- x: event.pageX || (event.clientX +
- (document.documentElement.scrollLeft || document.body.scrollLeft)),
- y: event.pageY || (event.clientY +
- (document.documentElement.scrollTop || document.body.scrollTop))
- };
- },
-
- pointerX: function(event) { return Event.pointer(event).x },
- pointerY: function(event) { return Event.pointer(event).y },
-
- stop: function(event) {
- Event.extend(event);
- event.preventDefault();
- event.stopPropagation();
- event.stopped = true;
- }
- };
-})();
-
-Event.extend = (function() {
- var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
- m[name] = Event.Methods[name].methodize();
- return m;
- });
-
- if (Prototype.Browser.IE) {
- Object.extend(methods, {
- stopPropagation: function() { this.cancelBubble = true },
- preventDefault: function() { this.returnValue = false },
- inspect: function() { return "[object Event]" }
- });
-
- return function(event) {
- if (!event) return false;
- if (event._extendedByPrototype) return event;
-
- event._extendedByPrototype = Prototype.emptyFunction;
- var pointer = Event.pointer(event);
- Object.extend(event, {
- target: event.srcElement,
- relatedTarget: Event.relatedTarget(event),
- pageX: pointer.x,
- pageY: pointer.y
- });
- return Object.extend(event, methods);
- };
-
- } else {
- Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
- Object.extend(Event.prototype, methods);
- return Prototype.K;
- }
-})();
-
-Object.extend(Event, (function() {
- var cache = Event.cache;
-
- function getEventID(element) {
- if (element._prototypeEventID) return element._prototypeEventID[0];
- arguments.callee.id = arguments.callee.id || 1;
- return element._prototypeEventID = [++arguments.callee.id];
- }
-
- function getDOMEventName(eventName) {
- if (eventName && eventName.include(':')) return "dataavailable";
- return eventName;
- }
-
- function getCacheForID(id) {
- return cache[id] = cache[id] || { };
- }
-
- function getWrappersForEventName(id, eventName) {
- var c = getCacheForID(id);
- return c[eventName] = c[eventName] || [];
- }
-
- function createWrapper(element, eventName, handler) {
- var id = getEventID(element);
- var c = getWrappersForEventName(id, eventName);
- if (c.pluck("handler").include(handler)) return false;
-
- var wrapper = function(event) {
- if (!Event || !Event.extend ||
- (event.eventName && event.eventName != eventName))
- return false;
-
- Event.extend(event);
- handler.call(element, event);
- };
-
- wrapper.handler = handler;
- c.push(wrapper);
- return wrapper;
- }
-
- function findWrapper(id, eventName, handler) {
- var c = getWrappersForEventName(id, eventName);
- return c.find(function(wrapper) { return wrapper.handler == handler });
- }
-
- function destroyWrapper(id, eventName, handler) {
- var c = getCacheForID(id);
- if (!c[eventName]) return false;
- c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
- }
-
- function destroyCache() {
- for (var id in cache)
- for (var eventName in cache[id])
- cache[id][eventName] = null;
- }
-
- if (window.attachEvent) {
- window.attachEvent("onunload", destroyCache);
- }
-
- return {
- observe: function(element, eventName, handler) {
- element = $(element);
- var name = getDOMEventName(eventName);
-
- var wrapper = createWrapper(element, eventName, handler);
- if (!wrapper) return element;
-
- if (element.addEventListener) {
- element.addEventListener(name, wrapper, false);
- } else {
- element.attachEvent("on" + name, wrapper);
- }
-
- return element;
- },
-
- stopObserving: function(element, eventName, handler) {
- element = $(element);
- var id = getEventID(element), name = getDOMEventName(eventName);
-
- if (!handler && eventName) {
- getWrappersForEventName(id, eventName).each(function(wrapper) {
- element.stopObserving(eventName, wrapper.handler);
- });
- return element;
-
- } else if (!eventName) {
- Object.keys(getCacheForID(id)).each(function(eventName) {
- element.stopObserving(eventName);
- });
- return element;
- }
-
- var wrapper = findWrapper(id, eventName, handler);
- if (!wrapper) return element;
-
- if (element.removeEventListener) {
- element.removeEventListener(name, wrapper, false);
- } else {
- element.detachEvent("on" + name, wrapper);
- }
-
- destroyWrapper(id, eventName, handler);
-
- return element;
- },
-
- fire: function(element, eventName, memo) {
- element = $(element);
- if (element == document && document.createEvent && !element.dispatchEvent)
- element = document.documentElement;
-
- var event;
- if (document.createEvent) {
- event = document.createEvent("HTMLEvents");
- event.initEvent("dataavailable", true, true);
- } else {
- event = document.createEventObject();
- event.eventType = "ondataavailable";
- }
-
- event.eventName = eventName;
- event.memo = memo || { };
-
- if (document.createEvent) {
- element.dispatchEvent(event);
- } else {
- element.fireEvent(event.eventType, event);
- }
-
- return Event.extend(event);
- }
- };
-})());
-
-Object.extend(Event, Event.Methods);
-
-Element.addMethods({
- fire: Event.fire,
- observe: Event.observe,
- stopObserving: Event.stopObserving
-});
-
-Object.extend(document, {
- fire: Element.Methods.fire.methodize(),
- observe: Element.Methods.observe.methodize(),
- stopObserving: Element.Methods.stopObserving.methodize(),
- loaded: false
-});
-
-(function() {
- /* Support for the DOMContentLoaded event is based on work by Dan Webb,
- Matthias Miller, Dean Edwards and John Resig. */
-
- var timer;
-
- function fireContentLoadedEvent() {
- if (document.loaded) return;
- if (timer) window.clearInterval(timer);
- document.fire("dom:loaded");
- document.loaded = true;
- }
-
- if (document.addEventListener) {
- if (Prototype.Browser.WebKit) {
- timer = window.setInterval(function() {
- if (/loaded|complete/.test(document.readyState))
- fireContentLoadedEvent();
- }, 0);
-
- Event.observe(window, "load", fireContentLoadedEvent);
-
- } else {
- document.addEventListener("DOMContentLoaded",
- fireContentLoadedEvent, false);
- }
-
- } else {
- document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
- $("__onDOMContentLoaded").onreadystatechange = function() {
- if (this.readyState == "complete") {
- this.onreadystatechange = null;
- fireContentLoadedEvent();
- }
- };
- }
-})();
-/*------------------------------- DEPRECATED -------------------------------*/
-
-Hash.toQueryString = Object.toQueryString;
-
-var Toggle = { display: Element.toggle };
-
-Element.Methods.childOf = Element.Methods.descendantOf;
-
-var Insertion = {
- Before: function(element, content) {
- return Element.insert(element, {before:content});
- },
-
- Top: function(element, content) {
- return Element.insert(element, {top:content});
- },
-
- Bottom: function(element, content) {
- return Element.insert(element, {bottom:content});
- },
-
- After: function(element, content) {
- return Element.insert(element, {after:content});
- }
-};
-
-var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
-
-// This should be moved to script.aculo.us; notice the deprecated methods
-// further below, that map to the newer Element methods.
-var Position = {
- // set to true if needed, warning: firefox performance problems
- // NOT neeeded for page scrolling, only if draggable contained in
- // scrollable elements
- includeScrollOffsets: false,
-
- // must be called before calling withinIncludingScrolloffset, every time the
- // page is scrolled
- prepare: function() {
- this.deltaX = window.pageXOffset
- || document.documentElement.scrollLeft
- || document.body.scrollLeft
- || 0;
- this.deltaY = window.pageYOffset
- || document.documentElement.scrollTop
- || document.body.scrollTop
- || 0;
- },
-
- // caches x/y coordinate pair to use with overlap
- within: function(element, x, y) {
- if (this.includeScrollOffsets)
- return this.withinIncludingScrolloffsets(element, x, y);
- this.xcomp = x;
- this.ycomp = y;
- this.offset = Element.cumulativeOffset(element);
-
- return (y >= this.offset[1] &&
- y < this.offset[1] + element.offsetHeight &&
- x >= this.offset[0] &&
- x < this.offset[0] + element.offsetWidth);
- },
-
- withinIncludingScrolloffsets: function(element, x, y) {
- var offsetcache = Element.cumulativeScrollOffset(element);
-
- this.xcomp = x + offsetcache[0] - this.deltaX;
- this.ycomp = y + offsetcache[1] - this.deltaY;
- this.offset = Element.cumulativeOffset(element);
-
- return (this.ycomp >= this.offset[1] &&
- this.ycomp < this.offset[1] + element.offsetHeight &&
- this.xcomp >= this.offset[0] &&
- this.xcomp < this.offset[0] + element.offsetWidth);
- },
-
- // within must be called directly before
- overlap: function(mode, element) {
- if (!mode) return 0;
- if (mode == 'vertical')
- return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
- element.offsetHeight;
- if (mode == 'horizontal')
- return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
- element.offsetWidth;
- },
-
- // Deprecation layer -- use newer Element methods now (1.5.2).
-
- cumulativeOffset: Element.Methods.cumulativeOffset,
-
- positionedOffset: Element.Methods.positionedOffset,
-
- absolutize: function(element) {
- Position.prepare();
- return Element.absolutize(element);
- },
-
- relativize: function(element) {
- Position.prepare();
- return Element.relativize(element);
- },
-
- realOffset: Element.Methods.cumulativeScrollOffset,
-
- offsetParent: Element.Methods.getOffsetParent,
-
- page: Element.Methods.viewportOffset,
-
- clone: function(source, target, options) {
- options = options || { };
- return Element.clonePosition(target, source, options);
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
- function iter(name) {
- return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
- }
-
- instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
- function(element, className) {
- className = className.toString().strip();
- var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
- return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
- } : function(element, className) {
- className = className.toString().strip();
- var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
- if (!classNames && !className) return elements;
-
- var nodes = $(element).getElementsByTagName('*');
- className = ' ' + className + ' ';
-
- for (var i = 0, child, cn; child = nodes[i]; i++) {
- if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
- (classNames && classNames.all(function(name) {
- return !name.toString().blank() && cn.include(' ' + name + ' ');
- }))))
- elements.push(Element.extend(child));
- }
- return elements;
- };
-
- return function(className, parentElement) {
- return $(parentElement || document.body).getElementsByClassName(className);
- };
-}(Element.Methods);
-
-/*--------------------------------------------------------------------------*/
-
-Element.ClassNames = Class.create();
-Element.ClassNames.prototype = {
- initialize: function(element) {
- this.element = $(element);
- },
-
- _each: function(iterator) {
- this.element.className.split(/\s+/).select(function(name) {
- return name.length > 0;
- })._each(iterator);
- },
-
- set: function(className) {
- this.element.className = className;
- },
-
- add: function(classNameToAdd) {
- if (this.include(classNameToAdd)) return;
- this.set($A(this).concat(classNameToAdd).join(' '));
- },
-
- remove: function(classNameToRemove) {
- if (!this.include(classNameToRemove)) return;
- this.set($A(this).without(classNameToRemove).join(' '));
- },
-
- toString: function() {
- return $A(this).join(' ');
- }
-};
-
-Object.extend(Element.ClassNames.prototype, Enumerable);
-
-/*--------------------------------------------------------------------------*/
-
-Element.addMethods(); \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index 77f19b36a6..3e734ccaab 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -220,8 +220,6 @@ module ActionView
end
end
- STORAGE_UNITS = %w( Bytes KB MB GB TB ).freeze
-
# Formats the bytes in +size+ into a more understandable representation
# (e.g., giving it 1500 yields 1.5 KB). This method is useful for
# reporting file sizes to users. This method returns nil if
@@ -257,6 +255,7 @@ module ActionView
defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {}
human = I18n.translate(:'number.human.format', :locale => options[:locale], :raise => true) rescue {}
defaults = defaults.merge(human)
+ storage_units = I18n.translate(:'number.human.storage_units', :locale => options[:locale], :raise => true)
unless args.empty?
ActiveSupport::Deprecation.warn('number_to_human_size takes an option hash ' +
@@ -268,12 +267,12 @@ module ActionView
separator ||= (options[:separator] || defaults[:separator])
delimiter ||= (options[:delimiter] || defaults[:delimiter])
- max_exp = STORAGE_UNITS.size - 1
+ max_exp = storage_units.size - 1
number = Float(number)
exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024
exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
number /= 1024 ** exponent
- unit = STORAGE_UNITS[exponent]
+ unit = storage_units[exponent]
begin
escaped_separator = Regexp.escape(separator)
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index a3eccc741d..7fab3102e7 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -1,4 +1,5 @@
require 'set'
+require 'active_support/json'
module ActionView
module Helpers
diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb
index 435ba936e1..d89b955317 100644
--- a/actionpack/lib/action_view/helpers/sanitize_helper.rb
+++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb
@@ -1,15 +1,5 @@
require 'action_view/helpers/tag_helper'
-begin
- require 'html/document'
-rescue LoadError
- html_scanner_path = "#{File.dirname(__FILE__)}/../../action_controller/vendor/html-scanner"
- if File.directory?(html_scanner_path)
- $:.unshift html_scanner_path
- require 'html/document'
- end
-end
-
module ActionView
module Helpers #:nodoc:
# The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
diff --git a/actionpack/lib/action_view/helpers/scriptaculous_helper.rb b/actionpack/lib/action_view/helpers/scriptaculous_helper.rb
index 1d01dafd0e..e16935ea87 100644
--- a/actionpack/lib/action_view/helpers/scriptaculous_helper.rb
+++ b/actionpack/lib/action_view/helpers/scriptaculous_helper.rb
@@ -1,4 +1,5 @@
require 'action_view/helpers/javascript_helper'
+require 'active_support/json'
module ActionView
module Helpers
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb
index de08672d2d..2bdd960f4c 100644
--- a/actionpack/lib/action_view/helpers/tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/tag_helper.rb
@@ -1,4 +1,3 @@
-require 'cgi'
require 'erb'
require 'set'
@@ -9,7 +8,7 @@ module ActionView
module TagHelper
include ERB::Util
- BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple).to_set
+ BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked).to_set
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym))
# Returns an empty HTML tag of type +name+ which by default is XHTML
@@ -133,10 +132,12 @@ module ActionView
unless options.blank?
attrs = []
if escape
- options.each do |key, value|
- next unless value
- value = BOOLEAN_ATTRIBUTES.include?(key) ? key : escape_once(value)
- attrs << %(#{key}="#{value}")
+ options.each_pair do |key, value|
+ if BOOLEAN_ATTRIBUTES.include?(key)
+ attrs << %(#{key}="#{key}") if value
+ else
+ attrs << %(#{key}="#{escape_once(value)}") if !value.nil?
+ end
end
else
attrs = options.map { |key, value| %(#{key}="#{value}") }
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index d80e7c6e57..1d9e4fe9b8 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -1,15 +1,5 @@
require 'action_view/helpers/tag_helper'
-begin
- require 'html/document'
-rescue LoadError
- html_scanner_path = "#{File.dirname(__FILE__)}/../../action_controller/vendor/html-scanner"
- if File.directory?(html_scanner_path)
- $:.unshift html_scanner_path
- require 'html/document'
- end
-end
-
module ActionView
module Helpers #:nodoc:
# The TextHelper module provides a set of methods for filtering, formatting
@@ -226,91 +216,79 @@ module ActionView
end * "\n"
end
- begin
- require_library_or_gem "redcloth" unless Object.const_defined?(:RedCloth)
-
- # Returns the text with all the Textile[http://www.textism.com/tools/textile] codes turned into HTML tags.
- #
- # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile].
- # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/]
- # is available</i>.
- #
- # ==== Examples
- # textilize("*This is Textile!* Rejoice!")
- # # => "<p><strong>This is Textile!</strong> Rejoice!</p>"
- #
- # textilize("I _love_ ROR(Ruby on Rails)!")
- # # => "<p>I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!</p>"
- #
- # textilize("h2. Textile makes markup -easy- simple!")
- # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>"
- #
- # textilize("Visit the Rails website "here":http://www.rubyonrails.org/.)
- # # => "<p>Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>.</p>"
- def textilize(text)
- if text.blank?
- ""
- else
- textilized = RedCloth.new(text, [ :hard_breaks ])
- textilized.hard_breaks = true if textilized.respond_to?(:hard_breaks=)
- textilized.to_html
- end
+ # Returns the text with all the Textile[http://www.textism.com/tools/textile] codes turned into HTML tags.
+ #
+ # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile].
+ # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/]
+ # is available</i>.
+ #
+ # ==== Examples
+ # textilize("*This is Textile!* Rejoice!")
+ # # => "<p><strong>This is Textile!</strong> Rejoice!</p>"
+ #
+ # textilize("I _love_ ROR(Ruby on Rails)!")
+ # # => "<p>I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!</p>"
+ #
+ # textilize("h2. Textile makes markup -easy- simple!")
+ # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>"
+ #
+ # textilize("Visit the Rails website "here":http://www.rubyonrails.org/.)
+ # # => "<p>Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>.</p>"
+ def textilize(text)
+ if text.blank?
+ ""
+ else
+ textilized = RedCloth.new(text, [ :hard_breaks ])
+ textilized.hard_breaks = true if textilized.respond_to?(:hard_breaks=)
+ textilized.to_html
end
+ end
- # Returns the text with all the Textile codes turned into HTML tags,
- # but without the bounding <p> tag that RedCloth adds.
- #
- # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile].
- # <i>This method is only available if RedCloth[http://whytheluckystiff.net/ruby/redcloth/]
- # is available</i>.
- #
- # ==== Examples
- # textilize_without_paragraph("*This is Textile!* Rejoice!")
- # # => "<strong>This is Textile!</strong> Rejoice!"
- #
- # textilize_without_paragraph("I _love_ ROR(Ruby on Rails)!")
- # # => "I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!"
- #
- # textilize_without_paragraph("h2. Textile makes markup -easy- simple!")
- # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>"
- #
- # textilize_without_paragraph("Visit the Rails website "here":http://www.rubyonrails.org/.)
- # # => "Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>."
- def textilize_without_paragraph(text)
- textiled = textilize(text)
- if textiled[0..2] == "<p>" then textiled = textiled[3..-1] end
- if textiled[-4..-1] == "</p>" then textiled = textiled[0..-5] end
- return textiled
- end
- rescue LoadError
- # We can't really help what's not there
+ # Returns the text with all the Textile codes turned into HTML tags,
+ # but without the bounding <p> tag that RedCloth adds.
+ #
+ # You can learn more about Textile's syntax at its website[http://www.textism.com/tools/textile].
+ # <i>This method is requires RedCloth[http://whytheluckystiff.net/ruby/redcloth/]
+ # to be available</i>.
+ #
+ # ==== Examples
+ # textilize_without_paragraph("*This is Textile!* Rejoice!")
+ # # => "<strong>This is Textile!</strong> Rejoice!"
+ #
+ # textilize_without_paragraph("I _love_ ROR(Ruby on Rails)!")
+ # # => "I <em>love</em> <acronym title="Ruby on Rails">ROR</acronym>!"
+ #
+ # textilize_without_paragraph("h2. Textile makes markup -easy- simple!")
+ # # => "<h2>Textile makes markup <del>easy</del> simple!</h2>"
+ #
+ # textilize_without_paragraph("Visit the Rails website "here":http://www.rubyonrails.org/.)
+ # # => "Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>."
+ def textilize_without_paragraph(text)
+ textiled = textilize(text)
+ if textiled[0..2] == "<p>" then textiled = textiled[3..-1] end
+ if textiled[-4..-1] == "</p>" then textiled = textiled[0..-5] end
+ return textiled
end
- begin
- require_library_or_gem "bluecloth" unless Object.const_defined?(:BlueCloth)
-
- # Returns the text with all the Markdown codes turned into HTML tags.
- # <i>This method is only available if BlueCloth[http://www.deveiate.org/projects/BlueCloth]
- # is available</i>.
- #
- # ==== Examples
- # markdown("We are using __Markdown__ now!")
- # # => "<p>We are using <strong>Markdown</strong> now!</p>"
- #
- # markdown("We like to _write_ `code`, not just _read_ it!")
- # # => "<p>We like to <em>write</em> <code>code</code>, not just <em>read</em> it!</p>"
- #
- # markdown("The [Markdown website](http://daringfireball.net/projects/markdown/) has more information.")
- # # => "<p>The <a href="http://daringfireball.net/projects/markdown/">Markdown website</a>
- # # has more information.</p>"
- #
- # markdown('![The ROR logo](http://rubyonrails.com/images/rails.png "Ruby on Rails")')
- # # => '<p><img src="http://rubyonrails.com/images/rails.png" alt="The ROR logo" title="Ruby on Rails" /></p>'
- def markdown(text)
- text.blank? ? "" : BlueCloth.new(text).to_html
- end
- rescue LoadError
- # We can't really help what's not there
+ # Returns the text with all the Markdown codes turned into HTML tags.
+ # <i>This method requires BlueCloth[http://www.deveiate.org/projects/BlueCloth]
+ # to be available</i>.
+ #
+ # ==== Examples
+ # markdown("We are using __Markdown__ now!")
+ # # => "<p>We are using <strong>Markdown</strong> now!</p>"
+ #
+ # markdown("We like to _write_ `code`, not just _read_ it!")
+ # # => "<p>We like to <em>write</em> <code>code</code>, not just <em>read</em> it!</p>"
+ #
+ # markdown("The [Markdown website](http://daringfireball.net/projects/markdown/) has more information.")
+ # # => "<p>The <a href="http://daringfireball.net/projects/markdown/">Markdown website</a>
+ # # has more information.</p>"
+ #
+ # markdown('![The ROR logo](http://rubyonrails.com/images/rails.png "Ruby on Rails")')
+ # # => '<p><img src="http://rubyonrails.com/images/rails.png" alt="The ROR logo" title="Ruby on Rails" /></p>'
+ def markdown(text)
+ text.blank? ? "" : BlueCloth.new(text).to_html
end
# Returns +text+ transformed into HTML using simple formatting rules.
@@ -392,8 +370,8 @@ module ActionView
options.reverse_merge!(:link => :all, :html => {})
case options[:link].to_sym
- when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], &block), &block)
- when :email_addresses then auto_link_email_addresses(text, &block)
+ when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], &block), options[:html], &block)
+ when :email_addresses then auto_link_email_addresses(text, options[:html], &block)
when :urls then auto_link_urls(text, options[:html], &block)
end
end
@@ -545,45 +523,43 @@ module ActionView
end
AUTO_LINK_RE = %r{
- ( # leading text
- <\w+.*?>| # leading HTML tag, or
- [^=!:'"/]| # leading punctuation, or
- ^ # beginning of line
- )
- (
- (?:https?://)| # protocol spec, or
- (?:www\.) # www.*
- )
- (
- [-\w]+ # subdomain or domain
- (?:\.[-\w]+)* # remaining subdomains or domain
- (?::\d+)? # port
- (?:/(?:[~\w\+@%=\(\)-]|(?:[,.;:'][^\s$]))*)* # path
- (?:\?[\w\+@%&=.;-]+)? # query string
- (?:\#[\w\-]*)? # trailing anchor
- )
- ([[:punct:]]|<|$|) # trailing text
- }x unless const_defined?(:AUTO_LINK_RE)
+ ( https?:// | www\. )
+ [^\s<]+
+ }x unless const_defined?(:AUTO_LINK_RE)
+
+ BRACKETS = { ']' => '[', ')' => '(', '}' => '{' }
# Turns all urls into clickable links. If a block is given, each url
# is yielded and the result is used as the link text.
def auto_link_urls(text, html_options = {})
- extra_options = tag_options(html_options.stringify_keys) || ""
+ link_attributes = html_options.stringify_keys
text.gsub(AUTO_LINK_RE) do
- all, a, b, c, d = $&, $1, $2, $3, $4
- if a =~ /<a\s/i # don't replace URL's that are already linked
- all
+ href = $&
+ punctuation = ''
+ # detect already linked URLs
+ if $` =~ /<a\s[^>]*href="$/
+ # do not change string; URL is alreay linked
+ href
else
- text = b + c
- text = yield(text) if block_given?
- %(#{a}<a href="#{b=="www."?"http://www.":b}#{c}"#{extra_options}>#{text}</a>#{d})
+ # don't include trailing punctuation character as part of the URL
+ if href.sub!(/[^\w\/-]$/, '') and punctuation = $& and opening = BRACKETS[punctuation]
+ if href.scan(opening).size > href.scan(punctuation).size
+ href << punctuation
+ punctuation = ''
+ end
+ end
+
+ link_text = block_given?? yield(href) : href
+ href = 'http://' + href unless href.index('http') == 0
+
+ content_tag(:a, h(link_text), link_attributes.merge('href' => href)) + punctuation
end
end
end
# Turns all email addresses into clickable links. If a block is given,
# each email is yielded and the result is used as the link text.
- def auto_link_email_addresses(text)
+ def auto_link_email_addresses(text, html_options = {})
body = text.dup
text.gsub(/([\w\.!#\$%\-+.]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/) do
text = $1
@@ -592,10 +568,10 @@ module ActionView
text
else
display_text = (block_given?) ? yield(text) : text
- %{<a href="mailto:#{text}">#{display_text}</a>}
+ mail_to text, display_text, html_options
end
end
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/locale/en-US.yml b/actionpack/lib/action_view/locale/en.yml
index 818f2f93bd..9542b035aa 100644
--- a/actionpack/lib/action_view/locale/en-US.yml
+++ b/actionpack/lib/action_view/locale/en.yml
@@ -1,4 +1,4 @@
-"en-US":
+"en":
number:
# Used in number_with_delimiter()
# These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
@@ -44,6 +44,7 @@
# separator:
delimiter: ""
precision: 1
+ storage_units: [Bytes, KB, MB, GB, TB]
# Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words()
datetime:
diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb
index 8841099900..bbc995a340 100644
--- a/actionpack/lib/action_view/partials.rb
+++ b/actionpack/lib/action_view/partials.rb
@@ -46,6 +46,38 @@ module ActionView
#
# This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from.
#
+ # == Rendering objects with the RecordIdentifier
+ #
+ # Instead of explicitly naming the location of a partial, you can also let the RecordIdentifier do the work if
+ # you're following its conventions for RecordIdentifier#partial_path. Examples:
+ #
+ # # @account is an Account instance, so it uses the RecordIdentifier to replace
+ # # <%= render :partial => "accounts/account", :locals => { :account => @buyer } %>
+ # <%= render :partial => @account %>
+ #
+ # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
+ # # <%= render :partial => "posts/post", :collection => @posts %>
+ # <%= render :partial => @posts %>
+ #
+ # == Rendering the default case
+ #
+ # If you're not going to be using any of the options like collections or layouts, you can also use the short-hand
+ # defaults of render to render partials. Examples:
+ #
+ # # Instead of <%= render :partial => "account" %>
+ # <%= render "account" %>
+ #
+ # # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %>
+ # <%= render "account", :account => @buyer %>
+ #
+ # # @account is an Account instance, so it uses the RecordIdentifier to replace
+ # # <%= render :partial => "accounts/account", :locals => { :account => @account } %>
+ # <%= render(@account) %>
+ #
+ # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
+ # # <%= render :partial => "posts/post", :collection => @posts %>
+ # <%= render(@posts) %>
+ #
# == Rendering partials with layouts
#
# Partials can have their own layouts applied to them. These layouts are different than the ones that are
diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb
index d6bf2137af..ecb6103ade 100644
--- a/actionpack/lib/action_view/paths.rb
+++ b/actionpack/lib/action_view/paths.rb
@@ -40,18 +40,10 @@ module ActionView #:nodoc:
end
class Path #:nodoc:
- def self.eager_load_templates!
- @eager_load_templates = true
- end
-
- def self.eager_load_templates?
- @eager_load_templates || false
- end
-
attr_reader :path, :paths
delegate :to_s, :to_str, :hash, :inspect, :to => :path
- def initialize(path, load = true)
+ def initialize(path, load = false)
raise ArgumentError, "path already is a Path class" if path.is_a?(Path)
@path = path.freeze
reload! if load
@@ -65,9 +57,35 @@ module ActionView #:nodoc:
to_str == path.to_str
end
+ # Returns a ActionView::Template object for the given path string. The
+ # input path should be relative to the view path directory,
+ # +hello/index.html.erb+. This method also has a special exception to
+ # match partial file names without a handler extension. So
+ # +hello/index.html+ will match the first template it finds with a
+ # known template extension, +hello/index.html.erb+. Template extensions
+ # should not be confused with format extensions +html+, +js+, +xml+,
+ # etc. A format must be supplied to match a formated file. +hello/index+
+ # will never match +hello/index.html.erb+.
+ #
+ # This method also has two different implementations, one that is "lazy"
+ # and makes file system calls every time and the other is cached,
+ # "eager" which looks up the template in an in memory index. The "lazy"
+ # version is designed for development where you want to automatically
+ # find new templates between requests. The "eager" version is designed
+ # for production mode and it is much faster but requires more time
+ # upfront to build the file index.
def [](path)
- raise "Unloaded view path! #{@path}" unless @loaded
- @paths[path]
+ if loaded?
+ @paths[path]
+ else
+ Dir.glob("#{@path}/#{path}*").each do |file|
+ template = create_template(file)
+ if path == template.path_without_extension || path == template.path
+ return template
+ end
+ end
+ nil
+ end
end
def loaded?
@@ -84,9 +102,7 @@ module ActionView #:nodoc:
@paths = {}
templates_in_path do |template|
- # Eager load memoized methods and freeze cached template
- template.freeze if self.class.eager_load_templates?
-
+ template.load!
@paths[template.path] = template
@paths[template.path_without_extension] ||= template
end
@@ -98,11 +114,13 @@ module ActionView #:nodoc:
private
def templates_in_path
(Dir.glob("#{@path}/**/*/**") | Dir.glob("#{@path}/**")).each do |file|
- unless File.directory?(file)
- yield Template.new(file.split("#{self}/").last, self)
- end
+ yield create_template(file) unless File.directory?(file)
end
end
+
+ def create_template(file)
+ Template.new(file.split("#{self}/").last, self)
+ end
end
def load
@@ -121,5 +139,20 @@ module ActionView #:nodoc:
end
nil
end
+
+ def find_template(path, *formats)
+ if formats && formats.first == :all
+ formats = Mime::EXTENSION_LOOKUP.values.map(&:to_sym)
+ end
+ formats.each do |format|
+ if template = self["#{path}.#{format}"]
+ return template
+ end
+ end
+ if template = self[path]
+ return template
+ end
+ nil
+ end
end
end
diff --git a/actionpack/lib/action_view/renderable.rb b/actionpack/lib/action_view/renderable.rb
index c23b8cde89..7258ad04bf 100644
--- a/actionpack/lib/action_view/renderable.rb
+++ b/actionpack/lib/action_view/renderable.rb
@@ -29,7 +29,9 @@ module ActionView
stack.push(self)
# This is only used for TestResponse to set rendered_template
- view.instance_variable_set(:@_first_render, self) unless view.instance_variable_get(:@_first_render)
+ unless is_a?(InlineTemplate) || view.instance_variable_get(:@_first_render)
+ view.instance_variable_set(:@_first_render, self)
+ end
view.send(:_evaluate_assigns_and_ivars)
view.send(:_set_controller_content_type, mime_type) if respond_to?(:mime_type)
@@ -94,7 +96,7 @@ module ActionView
# The template will be compiled if the file has not been compiled yet, or
# if local_assigns has a new key, which isn't supported by the compiled code yet.
def recompile?(symbol)
- !(ActionView::PathSet::Path.eager_load_templates? && Base::CompiledTemplates.method_defined?(symbol))
+ !Base::CompiledTemplates.method_defined?(symbol) || !loaded?
end
end
end
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index 12808581a3..52378e049e 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -1,5 +1,3 @@
-require 'action_controller/mime_type'
-
module ActionView #:nodoc:
class Template
extend TemplateHandlers
@@ -59,6 +57,11 @@ module ActionView #:nodoc:
end
memoize :relative_path
+ def mtime
+ File.mtime(filename)
+ end
+ memoize :mtime
+
def source
File.read(filename)
end
@@ -81,6 +84,19 @@ module ActionView #:nodoc:
end
end
+ def stale?
+ File.mtime(filename) > mtime
+ end
+
+ def loaded?
+ @loaded
+ end
+
+ def load!
+ @loaded = true
+ freeze
+ end
+
private
def valid_extension?(extension)
Template.template_handler_extensions.include?(extension)
@@ -99,16 +115,14 @@ module ActionView #:nodoc:
# [base_path, name, format, extension]
def split(file)
if m = file.match(/^(.*\/)?([^\.]+)\.?(\w+)?\.?(\w+)?\.?(\w+)?$/)
- if m[5] # Multipart formats
+ if valid_extension?(m[5]) # Multipart formats
[m[1], m[2], "#{m[3]}.#{m[4]}", m[5]]
- elsif m[4] # Single format
+ elsif valid_extension?(m[4]) # Single format
[m[1], m[2], m[3], m[4]]
- else
- if valid_extension?(m[3]) # No format
- [m[1], m[2], nil, m[3]]
- else # No extension
- [m[1], m[2], m[3], nil]
- end
+ elsif valid_extension?(m[3]) # No format
+ [m[1], m[2], nil, m[3]]
+ else # No extension
+ [m[1], m[2], m[3], nil]
end
end
end
diff --git a/actionpack/lib/action_view/template_error.rb b/actionpack/lib/action_view/template_error.rb
index bcce331773..37cb1c7c6c 100644
--- a/actionpack/lib/action_view/template_error.rb
+++ b/actionpack/lib/action_view/template_error.rb
@@ -20,7 +20,11 @@ module ActionView
end
def clean_backtrace
- original_exception.clean_backtrace
+ if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner)
+ Rails.backtrace_cleaner.clean(original_exception.backtrace)
+ else
+ original_exception.backtrace
+ end
end
def sub_template_message
@@ -66,8 +70,8 @@ module ActionView
end
def to_s
- "\n\n#{self.class} (#{message}) #{source_location}:\n" +
- "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
+ "\n#{self.class} (#{message}) #{source_location}:\n" +
+ "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
end
# don't do anything nontrivial here. Any raised exception from here becomes fatal
@@ -92,9 +96,4 @@ module ActionView
end + file_name
end
end
-end
-
-if defined?(Exception::TraceSubstitutions)
- Exception::TraceSubstitutions << [/:in\s+`_run_.*'\s*$/, '']
- Exception::TraceSubstitutions << [%r{^\s*#{Regexp.escape RAILS_ROOT}/}, ''] if defined?(RAILS_ROOT)
-end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/template_handler.rb b/actionpack/lib/action_view/template_handler.rb
index d7e7c9b199..672da0ed2b 100644
--- a/actionpack/lib/action_view/template_handler.rb
+++ b/actionpack/lib/action_view/template_handler.rb
@@ -1,14 +1,34 @@
# Legacy TemplateHandler stub
-
module ActionView
- module TemplateHandlers
+ module TemplateHandlers #:nodoc:
module Compilable
+ def self.included(base)
+ base.extend(ClassMethods)
+ end
+
+ module ClassMethods
+ def call(template)
+ new.compile(template)
+ end
+ end
+
+ def compile(template)
+ raise "Need to implement #{self.class.name}#compile(template)"
+ end
end
end
class TemplateHandler
def self.call(template)
- new.compile(template)
+ "#{name}.new(self).render(template, local_assigns)"
+ end
+
+ def initialize(view = nil)
+ @view = view
+ end
+
+ def render(template, local_assigns)
+ raise "Need to implement #{self.class.name}#render(template, local_assigns)"
end
end
end
diff --git a/actionpack/lib/action_view/template_handlers.rb b/actionpack/lib/action_view/template_handlers.rb
index 6c8aa4c2a7..d06ddd5fb5 100644
--- a/actionpack/lib/action_view/template_handlers.rb
+++ b/actionpack/lib/action_view/template_handlers.rb
@@ -1,10 +1,9 @@
-require 'action_view/template_handler'
-require 'action_view/template_handlers/builder'
-require 'action_view/template_handlers/erb'
-require 'action_view/template_handlers/rjs'
-
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
diff --git a/actionpack/lib/action_view/template_handlers/erb.rb b/actionpack/lib/action_view/template_handlers/erb.rb
index 3def949f1e..f8d3da15be 100644
--- a/actionpack/lib/action_view/template_handlers/erb.rb
+++ b/actionpack/lib/action_view/template_handlers/erb.rb
@@ -1,42 +1,3 @@
-require 'erb'
-
-class ERB
- module Util
- HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' }
- JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }
-
- # A utility method for escaping HTML tag characters.
- # This method is also aliased as <tt>h</tt>.
- #
- # In your ERb templates, use this method to escape any unsafe content. For example:
- # <%=h @person.name %>
- #
- # ==== Example:
- # puts html_escape("is a > 0 & a < 10?")
- # # => is a &gt; 0 &amp; a &lt; 10?
- def html_escape(s)
- s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
- end
-
- # A utility method for escaping HTML entities in JSON strings.
- # This method is also aliased as <tt>j</tt>.
- #
- # In your ERb templates, use this method to escape any HTML entities:
- # <%=j @person.to_json %>
- #
- # ==== Example:
- # puts json_escape("is a > 0 & a < 10?")
- # # => is a \u003E 0 \u0026 a \u003C 10?
- def json_escape(s)
- s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] }
- end
-
- alias j json_escape
- module_function :j
- module_function :json_escape
- end
-end
-
module ActionView
module TemplateHandlers
class ERB < TemplateHandler
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index c69f9455b2..4ab4ed233f 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -1,7 +1,7 @@
-require 'active_support/test_case'
-
module ActionView
class TestCase < ActiveSupport::TestCase
+ include ActionController::TestCase::Assertions
+
class_inheritable_accessor :helper_class
@@helper_class = nil
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 673efa6af0..51697fda2f 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -1,21 +1,29 @@
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers')
+$:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers')
+require 'rubygems'
require 'yaml'
require 'stringio'
require 'test/unit'
-require 'action_controller'
-require 'action_controller/cgi_ext'
-require 'action_controller/test_process'
-require 'action_view/test_case'
+
+gem 'mocha', '>= 0.9.3'
+require 'mocha'
begin
require 'ruby-debug'
+ Debugger.settings[:autoeval] = true
+ Debugger.start
rescue LoadError
# Debugging disabled. `gem install ruby-debug` to enable.
end
+require 'action_controller'
+require 'action_controller/cgi_ext'
+require 'action_controller/test_process'
+require 'action_view/test_case'
+
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
@@ -23,17 +31,9 @@ ActionController::Base.logger = nil
ActionController::Routing::Routes.reload rescue nil
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
-ActionView::PathSet::Path.eager_load_templates!
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
+ActionController::Base.view_paths.load
-# Wrap tests that use Mocha and skip if unavailable.
def uses_mocha(test_name)
- unless Object.const_defined?(:Mocha)
- require 'mocha'
- require 'stubba'
- end
yield
-rescue LoadError => load_error
- raise unless load_error.message =~ /mocha/i
- $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
end
diff --git a/actionpack/test/active_record_unit.rb b/actionpack/test/active_record_unit.rb
index a377ccad24..d8d2e00dc2 100644
--- a/actionpack/test/active_record_unit.rb
+++ b/actionpack/test/active_record_unit.rb
@@ -82,7 +82,9 @@ class ActiveRecordTestConnector
end
end
-class ActiveRecordTestCase < ActiveSupport::TestCase
+class ActiveRecordTestCase < ActionController::TestCase
+ include ActiveRecord::TestFixtures
+
# Set our fixture path
if ActiveRecordTestConnector.able_to_connect
self.fixture_path = [FIXTURE_LOAD_PATH]
@@ -96,8 +98,6 @@ class ActiveRecordTestCase < ActiveSupport::TestCase
def run(*args)
super if ActiveRecordTestConnector.connected
end
-
- def default_test; end
end
ActiveRecordTestConnector.setup
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index fd7da89aa7..677d434f9c 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -1,7 +1,6 @@
# These tests exercise CGI::Session::ActiveRecordStore, so you're going to
# need AR in a sibling directory to AP and have SQLite installed.
require 'active_record_unit'
-require 'action_controller/session/active_record_store'
module CommonActiveRecordStoreTests
def test_basics
diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
index d75cb2b53a..147b270808 100644
--- a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
+++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
@@ -47,15 +47,9 @@ class RenderPartialWithRecordIdentificationController < ActionController::Base
end
class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase
+ tests RenderPartialWithRecordIdentificationController
fixtures :developers, :projects, :developers_projects, :topics, :replies, :companies, :mascots
- def setup
- @controller = RenderPartialWithRecordIdentificationController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- super
- end
-
def test_rendering_partial_with_has_many_and_belongs_to_association
get :render_with_has_many_and_belongs_to_association
assert_template 'projects/_project'
@@ -162,12 +156,7 @@ module Fun
end
class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveRecordTestCase
- def setup
- @controller = Fun::NestedController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- super
- end
+ tests Fun::NestedController
def test_render_with_record_in_nested_controller
get :render_with_record_in_nested_controller
@@ -183,12 +172,7 @@ class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveReco
end
class RenderPartialWithRecordIdentificationAndNestedDeeperControllersTest < ActiveRecordTestCase
- def setup
- @controller = Fun::Serious::NestedDeeperController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- super
- end
+ tests Fun::Serious::NestedDeeperController
def test_render_with_record_in_deeper_nested_controller
get :render_with_record_in_deeper_nested_controller
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 56ba36cee5..ea56048f37 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -165,13 +165,11 @@ module Admin
end
# a test case to exercise the new capabilities TestRequest & TestResponse
-class ActionPackAssertionsControllerTest < Test::Unit::TestCase
+class ActionPackAssertionsControllerTest < ActionController::TestCase
# let's get this party started
def setup
ActionController::Routing::Routes.reload
ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module user content admin/user))
- @controller = ActionPackAssertionsController.new
- @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
end
def teardown
@@ -235,13 +233,13 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
map.connect ':controller/:action/:id'
end
process :redirect_to_named_route
- assert_raise(Test::Unit::AssertionFailedError) do
+ assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to 'http://test.host/route_two'
end
- assert_raise(Test::Unit::AssertionFailedError) do
+ assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two'
end
- assert_raise(Test::Unit::AssertionFailedError) do
+ assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to route_two_url
end
end
@@ -368,6 +366,12 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
assert @response.missing?
end
+ # check client errors
+ def test_client_error_response_code
+ process :response404
+ assert @response.client_error?
+ end
+
# check to see if our redirection matches a pattern
def test_redirect_url_match
process :redirect_external
@@ -410,7 +414,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
def test_assert_redirection_fails_with_incorrect_controller
process :redirect_to_controller
- assert_raise(Test::Unit::AssertionFailedError) do
+ assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to :controller => "action_pack_assertions", :action => "flash_me"
end
end
@@ -457,16 +461,16 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
def test_assert_valid
get :get_valid_record
- assert_valid assigns('record')
+ assert_deprecated { assert_valid assigns('record') }
end
def test_assert_valid_failing
get :get_invalid_record
begin
- assert_valid assigns('record')
+ assert_deprecated { assert_valid assigns('record') }
assert false
- rescue Test::Unit::AssertionFailedError => e
+ rescue ActiveSupport::TestCase::Assertion => e
end
end
@@ -475,7 +479,7 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
get :index
assert_response :success
flunk 'Expected non-success response'
- rescue Test::Unit::AssertionFailedError => e
+ rescue ActiveSupport::TestCase::Assertion => e
assert e.message.include?('FAIL')
end
@@ -484,17 +488,15 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
get :show
assert_response :success
flunk 'Expected non-success response'
- rescue Test::Unit::AssertionFailedError
+ rescue ActiveSupport::TestCase::Assertion
+ # success
rescue
flunk "assert_response failed to handle failure response with missing, but optional, exception."
end
end
-class ActionPackHeaderTest < Test::Unit::TestCase
- def setup
- @controller = ActionPackAssertionsController.new
- @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
- end
+class ActionPackHeaderTest < ActionController::TestCase
+ tests ActionPackAssertionsController
def test_rendering_xml_sets_content_type
process :hello_xml_world
diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb
index 08cbcbf302..ed8c4427c9 100644
--- a/actionpack/test/controller/assert_select_test.rb
+++ b/actionpack/test/controller/assert_select_test.rb
@@ -9,9 +9,10 @@ require 'controller/fake_controllers'
unless defined?(ActionMailer)
begin
- $:.unshift(File.dirname(__FILE__) + "/../../../actionmailer/lib")
+ $:.unshift("#{File.dirname(__FILE__)}/../../../actionmailer/lib")
require 'action_mailer'
- rescue LoadError
+ rescue LoadError => e
+ raise unless e.message =~ /action_mailer/
require 'rubygems'
gem 'actionmailer'
end
@@ -19,7 +20,18 @@ end
ActionMailer::Base.template_root = FIXTURE_LOAD_PATH
-class AssertSelectTest < Test::Unit::TestCase
+class AssertSelectTest < ActionController::TestCase
+ Assertion = ActiveSupport::TestCase::Assertion
+
+ class AssertSelectMailer < ActionMailer::Base
+ def test(html)
+ recipients "test <test@test.host>"
+ from "test@test.host"
+ subject "Test e-mail"
+ part :content_type=>"text/html", :body=>html
+ end
+ end
+
class AssertSelectController < ActionController::Base
def response_with=(content)
@content = content
@@ -51,21 +63,9 @@ class AssertSelectTest < Test::Unit::TestCase
end
end
- class AssertSelectMailer < ActionMailer::Base
- def test(html)
- recipients "test <test@test.host>"
- from "test@test.host"
- subject "Test e-mail"
- part :content_type=>"text/html", :body=>html
- end
- end
-
- AssertionFailedError = Test::Unit::AssertionFailedError
+ tests AssertSelectController
def setup
- @controller = AssertSelectController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@@ -76,7 +76,7 @@ class AssertSelectTest < Test::Unit::TestCase
end
def assert_failure(message, &block)
- e = assert_raises(AssertionFailedError, &block)
+ e = assert_raises(Assertion, &block)
assert_match(message, e.message) if Regexp === message
assert_equal(message, e.message) if String === message
end
@@ -94,43 +94,43 @@ class AssertSelectTest < Test::Unit::TestCase
def test_equality_true_false
render_html %Q{<div id="1"></div><div id="2"></div>}
- assert_nothing_raised { assert_select "div" }
- assert_raises(AssertionFailedError) { assert_select "p" }
- assert_nothing_raised { assert_select "div", true }
- assert_raises(AssertionFailedError) { assert_select "p", true }
- assert_raises(AssertionFailedError) { assert_select "div", false }
- assert_nothing_raised { assert_select "p", false }
+ assert_nothing_raised { assert_select "div" }
+ assert_raises(Assertion) { assert_select "p" }
+ assert_nothing_raised { assert_select "div", true }
+ assert_raises(Assertion) { assert_select "p", true }
+ assert_raises(Assertion) { assert_select "div", false }
+ assert_nothing_raised { assert_select "p", false }
end
def test_equality_string_and_regexp
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
- assert_nothing_raised { assert_select "div", "foo" }
- assert_raises(AssertionFailedError) { assert_select "div", "bar" }
- assert_nothing_raised { assert_select "div", :text=>"foo" }
- assert_raises(AssertionFailedError) { assert_select "div", :text=>"bar" }
- assert_nothing_raised { assert_select "div", /(foo|bar)/ }
- assert_raises(AssertionFailedError) { assert_select "div", /foobar/ }
- assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ }
- assert_raises(AssertionFailedError) { assert_select "div", :text=>/foobar/ }
- assert_raises(AssertionFailedError) { assert_select "p", :text=>/foobar/ }
+ assert_nothing_raised { assert_select "div", "foo" }
+ assert_raises(Assertion) { assert_select "div", "bar" }
+ assert_nothing_raised { assert_select "div", :text=>"foo" }
+ assert_raises(Assertion) { assert_select "div", :text=>"bar" }
+ assert_nothing_raised { assert_select "div", /(foo|bar)/ }
+ assert_raises(Assertion) { assert_select "div", /foobar/ }
+ assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ }
+ assert_raises(Assertion) { assert_select "div", :text=>/foobar/ }
+ assert_raises(Assertion) { assert_select "p", :text=>/foobar/ }
end
def test_equality_of_html
render_html %Q{<p>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</p>}
text = "\"This is not a big problem,\" he said."
html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said."
- assert_nothing_raised { assert_select "p", text }
- assert_raises(AssertionFailedError) { assert_select "p", html }
- assert_nothing_raised { assert_select "p", :html=>html }
- assert_raises(AssertionFailedError) { assert_select "p", :html=>text }
+ assert_nothing_raised { assert_select "p", text }
+ assert_raises(Assertion) { assert_select "p", html }
+ assert_nothing_raised { assert_select "p", :html=>html }
+ assert_raises(Assertion) { assert_select "p", :html=>text }
# No stripping for pre.
render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>}
text = "\n\"This is not a big problem,\" he said.\n"
html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n"
- assert_nothing_raised { assert_select "pre", text }
- assert_raises(AssertionFailedError) { assert_select "pre", html }
- assert_nothing_raised { assert_select "pre", :html=>html }
- assert_raises(AssertionFailedError) { assert_select "pre", :html=>text }
+ assert_nothing_raised { assert_select "pre", text }
+ assert_raises(Assertion) { assert_select "pre", html }
+ assert_nothing_raised { assert_select "pre", :html=>html }
+ assert_raises(Assertion) { assert_select "pre", :html=>text }
end
def test_counts
@@ -206,16 +206,16 @@ class AssertSelectTest < Test::Unit::TestCase
def test_assert_select_text_match
render_html %Q{<div id="1"><span>foo</span></div><div id="2"><span>bar</span></div>}
assert_select "div" do
- assert_nothing_raised { assert_select "div", "foo" }
- assert_nothing_raised { assert_select "div", "bar" }
- assert_nothing_raised { assert_select "div", /\w*/ }
- assert_nothing_raised { assert_select "div", /\w*/, :count=>2 }
- assert_raises(AssertionFailedError) { assert_select "div", :text=>"foo", :count=>2 }
- assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
- assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
- assert_nothing_raised { assert_select "div", :html=>/\w*/ }
- assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 }
- assert_raises(AssertionFailedError) { assert_select "div", :html=>"<span>foo</span>", :count=>2 }
+ assert_nothing_raised { assert_select "div", "foo" }
+ assert_nothing_raised { assert_select "div", "bar" }
+ assert_nothing_raised { assert_select "div", /\w*/ }
+ assert_nothing_raised { assert_select "div", /\w*/, :count=>2 }
+ assert_raises(Assertion) { assert_select "div", :text=>"foo", :count=>2 }
+ assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
+ assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
+ assert_nothing_raised { assert_select "div", :html=>/\w*/ }
+ assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 }
+ assert_raises(Assertion) { assert_select "div", :html=>"<span>foo</span>", :count=>2 }
end
end
@@ -323,7 +323,7 @@ class AssertSelectTest < Test::Unit::TestCase
# Test that we fail if there is nothing to pick.
def test_assert_select_rjs_fails_if_nothing_to_pick
render_rjs { }
- assert_raises(AssertionFailedError) { assert_select_rjs }
+ assert_raises(Assertion) { assert_select_rjs }
end
def test_assert_select_rjs_with_unicode
@@ -338,10 +338,10 @@ class AssertSelectTest < Test::Unit::TestCase
if str.respond_to?(:force_encoding)
str.force_encoding(Encoding::UTF_8)
assert_select str, /\343\203\201..\343\203\210/u
- assert_raises(AssertionFailedError) { assert_select str, /\343\203\201.\343\203\210/u }
+ assert_raises(Assertion) { assert_select str, /\343\203\201.\343\203\210/u }
else
assert_select str, Regexp.new("\343\203\201..\343\203\210",0,'U')
- assert_raises(AssertionFailedError) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') }
+ assert_raises(Assertion) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') }
end
end
end
@@ -365,7 +365,7 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select "div", 1
assert_select "#3"
end
- assert_raises(AssertionFailedError) { assert_select_rjs "test4" }
+ assert_raises(Assertion) { assert_select_rjs "test4" }
end
def test_assert_select_rjs_for_replace
@@ -383,7 +383,7 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select "div", 1
assert_select "#1"
end
- assert_raises(AssertionFailedError) { assert_select_rjs :replace, "test2" }
+ assert_raises(Assertion) { assert_select_rjs :replace, "test2" }
# Replace HTML.
assert_select_rjs :replace_html do
assert_select "div", 1
@@ -393,7 +393,7 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select "div", 1
assert_select "#2"
end
- assert_raises(AssertionFailedError) { assert_select_rjs :replace_html, "test1" }
+ assert_raises(Assertion) { assert_select_rjs :replace_html, "test1" }
end
def test_assert_select_rjs_for_chained_replace
@@ -411,7 +411,7 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select "div", 1
assert_select "#1"
end
- assert_raises(AssertionFailedError) { assert_select_rjs :chained_replace, "test2" }
+ assert_raises(Assertion) { assert_select_rjs :chained_replace, "test2" }
# Replace HTML.
assert_select_rjs :chained_replace_html do
assert_select "div", 1
@@ -421,7 +421,7 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select "div", 1
assert_select "#2"
end
- assert_raises(AssertionFailedError) { assert_select_rjs :replace_html, "test1" }
+ assert_raises(Assertion) { assert_select_rjs :replace_html, "test1" }
end
# Simple remove
@@ -440,8 +440,8 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select_rjs :remove, "test1"
- rescue Test::Unit::AssertionFailedError
- assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message
+ rescue Assertion
+ assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_remove_ignores_block
@@ -472,8 +472,8 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select_rjs :show, "test1"
- rescue Test::Unit::AssertionFailedError
- assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message
+ rescue Assertion
+ assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_show_ignores_block
@@ -504,8 +504,8 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select_rjs :hide, "test1"
- rescue Test::Unit::AssertionFailedError
- assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message
+ rescue Assertion
+ assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_hide_ignores_block
@@ -536,8 +536,8 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select_rjs :toggle, "test1"
- rescue Test::Unit::AssertionFailedError
- assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message
+ rescue Assertion
+ assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message
end
def test_assert_select_rjs_for_toggle_ignores_block
@@ -567,7 +567,7 @@ class AssertSelectTest < Test::Unit::TestCase
assert_select "div", 1
assert_select "#3"
end
- assert_raises(AssertionFailedError) { assert_select_rjs :insert_html, "test1" }
+ assert_raises(Assertion) { assert_select_rjs :insert_html, "test1" }
end
# Positioned insert.
@@ -693,7 +693,7 @@ EOF
#
def test_assert_select_email
- assert_raises(AssertionFailedError) { assert_select_email {} }
+ assert_raises(Assertion) { assert_select_email {} }
AssertSelectMailer.deliver_test "<div><p>foo</p><p>bar</p></div>"
assert_select_email do
assert_select "div:root" do
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index 738c016c6e..18d185b264 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -105,7 +105,7 @@ class ControllerInstanceTests < Test::Unit::TestCase
end
-class PerformActionTest < Test::Unit::TestCase
+class PerformActionTest < ActionController::TestCase
class MockLogger
attr_reader :logged
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index b6cdd116e5..10c65acd9a 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -42,7 +42,7 @@ class PageCachingTestController < ActionController::Base
end
end
-class PageCachingTest < Test::Unit::TestCase
+class PageCachingTest < ActionController::TestCase
def setup
ActionController::Base.perform_caching = true
@@ -222,7 +222,7 @@ class ActionCachingMockController
end
end
-class ActionCacheTest < Test::Unit::TestCase
+class ActionCacheTest < ActionController::TestCase
def setup
reset!
FileUtils.mkdir_p(FILE_STORE_PATH)
@@ -291,11 +291,13 @@ class ActionCacheTest < Test::Unit::TestCase
ActionController::Base.use_accept_header = old_use_accept_header
end
- def test_action_cache_with_store_options
- MockTime.expects(:now).returns(12345).once
- @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once
- @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once
- get :index
+ uses_mocha 'test action cache' do
+ def test_action_cache_with_store_options
+ MockTime.expects(:now).returns(12345).once
+ @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once
+ @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once
+ get :index
+ end
end
def test_action_cache_with_custom_cache_path
@@ -469,7 +471,7 @@ class FragmentCachingTestController < ActionController::Base
def some_action; end;
end
-class FragmentCachingTest < Test::Unit::TestCase
+class FragmentCachingTest < ActionController::TestCase
def setup
ActionController::Base.perform_caching = true
@store = ActiveSupport::Cache::MemoryStore.new
@@ -525,7 +527,7 @@ class FragmentCachingTest < Test::Unit::TestCase
def test_write_fragment_with_caching_disabled
assert_nil @store.read('views/name')
ActionController::Base.perform_caching = false
- assert_equal nil, @controller.write_fragment('name', 'value')
+ assert_equal 'value', @controller.write_fragment('name', 'value')
assert_nil @store.read('views/name')
end
@@ -601,7 +603,7 @@ class FunctionalCachingController < ActionController::Base
end
end
-class FunctionalFragmentCachingTest < Test::Unit::TestCase
+class FunctionalFragmentCachingTest < ActionController::TestCase
def setup
ActionController::Base.perform_caching = true
@store = ActiveSupport::Cache::MemoryStore.new
diff --git a/actionpack/test/controller/cgi_test.rb b/actionpack/test/controller/cgi_test.rb
index 813171857a..ac1c8abc59 100644
--- a/actionpack/test/controller/cgi_test.rb
+++ b/actionpack/test/controller/cgi_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'action_controller/cgi_process'
class BaseCgiTest < Test::Unit::TestCase
def setup
@@ -48,7 +47,8 @@ class BaseCgiTest < Test::Unit::TestCase
# some developers have grown accustomed to using comma in cookie values.
@alt_cookie_fmt_request_hash = {"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"}
@cgi = CGI.new
- @cgi.stubs(:env_table).returns(@request_hash)
+ class << @cgi; attr_accessor :env_table end
+ @cgi.env_table = @request_hash
@request = ActionController::CgiRequest.new(@cgi)
end
diff --git a/actionpack/test/controller/components_test.rb b/actionpack/test/controller/components_test.rb
deleted file mode 100644
index 4d36fc411d..0000000000
--- a/actionpack/test/controller/components_test.rb
+++ /dev/null
@@ -1,156 +0,0 @@
-require 'abstract_unit'
-
-class CallerController < ActionController::Base
- def calling_from_controller
- render_component(:controller => "callee", :action => "being_called")
- end
-
- def calling_from_controller_with_params
- render_component(:controller => "callee", :action => "being_called", :params => { "name" => "David" })
- end
-
- def calling_from_controller_with_different_status_code
- render_component(:controller => "callee", :action => "blowing_up")
- end
-
- def calling_from_template
- render :inline => "Ring, ring: <%= render_component(:controller => 'callee', :action => 'being_called') %>"
- end
-
- def internal_caller
- render :inline => "Are you there? <%= render_component(:action => 'internal_callee') %>"
- end
-
- def internal_callee
- render :text => "Yes, ma'am"
- end
-
- def set_flash
- render_component(:controller => "callee", :action => "set_flash")
- end
-
- def use_flash
- render_component(:controller => "callee", :action => "use_flash")
- end
-
- def calling_redirected
- render_component(:controller => "callee", :action => "redirected")
- end
-
- def calling_redirected_as_string
- render :inline => "<%= render_component(:controller => 'callee', :action => 'redirected') %>"
- end
-
- def rescue_action(e) raise end
-end
-
-class CalleeController < ActionController::Base
- def being_called
- render :text => "#{params[:name] || "Lady"} of the House, speaking"
- end
-
- def blowing_up
- render :text => "It's game over, man, just game over, man!", :status => 500
- end
-
- def set_flash
- flash[:notice] = 'My stoney baby'
- render :text => 'flash is set'
- end
-
- def use_flash
- render :text => flash[:notice] || 'no flash'
- end
-
- def redirected
- redirect_to :controller => "callee", :action => "being_called"
- end
-
- def rescue_action(e) raise end
-end
-
-class ComponentsTest < Test::Unit::TestCase
- def setup
- @controller = CallerController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
- def test_calling_from_controller
- assert_deprecated do
- get :calling_from_controller
- assert_equal "Lady of the House, speaking", @response.body
- end
- end
-
- def test_calling_from_controller_with_params
- assert_deprecated do
- get :calling_from_controller_with_params
- assert_equal "David of the House, speaking", @response.body
- end
- end
-
- def test_calling_from_controller_with_different_status_code
- assert_deprecated do
- get :calling_from_controller_with_different_status_code
- assert_equal 500, @response.response_code
- end
- end
-
- def test_calling_from_template
- assert_deprecated do
- get :calling_from_template
- assert_equal "Ring, ring: Lady of the House, speaking", @response.body
- end
- end
-
- def test_etag_is_set_for_parent_template_when_calling_from_template
- assert_deprecated do
- get :calling_from_template
- expected_etag = etag_for("Ring, ring: Lady of the House, speaking")
- assert_equal expected_etag, @response.headers['ETag']
- end
- end
-
- def test_internal_calling
- assert_deprecated do
- get :internal_caller
- assert_equal "Are you there? Yes, ma'am", @response.body
- end
- end
-
- def test_flash
- assert_deprecated do
- get :set_flash
- assert_equal 'My stoney baby', flash[:notice]
- get :use_flash
- assert_equal 'My stoney baby', @response.body
- get :use_flash
- assert_equal 'no flash', @response.body
- end
- end
-
- def test_component_redirect_redirects
- assert_deprecated do
- get :calling_redirected
- assert_redirected_to :controller=>"callee", :action => "being_called"
- end
- end
-
- def test_component_multiple_redirect_redirects
- test_component_redirect_redirects
- test_internal_calling
- end
-
- def test_component_as_string_redirect_renders_redirected_action
- assert_deprecated do
- get :calling_redirected_as_string
- assert_equal "Lady of the House, speaking", @response.body
- end
- end
-
- protected
- def etag_for(text)
- %("#{Digest::MD5.hexdigest(text)}")
- end
-end
diff --git a/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb b/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb
index 86555a77df..dd69a63020 100644
--- a/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb
+++ b/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class DeprecatedBaseMethodsTest < Test::Unit::TestCase
+class DeprecatedBaseMethodsTest < ActionController::TestCase
class Target < ActionController::Base
def home_url(greeting)
"http://example.com/#{greeting}"
@@ -13,11 +13,7 @@ class DeprecatedBaseMethodsTest < Test::Unit::TestCase
def rescue_action(e) raise e end
end
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = Target.new
- end
+ tests Target
def test_log_error_silences_deprecation_warnings
get :raises_name_error
@@ -25,10 +21,12 @@ class DeprecatedBaseMethodsTest < Test::Unit::TestCase
assert_not_deprecated { @controller.send :log_error, e }
end
- def test_assertion_failed_error_silences_deprecation_warnings
- get :raises_name_error
- rescue => e
- error = Test::Unit::Error.new('testing ur doodz', e)
- assert_not_deprecated { error.message }
+ if defined? Test::Unit::Error
+ def test_assertion_failed_error_silences_deprecation_warnings
+ get :raises_name_error
+ rescue => e
+ error = Test::Unit::Error.new('testing ur doodz', e)
+ assert_not_deprecated { error.message }
+ end
end
end
diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb
index 3ee78a6156..61bfb2b6e9 100644
--- a/actionpack/test/controller/dispatcher_test.rb
+++ b/actionpack/test/controller/dispatcher_test.rb
@@ -2,8 +2,6 @@ require 'abstract_unit'
uses_mocha 'dispatcher tests' do
-require 'action_controller/dispatcher'
-
class DispatcherTest < Test::Unit::TestCase
Dispatcher = ActionController::Dispatcher
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 83e3b085e7..5f36461b89 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-ActionController::Helpers::HELPERS_DIR.replace File.dirname(__FILE__) + '/../fixtures/helpers'
+ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers'
class TestController < ActionController::Base
attr_accessor :delegate_attr
@@ -130,6 +130,20 @@ class HelperTest < Test::Unit::TestCase
assert methods.include?('foobar')
end
+ def test_all_helpers_with_alternate_helper_dir
+ @controller_class.helpers_dir = File.dirname(__FILE__) + '/../fixtures/alternate_helpers'
+
+ # Reload helpers
+ @controller_class.master_helper_module = Module.new
+ @controller_class.helper :all
+
+ # helpers/abc_helper.rb should not be included
+ assert !master_helper_methods.include?('bare_a')
+
+ # alternate_helpers/foo_helper.rb
+ assert master_helper_methods.include?('baz')
+ end
+
def test_helper_proxy
methods = ApplicationController.helpers.methods.map(&:to_s)
diff --git a/actionpack/test/controller/html-scanner/sanitizer_test.rb b/actionpack/test/controller/html-scanner/sanitizer_test.rb
index a9e8447e32..e85a5c7abf 100644
--- a/actionpack/test/controller/html-scanner/sanitizer_test.rb
+++ b/actionpack/test/controller/html-scanner/sanitizer_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class SanitizerTest < Test::Unit::TestCase
+class SanitizerTest < ActionController::TestCase
def setup
@sanitizer = nil # used by assert_sanitizer
end
@@ -253,6 +253,10 @@ class SanitizerTest < Test::Unit::TestCase
assert_sanitized "<![CDATA[<span>neverending...", "&lt;![CDATA[&lt;span>neverending...]]>"
end
+ def test_should_not_mangle_urls_with_ampersand
+ assert_sanitized %{<a href=\"http://www.domain.com?var1=1&amp;var2=2\">my link</a>}
+ end
+
protected
def assert_sanitized(input, expected = nil)
@sanitizer ||= HTML::WhiteListSanitizer.new
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 7e4c3e171a..b39d35930d 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -1,6 +1,4 @@
require 'abstract_unit'
-require 'action_controller/integration'
-require 'action_controller/routing'
uses_mocha 'integration' do
diff --git a/actionpack/test/controller/integration_upload_test.rb b/actionpack/test/controller/integration_upload_test.rb
index 4af9b7e697..b1dd6a6341 100644
--- a/actionpack/test/controller/integration_upload_test.rb
+++ b/actionpack/test/controller/integration_upload_test.rb
@@ -1,6 +1,4 @@
require 'abstract_unit'
-require 'action_controller/integration'
-require 'action_controller/routing'
unless defined? ApplicationController
class ApplicationController < ActionController::Base
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index 1120fdbff5..18c01f755c 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -3,6 +3,10 @@ require 'abstract_unit'
# The view_paths array must be set on Base and not LayoutTest so that LayoutTest's inherited
# method has access to the view_paths array when looking for a layout to automatically assign.
old_load_paths = ActionController::Base.view_paths
+
+ActionView::Template::register_template_handler :mab,
+ lambda { |template| template.source.inspect }
+
ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../fixtures/layout_tests/' ]
class LayoutTest < ActionController::Base
@@ -31,14 +35,8 @@ end
class MultipleExtensions < LayoutTest
end
-ActionView::Template::register_template_handler :mab,
- lambda { |template| template.source.inspect }
-
-class LayoutAutoDiscoveryTest < Test::Unit::TestCase
+class LayoutAutoDiscoveryTest < ActionController::TestCase
def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
-
@request.host = "www.nextangle.com"
end
@@ -55,10 +53,9 @@ class LayoutAutoDiscoveryTest < Test::Unit::TestCase
end
def test_third_party_template_library_auto_discovers_layout
- ThirdPartyTemplateLibraryController.view_paths.reload!
@controller = ThirdPartyTemplateLibraryController.new
get :hello
- assert_equal 'layouts/third_party_template_library', @controller.active_layout
+ assert_equal 'layouts/third_party_template_library.mab', @controller.active_layout.to_s
assert_equal 'layouts/third_party_template_library', @response.layout
assert_response :success
assert_equal 'Mab', @response.body
@@ -67,14 +64,14 @@ class LayoutAutoDiscoveryTest < Test::Unit::TestCase
def test_namespaced_controllers_auto_detect_layouts
@controller = ControllerNameSpace::NestedController.new
get :hello
- assert_equal 'layouts/controller_name_space/nested', @controller.active_layout
+ assert_equal 'layouts/controller_name_space/nested', @controller.active_layout.to_s
assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body
end
def test_namespaced_controllers_auto_detect_layouts
@controller = MultipleExtensions.new
get :hello
- assert_equal 'layouts/multiple_extensions', @controller.active_layout
+ assert_equal 'layouts/multiple_extensions.html.erb', @controller.active_layout.to_s
assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip
end
end
@@ -98,12 +95,7 @@ class RendersNoLayoutController < LayoutTest
end
end
-class LayoutSetInResponseTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
+class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
get :hello
@@ -150,12 +142,7 @@ class SetsNonExistentLayoutFile < LayoutTest
layout "nofile.rhtml"
end
-class LayoutExceptionRaised < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
+class LayoutExceptionRaised < ActionController::TestCase
def test_exception_raised_when_layout_file_not_found
@controller = SetsNonExistentLayoutFile.new
get :hello
@@ -170,12 +157,7 @@ class LayoutStatusIsRendered < LayoutTest
end
end
-class LayoutStatusIsRenderedTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
+class LayoutStatusIsRenderedTest < ActionController::TestCase
def test_layout_status_is_rendered
@controller = LayoutStatusIsRendered.new
get :hello
@@ -187,12 +169,7 @@ class LayoutSymlinkedTest < LayoutTest
layout "symlinked/symlinked_layout"
end
-class LayoutSymlinkedIsRenderedTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
+class LayoutSymlinkedIsRenderedTest < ActionController::TestCase
def test_symlinked_layout_is_rendered
@controller = LayoutSymlinkedTest.new
get :hello
diff --git a/actionpack/test/controller/logging_test.rb b/actionpack/test/controller/logging_test.rb
new file mode 100644
index 0000000000..3c936854dd
--- /dev/null
+++ b/actionpack/test/controller/logging_test.rb
@@ -0,0 +1,46 @@
+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
+
+ def method_missing(method, *args)
+ @logged ||= []
+ @logged << args.first
+ end
+ end
+
+ setup :set_logger
+
+ def test_logging_without_parameters
+ get :show
+ assert_equal 2, logs.size
+ assert_nil logs.detect {|l| l =~ /Parameters/ }
+ end
+
+ def test_logging_with_parameters
+ get :show, :id => 10
+ assert_equal 3, logs.size
+
+ params = logs.detect {|l| l =~ /Parameters/ }
+ assert_equal 'Parameters: {"id"=>"10"}', params
+ end
+
+ private
+
+ def set_logger
+ @controller.logger = MockLogger.new
+ end
+
+ def logs
+ @logs ||= @controller.logger.logged.compact.map {|l| l.strip}
+ end
+end
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index 0d508eb8df..dc59180a68 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -162,13 +162,11 @@ class RespondToController < ActionController::Base
end
end
-class MimeControllerTest < Test::Unit::TestCase
+class MimeControllerTest < ActionController::TestCase
+ tests RespondToController
+
def setup
ActionController::Base.use_accept_header = true
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
-
- @controller = RespondToController.new
@request.host = "www.example.com"
end
@@ -509,12 +507,10 @@ class SuperPostController < PostController
end
end
-class MimeControllerLayoutsTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
+class MimeControllerLayoutsTest < ActionController::TestCase
+ tests PostController
- @controller = PostController.new
+ def setup
@request.host = "www.example.com"
end
diff --git a/actionpack/test/controller/mime_type_test.rb b/actionpack/test/controller/mime_type_test.rb
index f16a3c68b4..21ae0419f1 100644
--- a/actionpack/test/controller/mime_type_test.rb
+++ b/actionpack/test/controller/mime_type_test.rb
@@ -61,7 +61,9 @@ class MimeTypeTest < Test::Unit::TestCase
types.each do |type|
mime = Mime.const_get(type.to_s.upcase)
assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?"
- (types - [type]).each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
+ invalid_types = types - [type]
+ invalid_types.delete(:html) if Mime::Type.html_types.include?(type)
+ invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
end
end
@@ -71,14 +73,12 @@ class MimeTypeTest < Test::Unit::TestCase
end
def test_verifiable_mime_types
- unverified_types = Mime::Type.unverifiable_types
all_types = Mime::SET.to_a.map(&:to_sym)
all_types.uniq!
# Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) }
-
- unverified, verified = all_types.partition { |type| Mime::Type.unverifiable_types.include? type }
- assert verified.all? { |type| Mime.const_get(type.to_s.upcase).verify_request? }, "Not all Mime Types are verified: #{verified.inspect}"
- assert unverified.all? { |type| !Mime.const_get(type.to_s.upcase).verify_request? }, "Some Mime Types are verified: #{unverified.inspect}"
+ verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type }
+ assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" }
+ assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
end
end
diff --git a/actionpack/test/controller/polymorphic_routes_test.rb b/actionpack/test/controller/polymorphic_routes_test.rb
index 6ddf2826cd..09c7f74617 100644
--- a/actionpack/test/controller/polymorphic_routes_test.rb
+++ b/actionpack/test/controller/polymorphic_routes_test.rb
@@ -22,8 +22,7 @@ end
class Response::Nested < Response; end
uses_mocha 'polymorphic URL helpers' do
- class PolymorphicRoutesTest < Test::Unit::TestCase
-
+ class PolymorphicRoutesTest < ActiveSupport::TestCase
include ActionController::PolymorphicRoutes
def setup
@@ -72,20 +71,22 @@ uses_mocha 'polymorphic URL helpers' do
polymorphic_url(@article, :param1 => '10')
end
- def test_formatted_url_helper
- expects(:formatted_article_url).with(@article, :pdf)
- formatted_polymorphic_url([@article, :pdf])
+ def test_formatted_url_helper_is_deprecated
+ expects(:articles_url).with(:format => :pdf)
+ assert_deprecated do
+ formatted_polymorphic_url([@article, :pdf])
+ end
end
def test_format_option
@article.save
- expects(:formatted_article_url).with(@article, :pdf)
+ expects(:article_url).with(@article, :format => :pdf)
polymorphic_url(@article, :format => :pdf)
end
def test_format_option_with_url_options
@article.save
- expects(:formatted_article_url).with(@article, :pdf, :param1 => '10')
+ expects(:article_url).with(@article, :format => :pdf, :param1 => '10')
polymorphic_url(@article, :format => :pdf, :param1 => '10')
end
@@ -158,17 +159,34 @@ uses_mocha 'polymorphic URL helpers' do
def test_nesting_with_array_containing_singleton_resource_and_format
@tag = Tag.new
@tag.save
- expects(:formatted_article_response_tag_url).with(@article, @tag, :pdf)
- formatted_polymorphic_url([@article, :response, @tag, :pdf])
+ expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
+ polymorphic_url([@article, :response, @tag], :format => :pdf)
end
def test_nesting_with_array_containing_singleton_resource_and_format_option
@tag = Tag.new
@tag.save
- expects(:formatted_article_response_tag_url).with(@article, @tag, :pdf)
+ expects(:article_response_tag_url).with(@article, @tag, :format => :pdf)
polymorphic_url([@article, :response, @tag], :format => :pdf)
end
+ def test_nesting_with_array_containing_nil
+ expects(:article_response_url).with(@article)
+ polymorphic_url([@article, nil, :response])
+ end
+
+ def test_with_array_containing_single_object
+ @article.save
+ expects(:article_url).with(@article)
+ polymorphic_url([nil, @article])
+ end
+
+ def test_with_array_containing_single_name
+ @article.save
+ expects(:articles_url)
+ polymorphic_url([:articles])
+ end
+
# TODO: Needs to be updated to correctly know about whether the object is in a hash or not
def xtest_with_hash
expects(:article_url).with(@article)
diff --git a/actionpack/test/controller/rack_test.rb b/actionpack/test/controller/rack_test.rb
index d5e56b9584..7e8b0f9bf2 100644
--- a/actionpack/test/controller/rack_test.rb
+++ b/actionpack/test/controller/rack_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'action_controller/rack_process'
class BaseRackTest < Test::Unit::TestCase
def setup
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index c55307d645..27cedc91d2 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -103,12 +103,8 @@ class RedirectController < ActionController::Base
end
end
-class RedirectTest < Test::Unit::TestCase
- def setup
- @controller = RedirectController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
+class RedirectTest < ActionController::TestCase
+ tests RedirectController
def test_simple_redirect
get :simple_redirect
@@ -256,12 +252,8 @@ module ModuleTest
end
end
- class ModuleRedirectTest < Test::Unit::TestCase
- def setup
- @controller = ModuleRedirectController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
+ class ModuleRedirectTest < ActionController::TestCase
+ tests ModuleRedirectController
def test_simple_redirect
get :simple_redirect
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index df9376727f..972e425e35 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -39,7 +39,7 @@ class TestController < ActionController::Base
render :action => 'hello_world'
end
before_filter :handle_last_modified_and_etags, :only=>:conditional_hello_with_bangs
-
+
def handle_last_modified_and_etags
fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
end
@@ -246,6 +246,15 @@ class TestController < ActionController::Base
:locals => { :local_name => name }
end
+ def helper_method_to_render_to_string(*args)
+ render_to_string(*args)
+ end
+ helper_method :helper_method_to_render_to_string
+
+ def render_html_only_partial_within_inline
+ render :inline => "Hello world <%= helper_method_to_render_to_string :partial => 'test/partial_with_only_html_version' %>"
+ end
+
def formatted_html_erb
end
@@ -337,6 +346,11 @@ class TestController < ActionController::Base
render :text => "Hi web users! #{@stuff}"
end
+ def render_to_string_with_inline_and_render
+ render_to_string :inline => "<%= 'dlrow olleh'.reverse %>"
+ render :template => "test/hello_world"
+ end
+
def rendering_with_conflicting_local_vars
@name = "David"
def @template.name() nil end
@@ -641,12 +655,10 @@ class TestController < ActionController::Base
end
end
-class RenderTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = TestController.new
+class RenderTest < ActionController::TestCase
+ tests TestController
+ def setup
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
@controller.logger = Logger.new(nil)
@@ -871,12 +883,13 @@ class RenderTest < Test::Unit::TestCase
end
def test_enum_rjs_test
+ ActiveSupport::SecureRandom.stubs(:base64).returns("asdf")
get :enum_rjs_test
body = %{
$$(".product").each(function(value, index) {
new Effect.Highlight(element,{});
new Effect.Highlight(value,{});
- Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value)})}});
+ Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value) + '&authenticity_token=' + encodeURIComponent('asdf')})}});
new Draggable(value, {});
});
}.gsub(/^ /, '').strip
@@ -908,6 +921,11 @@ class RenderTest < Test::Unit::TestCase
assert_equal "The value of foo is: ::this is a test::\n", @response.body
end
+ def test_render_to_string_inline
+ get :render_to_string_with_inline_and_render
+ assert_template "test/hello_world"
+ end
+
def test_nested_rendering
@controller = Fun::GamesController.new
get :hello_world
@@ -924,6 +942,11 @@ class RenderTest < Test::Unit::TestCase
assert_equal "Goodbye, Local David", @response.body
end
+ def test_rendering_html_only_partial_within_inline_with_js
+ get :render_html_only_partial_within_inline, :format => :js
+ assert_equal "Hello world partial with only html version", @response.body
+ end
+
def test_should_render_formatted_template
get :formatted_html_erb
assert_equal 'formatted html erb', @response.body
@@ -1333,12 +1356,10 @@ class RenderTest < Test::Unit::TestCase
end
end
-class EtagRenderTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = TestController.new
+class EtagRenderTest < ActionController::TestCase
+ tests TestController
+ def setup
@request.host = "www.nextangle.com"
@expected_bang_etag = etag_for(expand_key([:foo, 123]))
end
@@ -1368,7 +1389,7 @@ class EtagRenderTest < Test::Unit::TestCase
assert_equal "200 OK", @response.status
assert !@response.body.empty?
end
-
+
def test_render_should_not_set_etag_when_last_modified_has_been_specified
get :render_hello_world_with_last_modified_set
assert_equal "200 OK", @response.status
@@ -1382,7 +1403,7 @@ class EtagRenderTest < Test::Unit::TestCase
expected_etag = etag_for('hello david')
assert_equal expected_etag, @response.headers['ETag']
@response = ActionController::TestResponse.new
-
+
@request.if_none_match = expected_etag
get :render_hello_world_from_variable
assert_equal "304 Not Modified", @response.status
@@ -1407,35 +1428,33 @@ class EtagRenderTest < Test::Unit::TestCase
assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
assert_equal etag_for("<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n"), @response.headers['ETag']
end
-
+
def test_etag_with_bang_should_set_etag
get :conditional_hello_with_bangs
assert_equal @expected_bang_etag, @response.headers["ETag"]
assert_response :success
end
-
+
def test_etag_with_bang_should_obey_if_none_match
@request.if_none_match = @expected_bang_etag
get :conditional_hello_with_bangs
assert_response :not_modified
end
-
+
protected
def etag_for(text)
%("#{Digest::MD5.hexdigest(text)}")
end
-
+
def expand_key(args)
ActiveSupport::Cache.expand_cache_key(args)
end
end
-class LastModifiedRenderTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = TestController.new
+class LastModifiedRenderTest < ActionController::TestCase
+ tests TestController
+ def setup
@request.host = "www.nextangle.com"
@last_modified = Time.now.utc.beginning_of_day.httpdate
end
@@ -1467,13 +1486,13 @@ class LastModifiedRenderTest < Test::Unit::TestCase
assert !@response.body.blank?
assert_equal @last_modified, @response.headers['Last-Modified']
end
-
+
def test_request_with_bang_gets_last_modified
get :conditional_hello_with_bangs
assert_equal @last_modified, @response.headers['Last-Modified']
assert_response :success
end
-
+
def test_request_with_bang_obeys_last_modified
@request.if_modified_since = @last_modified
get :conditional_hello_with_bangs
@@ -1487,12 +1506,10 @@ class LastModifiedRenderTest < Test::Unit::TestCase
end
end
-class RenderingLoggingTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = TestController.new
+class RenderingLoggingTest < ActionController::TestCase
+ tests TestController
+ def setup
@request.host = "www.nextangle.com"
end
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index f7adaa7d4e..ef0bf5fd08 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -5,13 +5,6 @@ ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id'
end
-# simulates cookie session store
-class FakeSessionDbMan
- def self.generate_digest(data)
- Digest::SHA1.hexdigest("secure")
- end
-end
-
# common controller actions
module RequestForgeryProtectionActions
def index
@@ -36,29 +29,10 @@ end
# sample controllers
class RequestForgeryProtectionController < ActionController::Base
include RequestForgeryProtectionActions
- protect_from_forgery :only => :index, :secret => 'abc'
-end
-
-class RequestForgeryProtectionWithoutSecretController < ActionController::Base
- include RequestForgeryProtectionActions
- protect_from_forgery
-end
-
-# no token is given, assume the cookie store is used
-class CsrfCookieMonsterController < ActionController::Base
- include RequestForgeryProtectionActions
protect_from_forgery :only => :index
end
-# sessions are turned off
-class SessionOffController < ActionController::Base
- protect_from_forgery :secret => 'foobar'
- session :off
- def rescue_action(e) raise e end
- include RequestForgeryProtectionActions
-end
-
-class FreeCookieController < CsrfCookieMonsterController
+class FreeCookieController < RequestForgeryProtectionController
self.allow_forgery_protection = false
def index
@@ -77,57 +51,61 @@ module RequestForgeryProtectionTests
ActionController::Base.request_forgery_protection_token = nil
end
+
def test_should_render_form_with_token_tag
- get :index
- assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
- end
-
- def test_should_render_button_to_with_token_tag
- get :show_button
- assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
- end
+ get :index
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
+ end
- def test_should_render_remote_form_with_only_one_token_parameter
- get :remote_form
- assert_equal 1, @response.body.scan(@token).size
- end
+ def test_should_render_button_to_with_token_tag
+ get :show_button
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
+ end
- def test_should_allow_get
- get :index
- assert_response :success
- end
-
- def test_should_allow_post_without_token_on_unsafe_action
- post :unsafe
- assert_response :success
- end
+ def test_should_render_remote_form_with_only_one_token_parameter
+ get :remote_form
+ assert_equal 1, @response.body.scan(@token).size
+ end
- def test_should_not_allow_post_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) { post :index }
- end
+ def test_should_allow_get
+ get :index
+ assert_response :success
+ end
- def test_should_not_allow_put_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) { put :index }
- end
+ def test_should_allow_post_without_token_on_unsafe_action
+ post :unsafe
+ assert_response :success
+ end
- def test_should_not_allow_delete_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) { delete :index }
+ def test_should_not_allow_html_post_without_token
+ @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
+ assert_raises(ActionController::InvalidAuthenticityToken) { post :index, :format => :html }
+ end
+
+ def test_should_not_allow_html_put_without_token
+ @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
+ assert_raises(ActionController::InvalidAuthenticityToken) { put :index, :format => :html }
+ end
+
+ def test_should_not_allow_html_delete_without_token
+ @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
+ assert_raises(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html }
end
- def test_should_not_allow_api_formatted_post_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) do
+ def test_should_allow_api_formatted_post_without_token
+ assert_nothing_raised do
post :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_put_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) do
+ assert_nothing_raised do
put :index, :format => 'xml'
end
end
- def test_should_not_allow_api_formatted_delete_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) do
+ def test_should_allow_api_formatted_delete_without_token
+ assert_nothing_raised do
delete :index, :format => 'xml'
end
end
@@ -174,16 +152,20 @@ module RequestForgeryProtectionTests
end
end
- def test_should_not_allow_xhr_post_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) { xhr :post, :index }
+ def test_should_allow_xhr_post_without_token
+ assert_nothing_raised { xhr :post, :index }
+ end
+ def test_should_not_allow_xhr_post_with_html_without_token
+ @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
+ assert_raise(ActionController::InvalidAuthenticityToken) { xhr :post, :index }
end
- def test_should_not_allow_xhr_put_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) { xhr :put, :index }
+ def test_should_allow_xhr_put_without_token
+ assert_nothing_raised { xhr :put, :index }
end
- def test_should_not_allow_xhr_delete_without_token
- assert_raises(ActionController::InvalidAuthenticityToken) { xhr :delete, :index }
+ def test_should_allow_xhr_delete_without_token
+ assert_nothing_raised { xhr :delete, :index }
end
def test_should_allow_post_with_token
@@ -222,61 +204,28 @@ end
# OK let's get our test on
-class RequestForgeryProtectionControllerTest < Test::Unit::TestCase
+class RequestForgeryProtectionControllerTest < ActionController::TestCase
include RequestForgeryProtectionTests
def setup
@controller = RequestForgeryProtectionController.new
@request = ActionController::TestRequest.new
+ @request.format = :html
@response = ActionController::TestResponse.new
- class << @request.session
- def session_id() '123' end
- end
- @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123')
- ActionController::Base.request_forgery_protection_token = :authenticity_token
- end
-end
+ @token = "cf50faa3fe97702ca1ae"
-class RequestForgeryProtectionWithoutSecretControllerTest < Test::Unit::TestCase
- def setup
- @controller = RequestForgeryProtectionWithoutSecretController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- class << @request.session
- def session_id() '123' end
- end
- @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123')
+ ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
ActionController::Base.request_forgery_protection_token = :authenticity_token
end
-
- def test_should_raise_error_without_secret
- assert_raises ActionController::InvalidAuthenticityToken do
- get :index
- end
- end
end
-class CsrfCookieMonsterControllerTest < Test::Unit::TestCase
- include RequestForgeryProtectionTests
- def setup
- @controller = CsrfCookieMonsterController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- class << @request.session
- attr_accessor :dbman
- end
- # simulate a cookie session store
- @request.session.dbman = FakeSessionDbMan
- @token = Digest::SHA1.hexdigest("secure")
- ActionController::Base.request_forgery_protection_token = :authenticity_token
- end
-end
-
-class FreeCookieControllerTest < Test::Unit::TestCase
+class FreeCookieControllerTest < ActionController::TestCase
def setup
@controller = FreeCookieController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
- @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123')
+ @token = "cf50faa3fe97702ca1ae"
+
+ ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
end
def test_should_not_render_form_with_token_tag
@@ -295,19 +244,3 @@ class FreeCookieControllerTest < Test::Unit::TestCase
end
end
end
-
-class SessionOffControllerTest < Test::Unit::TestCase
- def setup
- @controller = SessionOffController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123')
- end
-
- def test_should_raise_correct_exception
- @request.session = {} # session(:off) doesn't appear to work with controller tests
- assert_raises(ActionController::InvalidAuthenticityToken) do
- post :index, :authenticity_token => @token
- end
- end
-end
diff --git a/actionpack/test/controller/request_test.rb b/actionpack/test/controller/request_test.rb
index e79a0ea76b..ba4a6da39b 100644
--- a/actionpack/test/controller/request_test.rb
+++ b/actionpack/test/controller/request_test.rb
@@ -1,7 +1,6 @@
require 'abstract_unit'
-require 'action_controller/integration'
-class RequestTest < Test::Unit::TestCase
+class RequestTest < ActiveSupport::TestCase
def setup
ActionController::Base.relative_url_root = nil
@request = ActionController::TestRequest.new
@@ -67,6 +66,15 @@ class RequestTest < Test::Unit::TestCase
assert_match /HTTP_X_FORWARDED_FOR="9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4"/, e.message
assert_match /HTTP_CLIENT_IP="8.8.8.8"/, e.message
+ # turn IP Spoofing detection off.
+ # This is useful for sites that are aimed at non-IP clients. The typical
+ # example is WAP. Since the cellular network is not IP based, it's a
+ # leap of faith to assume that their proxies are ever going to set the
+ # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly.
+ ActionController::Base.ip_spoofing_check = false
+ assert_equal('8.8.8.8', @request.remote_ip(true))
+ ActionController::Base.ip_spoofing_check = true
+
@request.env['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 9.9.9.9'
assert_equal '8.8.8.8', @request.remote_ip(true)
@@ -400,7 +408,7 @@ class RequestTest < Test::Unit::TestCase
end
end
-class UrlEncodedRequestParameterParsingTest < Test::Unit::TestCase
+class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase
def setup
@query_string = "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
@query_string_with_empty = "action=create_customer&full_name="
@@ -704,20 +712,20 @@ class UrlEncodedRequestParameterParsingTest < Test::Unit::TestCase
end
end
-class MultipartRequestParameterParsingTest < Test::Unit::TestCase
+class MultipartRequestParameterParsingTest < ActiveSupport::TestCase
FIXTURE_PATH = File.dirname(__FILE__) + '/../fixtures/multipart'
def test_single_parameter
- params = process('single_parameter')
+ params = parse_multipart('single_parameter')
assert_equal({ 'foo' => 'bar' }, params)
end
def test_bracketed_param
- assert_equal({ 'foo' => { 'baz' => 'bar'}}, process('bracketed_param'))
+ assert_equal({ 'foo' => { 'baz' => 'bar'}}, parse_multipart('bracketed_param'))
end
def test_text_file
- params = process('text_file')
+ params = parse_multipart('text_file')
assert_equal %w(file foo), params.keys.sort
assert_equal 'bar', params['foo']
@@ -729,17 +737,13 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
end
def test_boundary_problem_file
- params = process('boundary_problem_file')
+ params = parse_multipart('boundary_problem_file')
assert_equal %w(file foo), params.keys.sort
file = params['file']
foo = params['foo']
- if RUBY_VERSION > '1.9'
- assert_kind_of File, file
- else
- assert_kind_of Tempfile, file
- end
+ assert_kind_of Tempfile, file
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
@@ -748,16 +752,14 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
end
def test_large_text_file
- params = process('large_text_file')
+ params = parse_multipart('large_text_file')
assert_equal %w(file foo), params.keys.sort
assert_equal 'bar', params['foo']
file = params['file']
- if RUBY_VERSION > '1.9'
- assert_kind_of File, file
- else
- assert_kind_of Tempfile, file
- end
+
+ assert_kind_of Tempfile, file
+
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
assert ('a' * 20480) == file.read
@@ -774,7 +776,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
end
def test_binary_file
- params = process('binary_file')
+ params = parse_multipart('binary_file')
assert_equal %w(file flowers foo), params.keys.sort
assert_equal 'bar', params['foo']
@@ -793,7 +795,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
end
def test_mixed_files
- params = process('mixed_files')
+ params = parse_multipart('mixed_files')
assert_equal %w(files foo), params.keys.sort
assert_equal 'bar', params['foo']
@@ -805,7 +807,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
end
private
- def process(name)
+ def parse_multipart(name)
File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
params = ActionController::AbstractRequest.parse_multipart_form_parameters(file, 'AaB03x', file.stat.size, {})
assert_equal 0, file.pos # file was rewound after reading
@@ -814,7 +816,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
end
end
-class XmlParamsParsingTest < Test::Unit::TestCase
+class XmlParamsParsingTest < ActiveSupport::TestCase
def test_hash_params
person = parse_body("<person><name>David</name></person>")[:person]
assert_kind_of Hash, person
@@ -868,7 +870,7 @@ class LegacyXmlParamsParsingTest < XmlParamsParsingTest
end
end
-class JsonParamsParsingTest < Test::Unit::TestCase
+class JsonParamsParsingTest < ActiveSupport::TestCase
def test_hash_params_for_application_json
person = parse_body({:person => {:name => "David"}}.to_json,'application/json')[:person]
assert_kind_of Hash, person
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index 32c6c013f1..63f9827f4a 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -291,24 +291,6 @@ class RescueControllerTest < ActionController::TestCase
assert_equal 'template_error', templates[ActionView::TemplateError.name]
end
- def test_clean_backtrace
- with_rails_root nil do
- # No action if RAILS_ROOT isn't set.
- cleaned = @controller.send(:clean_backtrace, @exception)
- assert_equal @exception.backtrace, cleaned
- end
-
- with_rails_root Dir.pwd do
- # RAILS_ROOT is removed from backtrace.
- cleaned = @controller.send(:clean_backtrace, @exception)
- expected = @exception.backtrace.map { |line| line.sub(RAILS_ROOT, '') }
- assert_equal expected, cleaned
-
- # No action if backtrace is nil.
- assert_nil @controller.send(:clean_backtrace, Exception.new)
- end
- end
-
def test_not_implemented
with_all_requests_local false do
with_rails_public_path(".") do
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index 1fea82e564..8dedeb23f6 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -14,6 +14,8 @@ class LogosController < ResourcesController; end
class AccountsController < ResourcesController; end
class AdminController < ResourcesController; end
+class ProductsController < ResourcesController; end
+class ImagesController < ResourcesController; end
module Backoffice
class ProductsController < ResourcesController; end
@@ -27,7 +29,7 @@ module Backoffice
end
end
-class ResourcesTest < Test::Unit::TestCase
+class ResourcesTest < ActionController::TestCase
# The assertions in these tests are incompatible with the hash method
# optimisation. This could indicate user level problems
def setup
@@ -185,7 +187,7 @@ class ResourcesTest < Test::Unit::TestCase
assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
actions.keys.each do |action|
- assert_named_route "/threads/1/messages/#{action}.xml", "formatted_#{action}_thread_messages_path", :action => action, :format => 'xml'
+ assert_named_route "/threads/1/messages/#{action}.xml", "#{action}_thread_messages_path", :action => action, :format => 'xml'
end
end
end
@@ -314,7 +316,7 @@ class ResourcesTest < Test::Unit::TestCase
end
assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
- assert_named_route preview_path, :formatted_preview_new_thread_message_path, preview_options
+ assert_named_route preview_path, :preview_new_thread_message_path, preview_options
end
end
end
@@ -776,6 +778,235 @@ class ResourcesTest < Test::Unit::TestCase
end
end
+ def test_resource_has_only_show_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :only => :show
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
+ end
+ end
+
+ def test_singleton_resource_has_only_show_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resource :account, :only => :show
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :show, [:index, :new, :create, :edit, :update, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :show, [:index, :new, :create, :edit, :update, :destroy])
+ end
+ end
+
+ def test_resource_does_not_have_destroy_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :except => :destroy
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
+ end
+ end
+
+ def test_singleton_resource_does_not_have_destroy_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resource :account, :except => :destroy
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, [:new, :create, :show, :edit, :update], :destroy)
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [:new, :create, :show, :edit, :update], :destroy)
+ end
+ end
+
+ def test_resource_has_only_create_action_and_named_route
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :only => :create
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy])
+
+ assert_not_nil set.named_routes[:products]
+ end
+ end
+
+ def test_resource_has_only_update_action_and_named_route
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :only => :update
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy])
+
+ assert_not_nil set.named_routes[:product]
+ end
+ end
+
+ def test_resource_has_only_destroy_action_and_named_route
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :only => :destroy
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update])
+
+ assert_not_nil set.named_routes[:product]
+ end
+ end
+
+ def test_singleton_resource_has_only_create_action_and_named_route
+ with_routing do |set|
+ set.draw do |map|
+ map.resource :account, :only => :create
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :create, [:new, :show, :edit, :update, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :create, [:new, :show, :edit, :update, :destroy])
+
+ assert_not_nil set.named_routes[:account]
+ end
+ end
+
+ def test_singleton_resource_has_only_update_action_and_named_route
+ with_routing do |set|
+ set.draw do |map|
+ map.resource :account, :only => :update
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :update, [:new, :create, :show, :edit, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :update, [:new, :create, :show, :edit, :destroy])
+
+ assert_not_nil set.named_routes[:account]
+ end
+ end
+
+ def test_singleton_resource_has_only_destroy_action_and_named_route
+ with_routing do |set|
+ set.draw do |map|
+ map.resource :account, :only => :destroy
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :destroy, [:new, :create, :show, :edit, :update])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :destroy, [:new, :create, :show, :edit, :update])
+
+ assert_not_nil set.named_routes[:account]
+ end
+ end
+
+ def test_resource_has_only_collection_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :except => :all, :collection => { :sale => :get }
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+
+ assert_recognizes({ :controller => 'products', :action => 'sale' }, :path => 'products/sale', :method => :get)
+ assert_recognizes({ :controller => 'products', :action => 'sale', :format => 'xml' }, :path => 'products/sale.xml', :method => :get)
+ end
+ end
+
+ def test_resource_has_only_member_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :except => :all, :member => { :preview => :get }
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+
+ assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1' }, :path => 'products/1/preview', :method => :get)
+ assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1', :format => 'xml' }, :path => 'products/1/preview.xml', :method => :get)
+ end
+ end
+
+ def test_singleton_resource_has_only_member_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resource :account, :except => :all, :member => { :signup => :get }
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, [], [:new, :create, :show, :edit, :update, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [], [:new, :create, :show, :edit, :update, :destroy])
+
+ assert_recognizes({ :controller => 'accounts', :action => 'signup' }, :path => 'account/signup', :method => :get)
+ assert_recognizes({ :controller => 'accounts', :action => 'signup', :format => 'xml' }, :path => 'account/signup.xml', :method => :get)
+ end
+ end
+
+ def test_nested_resource_inherits_only_show_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :only => :show do |product|
+ product.resources :images
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
+ end
+ end
+
+ def test_nested_resource_has_only_show_and_member_action
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :only => [:index, :show] do |product|
+ product.resources :images, :member => { :thumbnail => :get }, :only => :show
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
+
+ assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2' }, :path => 'products/1/images/2/thumbnail', :method => :get)
+ assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2', :format => 'jpg' }, :path => 'products/1/images/2/thumbnail.jpg', :method => :get)
+ end
+ end
+
+ def test_nested_resource_ignores_only_option
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :only => :show do |product|
+ product.resources :images, :except => :destroy
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images')
+ end
+ end
+
+ def test_nested_resource_ignores_except_option
+ with_routing do |set|
+ set.draw do |map|
+ map.resources :products, :except => :show do |product|
+ product.resources :images, :only => :destroy
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images')
+ end
+ end
+
+ def test_default_singleton_restful_route_uses_get
+ with_routing do |set|
+ set.draw do |map|
+ map.resource :product
+ end
+
+ assert_equal :get, set.named_routes.routes[:product].conditions[:method]
+ end
+ end
+
protected
def with_restful_routing(*args)
with_routing do |set|
@@ -899,14 +1130,14 @@ class ResourcesTest < Test::Unit::TestCase
end
assert_named_route "#{full_path}", "#{name_prefix}#{controller_name}_path", options[:options]
- assert_named_route "#{full_path}.xml", "formatted_#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}.xml", "#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml')
assert_named_route "#{shallow_path}/1", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1')
- assert_named_route "#{shallow_path}/1.xml", "formatted_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
+ assert_named_route "#{shallow_path}/1.xml", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
assert_named_route "#{full_path}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", options[:options]
- assert_named_route "#{full_path}/#{new_action}.xml", "formatted_new_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}/#{new_action}.xml", "new_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml')
assert_named_route "#{shallow_path}/1/#{edit_action}", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1')
- assert_named_route "#{shallow_path}/1/#{edit_action}.xml", "formatted_edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
+ assert_named_route "#{shallow_path}/1/#{edit_action}.xml", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
yield options[:options] if block_given?
end
@@ -958,12 +1189,12 @@ class ResourcesTest < Test::Unit::TestCase
name_prefix = options[:name_prefix]
assert_named_route "#{full_path}", "#{name_prefix}#{singleton_name}_path", options[:options]
- assert_named_route "#{full_path}.xml", "formatted_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}.xml", "#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
assert_named_route "#{full_path}/new", "new_#{name_prefix}#{singleton_name}_path", options[:options]
- assert_named_route "#{full_path}/new.xml", "formatted_new_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}/new.xml", "new_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
assert_named_route "#{full_path}/edit", "edit_#{name_prefix}#{singleton_name}_path", options[:options]
- assert_named_route "#{full_path}/edit.xml", "formatted_edit_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}/edit.xml", "edit_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
end
def assert_named_route(expected, route, options)
@@ -979,6 +1210,51 @@ class ResourcesTest < Test::Unit::TestCase
end
end
+ def assert_resource_allowed_routes(controller, options, shallow_options, allowed, not_allowed, path = controller)
+ shallow_path = "#{path}/#{shallow_options[:id]}"
+ format = options[:format] && ".#{options[:format]}"
+ options.merge!(:controller => controller)
+ shallow_options.merge!(options)
+
+ assert_whether_allowed(allowed, not_allowed, options, 'index', "#{path}#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'show', "#{shallow_path}#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'edit', "#{shallow_path}/edit#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'update', "#{shallow_path}#{format}", :put)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'destroy', "#{shallow_path}#{format}", :delete)
+ end
+
+ def assert_singleton_resource_allowed_routes(controller, options, allowed, not_allowed, path = controller.singularize)
+ format = options[:format] && ".#{options[:format]}"
+ options.merge!(:controller => controller)
+
+ assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post)
+ assert_whether_allowed(allowed, not_allowed, options, 'show', "#{path}#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'edit', "#{path}/edit#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'update', "#{path}#{format}", :put)
+ assert_whether_allowed(allowed, not_allowed, options, 'destroy', "#{path}#{format}", :delete)
+ end
+
+ def assert_whether_allowed(allowed, not_allowed, options, action, path, method)
+ action = action.to_sym
+ options = options.merge(:action => action.to_s)
+ path_options = { :path => path, :method => method }
+
+ if Array(allowed).include?(action)
+ assert_recognizes options, path_options
+ elsif Array(not_allowed).include?(action)
+ assert_not_recognizes options, path_options
+ end
+ end
+
+ def assert_not_recognizes(expected_options, path)
+ assert_raise ActionController::RoutingError, ActionController::MethodNotAllowed, Assertion do
+ assert_recognizes(expected_options, path)
+ end
+ end
+
def distinct_routes? (r1, r2)
if r1.conditions == r2.conditions and r1.requirements == r2.requirements then
if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 9699a04abb..d5b6bd6b2a 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -1,6 +1,5 @@
require 'abstract_unit'
require 'controller/fake_controllers'
-require 'action_controller/routing'
class MilestonesController < ActionController::Base
def index() head :ok end
@@ -706,12 +705,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
port = options.delete(:port) || 80
port_string = port == 80 ? '' : ":#{port}"
- host = options.delete(:host) || "named.route.test"
- anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
+ protocol = options.delete(:protocol) || "http"
+ host = options.delete(:host) || "named.route.test"
+ anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
path = routes.generate(options)
- only_path ? "#{path}#{anchor}" : "http://#{host}#{port_string}#{path}#{anchor}"
+ only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}"
end
def request
@@ -747,12 +747,16 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
ActionController::Base.optimise_named_routes = true
@rs = ::ActionController::Routing::RouteSet.new
- @rs.draw {|m| m.connect ':controller/:action/:id' }
ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed)
end
+
+ def teardown
+ @rs.clear!
+ end
def test_default_setup
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
@@ -769,6 +773,7 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
end
def test_ignores_leading_slash
+ @rs.clear!
@rs.draw {|m| m.connect '/:controller/:action/:id'}
test_default_setup
end
@@ -1002,6 +1007,8 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
end
def test_changing_controller
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
+
assert_equal '/admin/stuff/show/10', rs.generate(
{:controller => 'stuff', :action => 'show', :id => 10},
{:controller => 'admin/user', :action => 'index'}
@@ -1155,10 +1162,12 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
end
def test_action_expiry
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
end
def test_recognition_with_uppercase_controller_name
+ @rs.draw {|m| m.connect ':controller/:action/:id' }
assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content"))
assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list"))
assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10"))
@@ -1726,6 +1735,11 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com")
end
+ def test_named_route_url_method_with_protocol
+ controller = setup_named_route_test
+ assert_equal "https://named.route.test/people/5", controller.send(:show_url, 5, :protocol => "https")
+ end
+
def test_named_route_url_method_with_ordered_parameters
controller = setup_named_route_test
assert_equal "http://named.route.test/people/go/7/hello/joe/5",
@@ -2394,13 +2408,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
def setup
routes.instance_variable_set '@routes_last_modified', nil
silence_warnings { Object.const_set :RAILS_ROOT, '.' }
- ActionController::Routing::Routes.configuration_file = File.join(RAILS_ROOT, 'config', 'routes.rb')
+ routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb'))
@stat = stub_everything
end
def teardown
- ActionController::Routing::Routes.configuration_file = nil
+ ActionController::Routing::Routes.configuration_files.clear
Object.send :remove_const, :RAILS_ROOT
end
@@ -2443,12 +2457,24 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
end
def test_load_with_configuration
- routes.configuration_file = "foobarbaz"
+ 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
diff --git a/actionpack/test/controller/session/cookie_store_test.rb b/actionpack/test/controller/session/cookie_store_test.rb
index 010c00fa14..b5f14acc1f 100644
--- a/actionpack/test/controller/session/cookie_store_test.rb
+++ b/actionpack/test/controller/session/cookie_store_test.rb
@@ -1,7 +1,4 @@
require 'abstract_unit'
-require 'action_controller/cgi_process'
-require 'action_controller/cgi_ext'
-
require 'stringio'
@@ -45,8 +42,8 @@ class CookieStoreTest < Test::Unit::TestCase
{ :empty => ['BAgw--0686dcaccc01040f4bd4f35fe160afe9bc04c330', {}],
:a_one => ['BAh7BiIGYWkG--5689059497d7f122a7119f171aef81dcfd807fec', { 'a' => 1 }],
:typical => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7BiILbm90aWNlIgxIZXkgbm93--9d20154623b9eeea05c62ab819be0e2483238759', { 'user_id' => 123, 'flash' => { 'notice' => 'Hey now' }}],
- :flashed => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA==--bf9785a666d3c4ac09f7fe3353496b437546cfbf', { 'user_id' => 123, 'flash' => {} }],
- :double_escaped => [CGI.escape('BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA%3D%3D--bf9785a666d3c4ac09f7fe3353496b437546cfbf'), { 'user_id' => 123, 'flash' => {} }] }
+ :flashed => ['BAh7ByIMdXNlcl9pZGkBeyIKZmxhc2h7AA==--bf9785a666d3c4ac09f7fe3353496b437546cfbf', { 'user_id' => 123, 'flash' => {} }]
+ }
end
@@ -105,15 +102,6 @@ class CookieStoreTest < Test::Unit::TestCase
end
end
- def test_restores_double_encoded_cookies
- set_cookie! cookie_value(:double_escaped)
- new_session do |session|
- session.dbman.restore
- assert_equal session["user_id"], 123
- assert_equal session["flash"], {}
- end
- end
-
def test_close_doesnt_write_cookie_if_data_is_blank
new_session do |session|
assert_no_cookies session
@@ -266,6 +254,7 @@ class CookieStoreTest < Test::Unit::TestCase
@options = self.class.default_session_options.merge(options)
session = CGI::Session.new(cgi, @options)
+ ObjectSpace.undefine_finalizer(session)
assert_nil cgi.output_hidden, "Output hidden params should be empty: #{cgi.output_hidden.inspect}"
assert_nil cgi.output_cookies, "Output cookies should be empty: #{cgi.output_cookies.inspect}"
diff --git a/actionpack/test/controller/session/mem_cache_store_test.rb b/actionpack/test/controller/session/mem_cache_store_test.rb
index a7d48431f8..9ab927a01f 100644
--- a/actionpack/test/controller/session/mem_cache_store_test.rb
+++ b/actionpack/test/controller/session/mem_cache_store_test.rb
@@ -1,7 +1,4 @@
require 'abstract_unit'
-require 'action_controller/cgi_process'
-require 'action_controller/cgi_ext'
-
class CGI::Session
def cache
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index a23428804a..ee7b8ade8c 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
-class TestTest < Test::Unit::TestCase
+class TestTest < ActionController::TestCase
class TestController < ActionController::Base
def no_op
render :text => 'dummy'
@@ -24,7 +24,7 @@ class TestTest < Test::Unit::TestCase
end
def render_raw_post
- raise Test::Unit::AssertionFailedError, "#raw_post is blank" if request.raw_post.blank?
+ raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
render :text => request.raw_post
end
@@ -580,7 +580,7 @@ XML
assert_equal @response.redirect_url, redirect_to_url
# Must be a :redirect response.
- assert_raise(Test::Unit::AssertionFailedError) do
+ assert_raise(ActiveSupport::TestCase::Assertion) do
assert_redirected_to 'created resource'
end
end
@@ -602,21 +602,21 @@ XML
end
end
-class CleanBacktraceTest < Test::Unit::TestCase
+class CleanBacktraceTest < ActionController::TestCase
def test_should_reraise_the_same_object
- exception = Test::Unit::AssertionFailedError.new('message')
+ exception = ActiveSupport::TestCase::Assertion.new('message')
clean_backtrace { raise exception }
- rescue => caught
+ rescue Exception => caught
assert_equal exception.object_id, caught.object_id
assert_equal exception.message, caught.message
end
def test_should_clean_assertion_lines_from_backtrace
path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller")
- exception = Test::Unit::AssertionFailedError.new('message')
+ exception = ActiveSupport::TestCase::Assertion.new('message')
exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"]
clean_backtrace { raise exception }
- rescue => caught
+ rescue Exception => caught
assert_equal ["#{path}/abc"], caught.backtrace
end
@@ -629,21 +629,17 @@ class CleanBacktraceTest < Test::Unit::TestCase
end
end
-class InferringClassNameTest < Test::Unit::TestCase
+class InferringClassNameTest < ActionController::TestCase
def test_determine_controller_class
assert_equal ContentController, determine_class("ContentControllerTest")
end
def test_determine_controller_class_with_nonsense_name
- assert_raises ActionController::NonInferrableControllerError do
- determine_class("HelloGoodBye")
- end
+ assert_nil determine_class("HelloGoodBye")
end
def test_determine_controller_class_with_sensible_name_where_no_controller_exists
- assert_raises ActionController::NonInferrableControllerError do
- determine_class("NoControllerWithThisNameTest")
- end
+ assert_nil determine_class("NoControllerWithThisNameTest")
end
private
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index 64e9a085ca..e9d372544e 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -2,7 +2,7 @@ require 'abstract_unit'
ActionController::UrlRewriter
-class UrlRewriterTests < Test::Unit::TestCase
+class UrlRewriterTests < ActionController::TestCase
def setup
@request = ActionController::TestRequest.new
@params = {}
@@ -85,8 +85,7 @@ class UrlRewriterTests < Test::Unit::TestCase
end
end
-class UrlWriterTests < Test::Unit::TestCase
-
+class UrlWriterTests < ActionController::TestCase
class W
include ActionController::UrlWriter
end
@@ -302,6 +301,42 @@ class UrlWriterTests < Test::Unit::TestCase
assert_generates("/image", :controller=> :image)
end
+ def test_named_routes_with_nil_keys
+ ActionController::Routing::Routes.clear!
+ add_host!
+ ActionController::Routing::Routes.draw do |map|
+ map.main '', :controller => 'posts'
+ map.resources :posts
+ map.connect ':controller/:action/:id'
+ end
+ # We need to create a new class in order to install the new named route.
+ kls = Class.new { include ActionController::UrlWriter }
+ controller = kls.new
+ params = {:action => :index, :controller => :posts, :format => :xml}
+ assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params))
+ params[:format] = nil
+ assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params))
+ ensure
+ ActionController::Routing::Routes.load!
+ end
+
+ def test_formatted_url_methods_are_deprecated
+ ActionController::Routing::Routes.draw do |map|
+ map.resources :posts
+ end
+ # We need to create a new class in order to install the new named route.
+ kls = Class.new { include ActionController::UrlWriter }
+ controller = kls.new
+ params = {:id => 1, :format => :xml}
+ assert_deprecated do
+ assert_equal("/posts/1.xml", controller.send(:formatted_post_path, params))
+ end
+ assert_deprecated do
+ assert_equal("/posts/1.xml", controller.send(:formatted_post_path, 1, :xml))
+ end
+ ensure
+ ActionController::Routing::Routes.load!
+ end
private
def extract_params(url)
url.split('?', 2).last.split('&')
diff --git a/actionpack/test/controller/verification_test.rb b/actionpack/test/controller/verification_test.rb
index b289443129..418a81baa8 100644
--- a/actionpack/test/controller/verification_test.rb
+++ b/actionpack/test/controller/verification_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class VerificationTest < Test::Unit::TestCase
+class VerificationTest < ActionController::TestCase
class TestController < ActionController::Base
verify :only => :guarded_one, :params => "one",
:add_flash => { :error => 'unguarded' },
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
index b859a92cbd..04e14d8eac 100644
--- a/actionpack/test/controller/view_paths_test.rb
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class ViewLoadPathsTest < Test::Unit::TestCase
+class ViewLoadPathsTest < ActionController::TestCase
class TestController < ActionController::Base
def self.controller_path() "test" end
def rescue_action(e) raise end
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index 32f67ddd6c..6d2b3e4f23 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -101,14 +101,13 @@ class WebServiceTest < Test::Unit::TestCase
end
def test_post_xml_using_an_attributted_node_named_type
- ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) }
+ ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access }
process('POST', 'application/xml', '<request><type type="string">Arial,12</type><z>3</z></request>')
assert_equal 'type, z', @controller.response.body
assert @controller.params.has_key?(:type)
- assert_equal 'string', @controller.params['type']['type']
- assert_equal 'Arial,12', @controller.params['type']['content']
- assert_equal '3', @controller.params['z']
+ assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect
+ assert_equal '3', @controller.params['z'], @controller.params.inspect
end
def test_register_and_use_yaml
@@ -128,7 +127,7 @@ class WebServiceTest < Test::Unit::TestCase
end
def test_register_and_use_xml_simple
- ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) }
+ ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access }
process('POST', 'application/xml', '<request><summary>content...</summary><title>SimpleXml</title></request>' )
assert_equal 'summary, title', @controller.response.body
assert @controller.params.has_key?(:summary)
diff --git a/actionpack/test/fixtures/alternate_helpers/foo_helper.rb b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
new file mode 100644
index 0000000000..a956fce6fa
--- /dev/null
+++ b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
@@ -0,0 +1,3 @@
+module FooHelper
+ def baz() end
+end
diff --git a/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb b/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
new file mode 100644
index 0000000000..00e6b6d6da
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
@@ -0,0 +1 @@
+partial with only html version \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/dont_pick_me b/actionpack/test/fixtures/test/dont_pick_me
new file mode 100644
index 0000000000..0157c9e503
--- /dev/null
+++ b/actionpack/test/fixtures/test/dont_pick_me
@@ -0,0 +1 @@
+non-template file \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello.builder b/actionpack/test/fixtures/test/hello.builder
index 86a8bb3d7b..a471553941 100644
--- a/actionpack/test/fixtures/test/hello.builder
+++ b/actionpack/test/fixtures/test/hello.builder
@@ -1,4 +1,4 @@
xml.html do
xml.p "Hello #{@name}"
- xml << render("test/greeting")
+ xml << render(:file => "test/greeting")
end \ No newline at end of file
diff --git a/actionpack/test/template/active_record_helper_i18n_test.rb b/actionpack/test/template/active_record_helper_i18n_test.rb
index 7ba9659814..7e6bf70706 100644
--- a/actionpack/test/template/active_record_helper_i18n_test.rb
+++ b/actionpack/test/template/active_record_helper_i18n_test.rb
@@ -10,37 +10,37 @@ class ActiveRecordHelperI18nTest < Test::Unit::TestCase
@object_name = 'book'
stubs(:content_tag).returns 'content_tag'
- I18n.stubs(:t).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
- I18n.stubs(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
+ I18n.stubs(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
+ I18n.stubs(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
end
def test_error_messages_for_given_a_header_option_it_does_not_translate_header_message
- I18n.expects(:translate).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
- error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en-US')
+ I18n.expects(:translate).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
+ error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en')
end
def test_error_messages_for_given_no_header_option_it_translates_header_message
- I18n.expects(:t).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
+ I18n.expects(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :locale => 'en-US')
+ error_messages_for(:object => @object, :locale => 'en')
end
def test_error_messages_for_given_a_message_option_it_does_not_translate_message
- I18n.expects(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).never
+ I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).never
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :message => 'message', :locale => 'en-US')
+ error_messages_for(:object => @object, :message => 'message', :locale => 'en')
end
def test_error_messages_for_given_no_message_option_it_translates_message
- I18n.expects(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
+ I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
- error_messages_for(:object => @object, :locale => 'en-US')
+ error_messages_for(:object => @object, :locale => 'en')
end
def test_error_messages_for_given_object_name_it_translates_object_name
- I18n.expects(:t).with(:header, :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
+ I18n.expects(:t).with(:header, :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
I18n.expects(:t).with(@object_name, :default => @object_name, :count => 1, :scope => [:activerecord, :models]).once.returns @object_name
- error_messages_for(:object => @object, :locale => 'en-US', :object_name => @object_name)
+ error_messages_for(:object => @object, :locale => 'en', :object_name => @object_name)
end
end
end
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index bade96fe17..7597927f6d 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -239,7 +239,11 @@ class AssetTagHelperTest < ActionView::TestCase
File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true)
assert_equal '<img alt="Rails" src="/images/rails.png?1" />', image_tag('rails.png')
ensure
- ENV["RAILS_ASSET_ID"] = old_asset_id
+ if old_asset_id
+ ENV["RAILS_ASSET_ID"] = old_asset_id
+ else
+ ENV.delete("RAILS_ASSET_ID")
+ end
end
end
@@ -355,6 +359,46 @@ class AssetTagHelperTest < ActionView::TestCase
FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'secure.js'))
end
+ def test_caching_javascript_include_tag_when_caching_on_with_2_argument_object_asset_host
+ ENV['RAILS_ASSET_ID'] = ''
+ ActionController::Base.asset_host = Class.new do
+ def call(source, request)
+ if request.ssl?
+ "#{request.protocol}#{request.host_with_port}"
+ else
+ "#{request.protocol}assets#{source.length}.example.com"
+ end
+ end
+ end.new
+
+ ActionController::Base.perform_caching = true
+
+ assert_equal '/javascripts/vanilla.js'.length, 23
+ assert_dom_equal(
+ %(<script src="http://assets23.example.com/javascripts/vanilla.js" type="text/javascript"></script>),
+ javascript_include_tag(:all, :cache => 'vanilla')
+ )
+
+ assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'vanilla.js'))
+
+ class << @controller.request
+ def protocol() 'https://' end
+ def ssl?() true end
+ end
+
+ assert_equal '/javascripts/secure.js'.length, 22
+ assert_dom_equal(
+ %(<script src="https://localhost/javascripts/secure.js" type="text/javascript"></script>),
+ javascript_include_tag(:all, :cache => 'secure')
+ )
+
+ assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'secure.js'))
+
+ ensure
+ FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'vanilla.js'))
+ FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'secure.js'))
+ end
+
def test_caching_javascript_include_tag_when_caching_on_and_using_subdirectory
ENV["RAILS_ASSET_ID"] = ""
ActionController::Base.asset_host = 'http://a%d.example.com'
@@ -644,4 +688,10 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
ensure
ActionController::Base.asset_host = nil
end
+
+ def test_assert_css_and_js_of_the_same_name_return_correct_extension
+ assert_dom_equal(%(/collaboration/hieraki/javascripts/foo.js), javascript_path("foo"))
+ assert_dom_equal(%(/collaboration/hieraki/stylesheets/foo.css), stylesheet_path("foo"))
+
+ end
end
diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb
index 9247a42d33..8a00a397ca 100644
--- a/actionpack/test/template/atom_feed_helper_test.rb
+++ b/actionpack/test/template/atom_feed_helper_test.rb
@@ -166,12 +166,10 @@ class ScrollsController < ActionController::Base
end
end
-class AtomFeedTest < Test::Unit::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- @controller = ScrollsController.new
+class AtomFeedTest < ActionController::TestCase
+ tests ScrollsController
+ def setup
@request.host = "www.nextangle.com"
end
@@ -255,7 +253,8 @@ class AtomFeedTest < Test::Unit::TestCase
def test_feed_xml_processing_instructions
with_restful_routing(:scrolls) do
get :index, :id => 'feed_with_xml_processing_instructions'
- assert_match %r{<\?xml-stylesheet type="text/css" href="t.css"\?>}, @response.body
+ assert_match %r{<\?xml-stylesheet [^\?]*type="text/css"}, @response.body
+ assert_match %r{<\?xml-stylesheet [^\?]*href="t.css"}, @response.body
end
end
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index e005aa0f03..a68b09bb45 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -12,36 +12,75 @@ uses_mocha 'TestTemplateRecompilation' do
def test_template_gets_compiled
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
assert_equal 1, @compiled_templates.instance_methods.size
end
def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("test/hello_world.erb")
- assert_equal "Hello world!", render("test/hello_world.erb", {:foo => "bar"})
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"})
assert_equal 2, @compiled_templates.instance_methods.size
end
def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
ActionView::Template.any_instance.expects(:compile!).never
- assert_equal "Hello world!", render("test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
end
- def test_compiled_template_will_always_be_recompiled_when_eager_loaded_templates_is_off
- ActionView::PathSet::Path.expects(:eager_load_templates?).times(4).returns(false)
+ def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached
+ ActionView::Template.any_instance.expects(:loaded?).times(3).returns(false)
assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
ActionView::Template.any_instance.expects(:compile!).times(3)
- 3.times { assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
+ 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
assert_equal 1, @compiled_templates.instance_methods.size
end
+ def test_template_changes_are_not_reflected_with_cached_templates
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
+ assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ end
+
+ def test_template_changes_are_reflected_with_uncached_templates
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb")
+ end
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ end
+
private
def render(*args)
- ActionView::Base.new(ActionController::Base.view_paths, {}).render(*args)
+ render_with_cache(*args)
+ end
+
+ def render_with_cache(*args)
+ view_paths = ActionController::Base.view_paths
+ assert view_paths.first.loaded?
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
+
+ def render_without_cache(*args)
+ view_paths = ActionView::Base.process_view_paths(FIXTURE_LOAD_PATH)
+ assert !view_paths.first.loaded?
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
+
+ def modify_template(template, content)
+ filename = "#{FIXTURE_LOAD_PATH}/#{template}"
+ old_content = File.read(filename)
+ begin
+ File.open(filename, "wb+") { |f| f.write(content) }
+ yield
+ ensure
+ File.open(filename, "wb+") { |f| f.write(old_content) }
+ end
end
end
end
diff --git a/actionpack/test/template/date_helper_i18n_test.rb b/actionpack/test/template/date_helper_i18n_test.rb
index bf3b2588c8..dc9616db3b 100644
--- a/actionpack/test/template/date_helper_i18n_test.rb
+++ b/actionpack/test/template/date_helper_i18n_test.rb
@@ -41,11 +41,11 @@ class DateHelperDistanceOfTimeInWordsI18nTests < Test::Unit::TestCase
key, count = *expected
to = @from + diff
- options = {:locale => 'en-US', :scope => :'datetime.distance_in_words'}
+ options = {:locale => 'en', :scope => :'datetime.distance_in_words'}
options[:count] = count if count
I18n.expects(:t).with(key, options)
- distance_of_time_in_words(@from, to, include_seconds, :locale => 'en-US')
+ distance_of_time_in_words(@from, to, include_seconds, :locale => 'en')
end
def test_distance_of_time_pluralizations
@@ -78,36 +78,36 @@ class DateHelperSelectTagsI18nTests < Test::Unit::TestCase
uses_mocha 'date_helper_select_tags_i18n_tests' do
def setup
- I18n.stubs(:translate).with(:'date.month_names', :locale => 'en-US').returns Date::MONTHNAMES
+ I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
end
# select_month
def test_select_month_given_use_month_names_option_does_not_translate_monthnames
I18n.expects(:translate).never
- select_month(8, :locale => 'en-US', :use_month_names => Date::MONTHNAMES)
+ select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
end
def test_select_month_translates_monthnames
- I18n.expects(:translate).with(:'date.month_names', :locale => 'en-US').returns Date::MONTHNAMES
- select_month(8, :locale => 'en-US')
+ I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
+ select_month(8, :locale => 'en')
end
def test_select_month_given_use_short_month_option_translates_abbr_monthnames
- I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en-US').returns Date::ABBR_MONTHNAMES
- select_month(8, :locale => 'en-US', :use_short_month => true)
+ I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES
+ select_month(8, :locale => 'en', :use_short_month => true)
end
# date_or_time_select
def test_date_or_time_select_given_an_order_options_does_not_translate_order
I18n.expects(:translate).never
- datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en-US')
+ datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en')
end
def test_date_or_time_select_given_no_order_options_translates_order
- I18n.expects(:translate).with(:'date.order', :locale => 'en-US').returns [:year, :month, :day]
- datetime_select('post', 'updated_at', :locale => 'en-US')
+ I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day]
+ datetime_select('post', 'updated_at', :locale => 'en')
end
end
end \ No newline at end of file
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 1a645bccc6..49ba140c23 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -1149,6 +1149,46 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, date_select("post", "written_on", :include_blank => true)
end
+
+ def test_date_select_with_nil_and_blank_and_order
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+
+ expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i"/>' + "\n"
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true)
+ end
+
+ def test_date_select_with_nil_and_blank_and_order
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+
+ expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i"/>' + "\n"
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true)
+ end
def test_date_select_cant_override_discard_hour
@post = Post.new
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index a33eb85b66..86a0bb6a79 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'tzinfo'
TZInfo::Timezone.cattr_reader :loaded_zones
@@ -682,4 +683,4 @@ uses_mocha "FormOptionsHelperTest" do
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index 1849a61f2f..0c8af60aa4 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -12,12 +12,19 @@ class FormTagHelperTest < ActionView::TestCase
@controller = @controller.new
end
+ VALID_HTML_ID = /^[A-Za-z][-_:.A-Za-z0-9]*$/ # see http://www.w3.org/TR/html4/types.html#type-name
+
def test_check_box_tag
actual = check_box_tag "admin"
expected = %(<input id="admin" name="admin" type="checkbox" value="1" />)
assert_dom_equal expected, actual
end
+ def test_check_box_tag_id_sanitized
+ label_elem = root_elem(check_box_tag("project[2][admin]"))
+ assert_match VALID_HTML_ID, label_elem['id']
+ end
+
def test_form_tag
actual = form_tag
expected = %(<form action="http://www.example.com" method="post">)
@@ -64,6 +71,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_hidden_field_tag_id_sanitized
+ input_elem = root_elem(hidden_field_tag("item[][title]"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
def test_file_field_tag
assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz")
end
@@ -118,6 +130,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_select_tag_id_sanitized
+ input_elem = root_elem(select_tag("project[1]people", "<option>david</option>"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
def test_text_area_tag_size_string
actual = text_area_tag "body", "hello world", "size" => "20x40"
expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>)
@@ -184,6 +201,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_text_field_tag_id_sanitized
+ input_elem = root_elem(text_field_tag("item[][title]"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
def test_label_tag_without_text
actual = label_tag "title"
expected = %(<label for="title">Title</label>)
@@ -208,11 +230,17 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
- def test_boolean_optios
+ def test_label_tag_id_sanitized
+ label_elem = root_elem(label_tag("item[title]"))
+ assert_match VALID_HTML_ID, label_elem['for']
+ end
+
+ def test_boolean_options
assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes")
assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil)
+ assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false)
assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => true)
- assert_dom_equal %(<select id="people[]" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>", :multiple => true)
+ assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>", :multiple => true)
assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => nil)
end
@@ -283,4 +311,10 @@ class FormTagHelperTest < ActionView::TestCase
def protect_against_forgery?
false
end
+
+ private
+
+ def root_elem(rendered_content)
+ HTML::Document.new(rendered_content).root.children[0]
+ end
end
diff --git a/actionpack/test/template/number_helper_i18n_test.rb b/actionpack/test/template/number_helper_i18n_test.rb
index 2ee7f43a65..2528bead36 100644
--- a/actionpack/test/template/number_helper_i18n_test.rb
+++ b/actionpack/test/template/number_helper_i18n_test.rb
@@ -10,45 +10,48 @@ class NumberHelperI18nTests < Test::Unit::TestCase
@number_defaults = { :precision => 3, :delimiter => ',', :separator => '.' }
@currency_defaults = { :unit => '$', :format => '%u%n', :precision => 2 }
@human_defaults = { :precision => 1 }
+ @human_storage_units_defaults = %w(Bytes KB MB GB TB)
@percentage_defaults = { :delimiter => '' }
@precision_defaults = { :delimiter => '' }
- I18n.backend.store_translations 'en-US', :number => { :format => @number_defaults,
+ I18n.backend.store_translations 'en', :number => { :format => @number_defaults,
:currency => { :format => @currency_defaults }, :human => @human_defaults }
end
def test_number_to_currency_translates_currency_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.currency.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.currency.format', :locale => 'en',
:raise => true).returns(@currency_defaults)
- number_to_currency(1, :locale => 'en-US')
+ number_to_currency(1, :locale => 'en')
end
def test_number_with_precision_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.precision.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.precision.format', :locale => 'en',
:raise => true).returns(@precision_defaults)
- number_with_precision(1, :locale => 'en-US')
+ number_with_precision(1, :locale => 'en')
end
def test_number_with_delimiter_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- number_with_delimiter(1, :locale => 'en-US')
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ number_with_delimiter(1, :locale => 'en')
end
def test_number_to_percentage_translates_number_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en',
:raise => true).returns(@percentage_defaults)
- number_to_percentage(1, :locale => 'en-US')
+ number_to_percentage(1, :locale => 'en')
end
def test_number_to_human_size_translates_human_formats
- I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
- I18n.expects(:translate).with(:'number.human.format', :locale => 'en-US',
+ I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
+ I18n.expects(:translate).with(:'number.human.format', :locale => 'en',
:raise => true).returns(@human_defaults)
+ I18n.expects(:translate).with(:'number.human.storage_units', :locale => 'en',
+ :raise => true).returns(@human_storage_units_defaults)
# can't be called with 1 because this directly returns without calling I18n.translate
- number_to_human_size(1025, :locale => 'en-US')
+ number_to_human_size(1025, :locale => 'en')
end
end
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 476e651757..9e827abbca 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -1,14 +1,14 @@
require 'abstract_unit'
require 'controller/fake_models'
-class ViewRenderTest < Test::Unit::TestCase
- def setup
+module RenderTestCases
+ def setup_view(paths)
@assigns = { :secret => 'in the sauce' }
- @view = ActionView::Base.new(ActionController::Base.view_paths, @assigns)
+ @view = ActionView::Base.new(paths, @assigns)
end
def test_render_file
- assert_equal "Hello world!", @view.render("test/hello_world.erb")
+ assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb")
end
def test_render_file_not_using_full_path
@@ -16,11 +16,11 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_file_without_specific_extension
- assert_equal "Hello world!", @view.render("test/hello_world")
+ assert_equal "Hello world!", @view.render(:file => "test/hello_world")
end
def test_render_file_at_top_level
- assert_equal 'Elastica', @view.render('/shared')
+ assert_equal 'Elastica', @view.render(:file => '/shared')
end
def test_render_file_with_full_path
@@ -29,20 +29,20 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_file_with_instance_variables
- assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_ivar.erb")
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar.erb")
end
def test_render_file_with_locals
locals = { :secret => 'in the sauce' }
- assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_locals.erb", locals)
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals.erb", :locals => locals)
end
def test_render_file_not_using_full_path_with_dot_in_path
- assert_equal "The secret is in the sauce\n", @view.render("test/dot.directory/render_file_with_ivar")
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/dot.directory/render_file_with_ivar")
end
def test_render_has_access_current_template
- assert_equal "test/template.erb", @view.render("test/template.erb")
+ assert_equal "test/template.erb", @view.render(:file => "test/template.erb")
end
def test_render_update
@@ -51,6 +51,10 @@ class ViewRenderTest < Test::Unit::TestCase
assert_equal 'alert("Hello, World!");', @view.render(:update) { |page| page.alert('Hello, World!') }
end
+ def test_render_partial_from_default
+ assert_equal "only partial", @view.render("test/partial_only")
+ end
+
def test_render_partial
assert_equal "only partial", @view.render(:partial => "test/partial_only")
end
@@ -73,6 +77,10 @@ class ViewRenderTest < Test::Unit::TestCase
assert_equal "5", @view.render(:partial => "test/counter", :locals => { :counter_counter => 5 })
end
+ def test_render_partial_with_locals_from_default
+ assert_equal "only partial", @view.render("test/partial_only", :counter_counter => 5)
+ end
+
def test_render_partial_with_errors
@view.render(:partial => "test/raise")
flunk "Render did not raise TemplateError"
@@ -149,7 +157,7 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_fallbacks_to_erb_for_unknown_types
- assert_equal "Hello, World!", @view.render(:inline => "Hello, World!", :type => :foo)
+ assert_equal "Hello, World!", @view.render(:inline => "Hello, World!", :type => :bar)
end
CustomHandler = lambda do |template|
@@ -167,6 +175,17 @@ class ViewRenderTest < Test::Unit::TestCase
assert_equal 'source: "Hello, <%= name %>!"', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo)
end
+ class LegacyHandler < ActionView::TemplateHandler
+ def render(template, local_assigns)
+ "source: #{template.source}; locals: #{local_assigns.inspect}"
+ end
+ end
+
+ def test_render_legacy_handler_with_custom_type
+ ActionView::Template.register_template_handler :foo, LegacyHandler
+ assert_equal 'source: Hello, <%= name %>!; locals: {:name=>"Josh"}', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo)
+ end
+
def test_render_with_layout
assert_equal %(<title></title>\nHello world!\n),
@view.render(:file => "test/hello_world.erb", :layout => "layouts/yield")
@@ -177,3 +196,26 @@ class ViewRenderTest < Test::Unit::TestCase
@view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield")
end
end
+
+class CachedViewRenderTest < Test::Unit::TestCase
+ include RenderTestCases
+
+ # Ensure view path cache is primed
+ def setup
+ view_paths = ActionController::Base.view_paths
+ assert view_paths.first.loaded?
+ setup_view(view_paths)
+ end
+end
+
+class LazyViewRenderTest < Test::Unit::TestCase
+ include RenderTestCases
+
+ # Test the same thing as above, but make sure the view path
+ # is not eager loaded
+ def setup
+ view_paths = ActionView::Base.process_view_paths(FIXTURE_LOAD_PATH)
+ assert !view_paths.first.loaded?
+ setup_view(view_paths)
+ end
+end
diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb
index fc49d340ef..ef88cae5b8 100644
--- a/actionpack/test/template/tag_helper_test.rb
+++ b/actionpack/test/template/tag_helper_test.rb
@@ -19,6 +19,10 @@ class TagHelperTest < ActionView::TestCase
assert_equal "<p />", tag("p", :ignored => nil)
end
+ def test_tag_options_accepts_false_option
+ assert_equal "<p value=\"false\" />", tag("p", :value => false)
+ end
+
def test_tag_options_accepts_blank_option
assert_equal "<p included=\"\" />", tag("p", :included => '')
end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index 5f9f715819..a6200fbdd7 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -205,55 +205,48 @@ class TextHelperTest < ActionView::TestCase
end
def test_auto_link_parsing
- urls = %w(http://www.rubyonrails.com
- http://www.rubyonrails.com:80
- http://www.rubyonrails.com/~minam
- https://www.rubyonrails.com/~minam
- http://www.rubyonrails.com/~minam/url%20with%20spaces
- http://www.rubyonrails.com/foo.cgi?something=here
- http://www.rubyonrails.com/foo.cgi?something=here&and=here
- http://www.rubyonrails.com/contact;new
- http://www.rubyonrails.com/contact;new%20with%20spaces
- http://www.rubyonrails.com/contact;new?with=query&string=params
- http://www.rubyonrails.com/~minam/contact;new?with=query&string=params
- http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007
- http://www.mail-archive.com/rails@lists.rubyonrails.org/
- http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1
- http://en.wikipedia.org/wiki/Sprite_(computer_graphics)
- http://en.wikipedia.org/wiki/Texas_hold'em
- )
+ urls = %w(
+ http://www.rubyonrails.com
+ http://www.rubyonrails.com:80
+ http://www.rubyonrails.com/~minam
+ https://www.rubyonrails.com/~minam
+ http://www.rubyonrails.com/~minam/url%20with%20spaces
+ http://www.rubyonrails.com/foo.cgi?something=here
+ http://www.rubyonrails.com/foo.cgi?something=here&and=here
+ http://www.rubyonrails.com/contact;new
+ http://www.rubyonrails.com/contact;new%20with%20spaces
+ http://www.rubyonrails.com/contact;new?with=query&string=params
+ http://www.rubyonrails.com/~minam/contact;new?with=query&string=params
+ http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007
+ http://www.mail-archive.com/rails@lists.rubyonrails.org/
+ http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1
+ http://en.wikipedia.org/wiki/Texas_hold'em
+ https://www.google.com/doku.php?id=gps:resource:scs:start
+ http://connect.oraclecorp.com/search?search[q]=green+france&search[type]=Group
+ http://of.openfoundry.org/projects/492/download#4th.Release.3
+ http://maps.google.co.uk/maps?f=q&q=the+london+eye&ie=UTF8&ll=51.503373,-0.11939&spn=0.007052,0.012767&z=16&iwloc=A
+ )
urls.each do |url|
- assert_equal %(<a href="#{url}">#{url}</a>), auto_link(url)
+ assert_equal generate_result(url), auto_link(url)
end
end
+ def generate_result(link_text, href = nil)
+ href ||= link_text
+ %{<a href="#{CGI::escapeHTML href}">#{CGI::escapeHTML link_text}</a>}
+ end
+
def test_auto_linking
email_raw = 'david@loudthinking.com'
email_result = %{<a href="mailto:#{email_raw}">#{email_raw}</a>}
- email2_raw = '+david@loudthinking.com'
- email2_result = %{<a href="mailto:#{email2_raw}">#{email2_raw}</a>}
link_raw = 'http://www.rubyonrails.com'
- link_result = %{<a href="#{link_raw}">#{link_raw}</a>}
- link_result_with_options = %{<a href="#{link_raw}" target="_blank">#{link_raw}</a>}
- link2_raw = 'www.rubyonrails.com'
- link2_result = %{<a href="http://#{link2_raw}">#{link2_raw}</a>}
- link3_raw = 'http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281'
- link3_result = %{<a href="#{link3_raw}">#{link3_raw}</a>}
- link4_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor123'
- link4_result = %{<a href="#{link4_raw}">#{link4_raw}</a>}
- link5_raw = 'http://foo.example.com:3000/controller/action'
- link5_result = %{<a href="#{link5_raw}">#{link5_raw}</a>}
- link6_raw = 'http://foo.example.com:3000/controller/action+pack'
- link6_result = %{<a href="#{link6_raw}">#{link6_raw}</a>}
- link7_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor-123'
- link7_result = %{<a href="#{link7_raw}">#{link7_raw}</a>}
- link8_raw = 'http://foo.example.com:3000/controller/action.html'
- link8_result = %{<a href="#{link8_raw}">#{link8_raw}</a>}
- link9_raw = 'http://business.timesonline.co.uk/article/0,,9065-2473189,00.html'
- link9_result = %{<a href="#{link9_raw}">#{link9_raw}</a>}
- link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/'
- link10_result = %{<a href="#{link10_raw}">#{link10_raw}</a>}
+ link_result = generate_result(link_raw)
+ link_result_with_options = %{<a href="#{link_raw}" target="_blank">#{link_raw}</a>}
+
+ assert_equal '', auto_link(nil)
+ assert_equal '', auto_link('')
+ assert_equal "#{link_result} #{link_result} #{link_result}", auto_link("#{link_raw} #{link_raw} #{link_raw}")
assert_equal %(hello #{email_result}), auto_link("hello #{email_raw}", :email_addresses)
assert_equal %(Go to #{link_result}), auto_link("Go to #{link_raw}", :urls)
@@ -264,41 +257,99 @@ class TextHelperTest < ActionView::TestCase
assert_equal %(<p>Link #{link_result_with_options}</p>), auto_link("<p>Link #{link_raw}</p>", :all, {:target => "_blank"})
assert_equal %(Go to #{link_result}.), auto_link(%(Go to #{link_raw}.))
assert_equal %(<p>Go to #{link_result}, then say hello to #{email_result}.</p>), auto_link(%(<p>Go to #{link_raw}, then say hello to #{email_raw}.</p>))
+
+ email2_raw = '+david@loudthinking.com'
+ email2_result = %{<a href="mailto:#{email2_raw}">#{email2_raw}</a>}
+ assert_equal email2_result, auto_link(email2_raw)
+
+ email3_raw = '+david@loudthinking.com'
+ email3_result = %{<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;+%64%61%76%69%64@%6c%6f%75%64%74%68%69%6e%6b%69%6e%67.%63%6f%6d">#{email3_raw}</a>}
+ assert_equal email3_result, auto_link(email3_raw, :all, :encode => :hex)
+ assert_equal email3_result, auto_link(email3_raw, :email_addresses, :encode => :hex)
+
+ link2_raw = 'www.rubyonrails.com'
+ link2_result = generate_result(link2_raw, "http://#{link2_raw}")
assert_equal %(Go to #{link2_result}), auto_link("Go to #{link2_raw}", :urls)
assert_equal %(Go to #{link2_raw}), auto_link("Go to #{link2_raw}", :email_addresses)
assert_equal %(<p>Link #{link2_result}</p>), auto_link("<p>Link #{link2_raw}</p>")
assert_equal %(<p>#{link2_result} Link</p>), auto_link("<p>#{link2_raw} Link</p>")
assert_equal %(Go to #{link2_result}.), auto_link(%(Go to #{link2_raw}.))
assert_equal %(<p>Say hello to #{email_result}, then go to #{link2_result}.</p>), auto_link(%(<p>Say hello to #{email_raw}, then go to #{link2_raw}.</p>))
+
+ link3_raw = 'http://manuals.ruby-on-rails.com/read/chapter.need_a-period/103#page281'
+ link3_result = generate_result(link3_raw)
assert_equal %(Go to #{link3_result}), auto_link("Go to #{link3_raw}", :urls)
assert_equal %(Go to #{link3_raw}), auto_link("Go to #{link3_raw}", :email_addresses)
assert_equal %(<p>Link #{link3_result}</p>), auto_link("<p>Link #{link3_raw}</p>")
assert_equal %(<p>#{link3_result} Link</p>), auto_link("<p>#{link3_raw} Link</p>")
assert_equal %(Go to #{link3_result}.), auto_link(%(Go to #{link3_raw}.))
- assert_equal %(<p>Go to #{link3_result}. seriously, #{link3_result}? i think I'll say hello to #{email_result}. instead.</p>), auto_link(%(<p>Go to #{link3_raw}. seriously, #{link3_raw}? i think I'll say hello to #{email_raw}. instead.</p>))
+ assert_equal %(<p>Go to #{link3_result}. Seriously, #{link3_result}? I think I'll say hello to #{email_result}. Instead.</p>),
+ auto_link(%(<p>Go to #{link3_raw}. Seriously, #{link3_raw}? I think I'll say hello to #{email_raw}. Instead.</p>))
+
+ link4_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor123'
+ link4_result = generate_result(link4_raw)
assert_equal %(<p>Link #{link4_result}</p>), auto_link("<p>Link #{link4_raw}</p>")
assert_equal %(<p>#{link4_result} Link</p>), auto_link("<p>#{link4_raw} Link</p>")
+
+ link5_raw = 'http://foo.example.com:3000/controller/action'
+ link5_result = generate_result(link5_raw)
assert_equal %(<p>#{link5_result} Link</p>), auto_link("<p>#{link5_raw} Link</p>")
+
+ link6_raw = 'http://foo.example.com:3000/controller/action+pack'
+ link6_result = generate_result(link6_raw)
assert_equal %(<p>#{link6_result} Link</p>), auto_link("<p>#{link6_raw} Link</p>")
+
+ link7_raw = 'http://foo.example.com/controller/action?parm=value&p2=v2#anchor-123'
+ link7_result = generate_result(link7_raw)
assert_equal %(<p>#{link7_result} Link</p>), auto_link("<p>#{link7_raw} Link</p>")
+
+ link8_raw = 'http://foo.example.com:3000/controller/action.html'
+ link8_result = generate_result(link8_raw)
assert_equal %(Go to #{link8_result}), auto_link("Go to #{link8_raw}", :urls)
assert_equal %(Go to #{link8_raw}), auto_link("Go to #{link8_raw}", :email_addresses)
assert_equal %(<p>Link #{link8_result}</p>), auto_link("<p>Link #{link8_raw}</p>")
assert_equal %(<p>#{link8_result} Link</p>), auto_link("<p>#{link8_raw} Link</p>")
assert_equal %(Go to #{link8_result}.), auto_link(%(Go to #{link8_raw}.))
- assert_equal %(<p>Go to #{link8_result}. seriously, #{link8_result}? i think I'll say hello to #{email_result}. instead.</p>), auto_link(%(<p>Go to #{link8_raw}. seriously, #{link8_raw}? i think I'll say hello to #{email_raw}. instead.</p>))
+ assert_equal %(<p>Go to #{link8_result}. Seriously, #{link8_result}? I think I'll say hello to #{email_result}. Instead.</p>),
+ auto_link(%(<p>Go to #{link8_raw}. Seriously, #{link8_raw}? I think I'll say hello to #{email_raw}. Instead.</p>))
+
+ link9_raw = 'http://business.timesonline.co.uk/article/0,,9065-2473189,00.html'
+ link9_result = generate_result(link9_raw)
assert_equal %(Go to #{link9_result}), auto_link("Go to #{link9_raw}", :urls)
assert_equal %(Go to #{link9_raw}), auto_link("Go to #{link9_raw}", :email_addresses)
assert_equal %(<p>Link #{link9_result}</p>), auto_link("<p>Link #{link9_raw}</p>")
assert_equal %(<p>#{link9_result} Link</p>), auto_link("<p>#{link9_raw} Link</p>")
assert_equal %(Go to #{link9_result}.), auto_link(%(Go to #{link9_raw}.))
- assert_equal %(<p>Go to #{link9_result}. seriously, #{link9_result}? i think I'll say hello to #{email_result}. instead.</p>), auto_link(%(<p>Go to #{link9_raw}. seriously, #{link9_raw}? i think I'll say hello to #{email_raw}. instead.</p>))
+ assert_equal %(<p>Go to #{link9_result}. Seriously, #{link9_result}? I think I'll say hello to #{email_result}. Instead.</p>),
+ auto_link(%(<p>Go to #{link9_raw}. Seriously, #{link9_raw}? I think I'll say hello to #{email_raw}. Instead.</p>))
+
+ link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/'
+ link10_result = generate_result(link10_raw)
assert_equal %(<p>#{link10_result} Link</p>), auto_link("<p>#{link10_raw} Link</p>")
- assert_equal email2_result, auto_link(email2_raw)
- assert_equal '', auto_link(nil)
- assert_equal '', auto_link('')
- assert_equal "#{link_result} #{link_result} #{link_result}", auto_link("#{link_raw} #{link_raw} #{link_raw}")
- assert_equal '<a href="http://www.rubyonrails.com">Ruby On Rails</a>', auto_link('<a href="http://www.rubyonrails.com">Ruby On Rails</a>')
+ end
+
+ def test_auto_link_already_linked
+ linked1 = generate_result('Ruby On Rails', 'http://www.rubyonrails.com')
+ linked2 = generate_result('www.rubyonrails.com', 'http://www.rubyonrails.com')
+ assert_equal linked1, auto_link(linked1)
+ assert_equal linked2, auto_link(linked2)
+ end
+
+ def test_auto_link_with_brackets
+ link1_raw = 'http://en.wikipedia.org/wiki/Sprite_(computer_graphics)'
+ link1_result = generate_result(link1_raw)
+ assert_equal link1_result, auto_link(link1_raw)
+ assert_equal "(link: #{link1_result})", auto_link("(link: #{link1_raw})")
+
+ link2_raw = 'http://en.wikipedia.org/wiki/Sprite_[computer_graphics]'
+ link2_result = generate_result(link2_raw)
+ assert_equal link2_result, auto_link(link2_raw)
+ assert_equal "[link: #{link2_result}]", auto_link("[link: #{link2_raw}]")
+
+ link3_raw = 'http://en.wikipedia.org/wiki/Sprite_{computer_graphics}'
+ link3_result = generate_result(link3_raw)
+ assert_equal link3_result, auto_link(link3_raw)
+ assert_equal "{link: #{link3_result}}", auto_link("{link: #{link3_raw}}")
end
def test_auto_link_at_eol
@@ -316,7 +367,7 @@ class TextHelperTest < ActionView::TestCase
end
def test_auto_link_with_options_hash
- assert_equal 'Welcome to my new blog at <a href="http://www.myblog.com/" class="menu" target="_blank">http://www.myblog.com/</a>. Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.',
+ assert_dom_equal 'Welcome to my new blog at <a href="http://www.myblog.com/" class="menu" target="_blank">http://www.myblog.com/</a>. Please e-mail me at <a href="mailto:me@email.com" class="menu" target="_blank">me@email.com</a>.',
auto_link("Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com.",
:link => :all, :html => { :class => "menu", :target => "_blank" })
end
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index 1b28a59288..d0d65cb450 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -10,12 +10,12 @@ class TranslationHelperTest < Test::Unit::TestCase
end
def test_delegates_to_i18n_setting_the_raise_option
- I18n.expects(:translate).with(:foo, :locale => 'en-US', :raise => true)
- translate :foo, :locale => 'en-US'
+ I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true)
+ translate :foo, :locale => 'en'
end
def test_returns_missing_translation_message_wrapped_into_span
- expected = '<span class="translation_missing">en-US, foo</span>'
+ expected = '<span class="translation_missing">en, foo</span>'
assert_equal expected, translate(:foo)
end
diff --git a/activemodel/lib/active_model/state_machine.rb b/activemodel/lib/active_model/state_machine.rb
index 96df6539ae..bce90fd743 100644
--- a/activemodel/lib/active_model/state_machine.rb
+++ b/activemodel/lib/active_model/state_machine.rb
@@ -1,14 +1,10 @@
-Dir[File.dirname(__FILE__) + "/state_machine/*.rb"].sort.each do |path|
- filename = File.basename(path)
- require "active_model/state_machine/#{filename}"
-end
-
module ActiveModel
module StateMachine
class InvalidTransition < Exception
end
def self.included(base)
+ require 'active_model/state_machine/machine'
base.extend ClassMethods
end
@@ -35,6 +31,12 @@ module ActiveModel
state_machines[name] ||= Machine.new(self, name)
block ? state_machines[name].update(options, &block) : state_machines[name]
end
+
+ def define_state_query_method(state_name)
+ name = "#{state_name}?"
+ undef_method(name) if method_defined?(name)
+ class_eval "def #{name}; current_state.to_s == %(#{state_name}) end"
+ end
end
def current_state(name = nil, new_state = nil, persist = false)
@@ -63,4 +65,4 @@ module ActiveModel
end
end
end
-end \ No newline at end of file
+end
diff --git a/activemodel/lib/active_model/state_machine/event.rb b/activemodel/lib/active_model/state_machine/event.rb
index 8acde7fd47..3eb656b6d6 100644
--- a/activemodel/lib/active_model/state_machine/event.rb
+++ b/activemodel/lib/active_model/state_machine/event.rb
@@ -1,3 +1,5 @@
+require 'active_model/state_machine/state_transition'
+
module ActiveModel
module StateMachine
class Event
diff --git a/activemodel/lib/active_model/state_machine/machine.rb b/activemodel/lib/active_model/state_machine/machine.rb
index 170505c0b2..a5ede021b1 100644
--- a/activemodel/lib/active_model/state_machine/machine.rb
+++ b/activemodel/lib/active_model/state_machine/machine.rb
@@ -1,7 +1,11 @@
+require 'active_model/state_machine/state'
+require 'active_model/state_machine/event'
+
module ActiveModel
module StateMachine
class Machine
- attr_accessor :initial_state, :states, :events, :state_index
+ attr_writer :initial_state
+ attr_accessor :states, :events, :state_index
attr_reader :klass, :name
def initialize(klass, name, options = {}, &block)
@@ -71,4 +75,4 @@ module ActiveModel
end
end
end
-end \ No newline at end of file
+end
diff --git a/activemodel/lib/active_model/state_machine/state.rb b/activemodel/lib/active_model/state_machine/state.rb
index 68eb2aa34a..76916b1d86 100644
--- a/activemodel/lib/active_model/state_machine/state.rb
+++ b/activemodel/lib/active_model/state_machine/state.rb
@@ -5,11 +5,8 @@ module ActiveModel
def initialize(name, options = {})
@name = name
- machine = options.delete(:machine)
- if machine
- machine.klass.send(:define_method, "#{name}?") do
- current_state.to_s == name.to_s
- end
+ if machine = options.delete(:machine)
+ machine.klass.define_state_query_method(name)
end
update(options)
end
diff --git a/activemodel/test/observing_test.rb b/activemodel/test/observing_test.rb
index 6e124de52f..dc41c9f881 100644
--- a/activemodel/test/observing_test.rb
+++ b/activemodel/test/observing_test.rb
@@ -1,4 +1,4 @@
-require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper'))
+require 'test_helper'
class ObservedModel < ActiveModel::Base
class Observer
@@ -40,24 +40,22 @@ class ObservingTest < ActiveModel::TestCase
assert ObservedModel.observers.include?(:bar), ":bar not in #{ObservedModel.observers.inspect}"
end
- uses_mocha "observer instantiation" do
- test "instantiates observer names passed as strings" do
- ObservedModel.observers << 'foo_observer'
- FooObserver.expects(:instance)
- ObservedModel.instantiate_observers
- end
-
- test "instantiates observer names passed as symbols" do
- ObservedModel.observers << :foo_observer
- FooObserver.expects(:instance)
- ObservedModel.instantiate_observers
- end
-
- test "instantiates observer classes" do
- ObservedModel.observers << ObservedModel::Observer
- ObservedModel::Observer.expects(:instance)
- ObservedModel.instantiate_observers
- end
+ test "instantiates observer names passed as strings" do
+ ObservedModel.observers << 'foo_observer'
+ FooObserver.expects(:instance)
+ ObservedModel.instantiate_observers
+ end
+
+ test "instantiates observer names passed as symbols" do
+ ObservedModel.observers << :foo_observer
+ FooObserver.expects(:instance)
+ ObservedModel.instantiate_observers
+ end
+
+ test "instantiates observer classes" do
+ ObservedModel.observers << ObservedModel::Observer
+ ObservedModel::Observer.expects(:instance)
+ ObservedModel.instantiate_observers
end
test "passes observers to subclasses" do
@@ -120,4 +118,4 @@ class ObserverTest < ActiveModel::TestCase
Foo.send(:changed)
Foo.send(:notify_observers, :whatever, foo)
end
-end \ No newline at end of file
+end
diff --git a/activemodel/test/state_machine/event_test.rb b/activemodel/test/state_machine/event_test.rb
index 40b630da7c..8fb7e82ec2 100644
--- a/activemodel/test/state_machine/event_test.rb
+++ b/activemodel/test/state_machine/event_test.rb
@@ -1,31 +1,29 @@
-require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
+require 'test_helper'
class EventTest < ActiveModel::TestCase
def setup
- @name = :close_order
+ @state_name = :close_order
@success = :success_callback
end
def new_event
- @event = ActiveModel::StateMachine::Event.new(nil, @name, {:success => @success}) do
+ @event = ActiveModel::StateMachine::Event.new(nil, @state_name, {:success => @success}) do
transitions :to => :closed, :from => [:open, :received]
end
end
test 'should set the name' do
- assert_equal @name, new_event.name
+ assert_equal @state_name, new_event.name
end
test 'should set the success option' do
assert_equal @success, new_event.success
end
- uses_mocha 'StateTransition creation' do
- test 'should create StateTransitions' do
- ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :open)
- ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :received)
- new_event
- end
+ test 'should create StateTransitions' do
+ ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :open)
+ ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :received)
+ new_event
end
end
diff --git a/activemodel/test/state_machine/machine_test.rb b/activemodel/test/state_machine/machine_test.rb
index 2cdfcd9554..d23c223160 100644
--- a/activemodel/test/state_machine/machine_test.rb
+++ b/activemodel/test/state_machine/machine_test.rb
@@ -1,4 +1,4 @@
-require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
+require 'test_helper'
class MachineTestSubject
include ActiveModel::StateMachine
@@ -40,4 +40,4 @@ class StateMachineMachineTest < ActiveModel::TestCase
assert events.include?(:shutdown)
assert events.include?(:timeout)
end
-end \ No newline at end of file
+end
diff --git a/activemodel/test/state_machine/state_test.rb b/activemodel/test/state_machine/state_test.rb
index 22d0d9eb93..fbf9ce7b0a 100644
--- a/activemodel/test/state_machine/state_test.rb
+++ b/activemodel/test/state_machine/state_test.rb
@@ -1,4 +1,4 @@
-require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
+require 'test_helper'
class StateTestSubject
include ActiveModel::StateMachine
@@ -9,13 +9,13 @@ end
class StateTest < ActiveModel::TestCase
def setup
- @name = :astate
+ @state_name = :astate
@machine = StateTestSubject.state_machine
@options = { :crazy_custom_key => 'key', :machine => @machine }
end
def new_state(options={})
- ActiveModel::StateMachine::State.new(@name, @options.merge(options))
+ ActiveModel::StateMachine::State.new(@state_name, @options.merge(options))
end
test 'sets the name' do
@@ -43,32 +43,30 @@ class StateTest < ActiveModel::TestCase
assert_equal new_state, new_state
end
- uses_mocha 'state actions' do
- test 'should send a message to the record for an action if the action is present as a symbol' do
- state = new_state(:entering => :foo)
+ test 'should send a message to the record for an action if the action is present as a symbol' do
+ state = new_state(:entering => :foo)
- record = stub
- record.expects(:foo)
+ record = stub
+ record.expects(:foo)
- state.call_action(:entering, record)
- end
+ state.call_action(:entering, record)
+ end
- test 'should send a message to the record for an action if the action is present as a string' do
- state = new_state(:entering => 'foo')
+ test 'should send a message to the record for an action if the action is present as a string' do
+ state = new_state(:entering => 'foo')
- record = stub
- record.expects(:foo)
+ record = stub
+ record.expects(:foo)
- state.call_action(:entering, record)
- end
+ state.call_action(:entering, record)
+ end
- test 'should call a proc, passing in the record for an action if the action is present' do
- state = new_state(:entering => Proc.new {|r| r.foobar})
+ test 'should call a proc, passing in the record for an action if the action is present' do
+ state = new_state(:entering => Proc.new {|r| r.foobar})
- record = stub
- record.expects(:foobar)
-
- state.call_action(:entering, record)
- end
+ record = stub
+ record.expects(:foobar)
+
+ state.call_action(:entering, record)
end
-end \ No newline at end of file
+end
diff --git a/activemodel/test/state_machine/state_transition_test.rb b/activemodel/test/state_machine/state_transition_test.rb
index 9a9e7f60c5..b59ff5a6a7 100644
--- a/activemodel/test/state_machine/state_transition_test.rb
+++ b/activemodel/test/state_machine/state_transition_test.rb
@@ -1,4 +1,4 @@
-require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
+require 'test_helper'
class StateTransitionTest < ActiveModel::TestCase
test 'should set from, to, and opts attr readers' do
@@ -10,39 +10,37 @@ class StateTransitionTest < ActiveModel::TestCase
assert_equal opts, st.options
end
- uses_mocha 'checking ActiveModel StateMachine transitions' do
- test 'should pass equality check if from and to are the same' do
- opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
- st = ActiveModel::StateMachine::StateTransition.new(opts)
+ test 'should pass equality check if from and to are the same' do
+ opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
+ st = ActiveModel::StateMachine::StateTransition.new(opts)
- obj = stub
- obj.stubs(:from).returns(opts[:from])
- obj.stubs(:to).returns(opts[:to])
+ obj = stub
+ obj.stubs(:from).returns(opts[:from])
+ obj.stubs(:to).returns(opts[:to])
- assert_equal st, obj
- end
+ assert_equal st, obj
+ end
- test 'should fail equality check if from are not the same' do
- opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
- st = ActiveModel::StateMachine::StateTransition.new(opts)
+ test 'should fail equality check if from are not the same' do
+ opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
+ st = ActiveModel::StateMachine::StateTransition.new(opts)
- obj = stub
- obj.stubs(:from).returns('blah')
- obj.stubs(:to).returns(opts[:to])
+ obj = stub
+ obj.stubs(:from).returns('blah')
+ obj.stubs(:to).returns(opts[:to])
- assert_not_equal st, obj
- end
-
- test 'should fail equality check if to are not the same' do
- opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
- st = ActiveModel::StateMachine::StateTransition.new(opts)
+ assert_not_equal st, obj
+ end
+
+ test 'should fail equality check if to are not the same' do
+ opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
+ st = ActiveModel::StateMachine::StateTransition.new(opts)
- obj = stub
- obj.stubs(:from).returns(opts[:from])
- obj.stubs(:to).returns('blah')
+ obj = stub
+ obj.stubs(:from).returns(opts[:from])
+ obj.stubs(:to).returns('blah')
- assert_not_equal st, obj
- end
+ assert_not_equal st, obj
end
end
@@ -54,35 +52,33 @@ class StateTransitionGuardCheckTest < ActiveModel::TestCase
assert st.perform(nil)
end
- uses_mocha 'checking ActiveModel StateMachine transition guard checks' do
- test 'should call the method on the object if guard is a symbol' do
- opts = {:from => 'foo', :to => 'bar', :guard => :test_guard}
- st = ActiveModel::StateMachine::StateTransition.new(opts)
-
- obj = stub
- obj.expects(:test_guard)
-
- st.perform(obj)
- end
-
- test 'should call the method on the object if guard is a string' do
- opts = {:from => 'foo', :to => 'bar', :guard => 'test_guard'}
- st = ActiveModel::StateMachine::StateTransition.new(opts)
-
- obj = stub
- obj.expects(:test_guard)
-
- st.perform(obj)
- end
-
- test 'should call the proc passing the object if the guard is a proc' do
- opts = {:from => 'foo', :to => 'bar', :guard => Proc.new {|o| o.test_guard}}
- st = ActiveModel::StateMachine::StateTransition.new(opts)
+ test 'should call the method on the object if guard is a symbol' do
+ opts = {:from => 'foo', :to => 'bar', :guard => :test_guard}
+ st = ActiveModel::StateMachine::StateTransition.new(opts)
+
+ obj = stub
+ obj.expects(:test_guard)
- obj = stub
- obj.expects(:test_guard)
+ st.perform(obj)
+ end
+
+ test 'should call the method on the object if guard is a string' do
+ opts = {:from => 'foo', :to => 'bar', :guard => 'test_guard'}
+ st = ActiveModel::StateMachine::StateTransition.new(opts)
+
+ obj = stub
+ obj.expects(:test_guard)
- st.perform(obj)
- end
+ st.perform(obj)
+ end
+
+ test 'should call the proc passing the object if the guard is a proc' do
+ opts = {:from => 'foo', :to => 'bar', :guard => Proc.new {|o| o.test_guard}}
+ st = ActiveModel::StateMachine::StateTransition.new(opts)
+
+ obj = stub
+ obj.expects(:test_guard)
+
+ st.perform(obj)
end
end
diff --git a/activemodel/test/state_machine_test.rb b/activemodel/test/state_machine_test.rb
index b2f0fc4ec0..312d8728ba 100644
--- a/activemodel/test/state_machine_test.rb
+++ b/activemodel/test/state_machine_test.rb
@@ -1,4 +1,4 @@
-require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper'))
+require 'test_helper'
class StateMachineSubject
include ActiveModel::StateMachine
@@ -122,24 +122,22 @@ class StateMachineEventFiringWithPersistenceTest < ActiveModel::TestCase
assert_equal :closed, @subj.current_state
end
- uses_mocha "StateMachineEventFiringWithPersistenceTest with callbacks" do
- test 'fires the Event' do
- @subj.class.state_machine.events[:close].expects(:fire).with(@subj)
- @subj.close!
- end
-
- test 'calls the success callback if one was provided' do
- @subj.expects(:success_callback)
- @subj.close!
- end
+ test 'fires the Event' do
+ @subj.class.state_machine.events[:close].expects(:fire).with(@subj)
+ @subj.close!
+ end
- test 'attempts to persist if write_state is defined' do
- def @subj.write_state
- end
+ test 'calls the success callback if one was provided' do
+ @subj.expects(:success_callback)
+ @subj.close!
+ end
- @subj.expects(:write_state)
- @subj.close!
+ test 'attempts to persist if write_state is defined' do
+ def @subj.write_state
end
+
+ @subj.expects(:write_state)
+ @subj.close!
end
end
@@ -151,98 +149,90 @@ class StateMachineEventFiringWithoutPersistence < ActiveModel::TestCase
assert_equal :closed, subj.current_state
end
- uses_mocha 'StateMachineEventFiringWithoutPersistence' do
- test 'fires the Event' do
- subj = StateMachineSubject.new
+ test 'fires the Event' do
+ subj = StateMachineSubject.new
- StateMachineSubject.state_machine.events[:close].expects(:fire).with(subj)
- subj.close
- end
+ StateMachineSubject.state_machine.events[:close].expects(:fire).with(subj)
+ subj.close
+ end
- test 'attempts to persist if write_state is defined' do
- subj = StateMachineSubject.new
+ test 'attempts to persist if write_state is defined' do
+ subj = StateMachineSubject.new
- def subj.write_state
- end
+ def subj.write_state
+ end
- subj.expects(:write_state_without_persistence)
+ subj.expects(:write_state_without_persistence)
- subj.close
- end
+ subj.close
end
end
-uses_mocha 'StateMachinePersistenceTest' do
- class StateMachinePersistenceTest < ActiveModel::TestCase
- test 'reads the state if it has not been set and read_state is defined' do
- subj = StateMachineSubject.new
- def subj.read_state
- end
+class StateMachinePersistenceTest < ActiveModel::TestCase
+ test 'reads the state if it has not been set and read_state is defined' do
+ subj = StateMachineSubject.new
+ def subj.read_state
+ end
- subj.expects(:read_state).with(StateMachineSubject.state_machine)
+ subj.expects(:read_state).with(StateMachineSubject.state_machine)
- subj.current_state
- end
+ subj.current_state
end
end
-uses_mocha 'StateMachineEventCallbacksTest' do
- class StateMachineEventCallbacksTest < ActiveModel::TestCase
- test 'should call aasm_event_fired if defined and successful for bang fire' do
- subj = StateMachineSubject.new
- def subj.aasm_event_fired(from, to)
- end
-
- subj.expects(:event_fired)
-
- subj.close!
+class StateMachineEventCallbacksTest < ActiveModel::TestCase
+ test 'should call aasm_event_fired if defined and successful for bang fire' do
+ subj = StateMachineSubject.new
+ def subj.aasm_event_fired(from, to)
end
- test 'should call aasm_event_fired if defined and successful for non-bang fire' do
- subj = StateMachineSubject.new
- def subj.aasm_event_fired(from, to)
- end
+ subj.expects(:event_fired)
- subj.expects(:event_fired)
+ subj.close!
+ end
- subj.close
+ test 'should call aasm_event_fired if defined and successful for non-bang fire' do
+ subj = StateMachineSubject.new
+ def subj.aasm_event_fired(from, to)
end
- test 'should call aasm_event_failed if defined and transition failed for bang fire' do
- subj = StateMachineSubject.new
- def subj.event_failed(event)
- end
+ subj.expects(:event_fired)
- subj.expects(:event_failed)
+ subj.close
+ end
- subj.null!
+ test 'should call aasm_event_failed if defined and transition failed for bang fire' do
+ subj = StateMachineSubject.new
+ def subj.event_failed(event)
end
- test 'should call aasm_event_failed if defined and transition failed for non-bang fire' do
- subj = StateMachineSubject.new
- def subj.aasm_event_failed(event)
- end
+ subj.expects(:event_failed)
- subj.expects(:event_failed)
+ subj.null!
+ end
- subj.null
+ test 'should call aasm_event_failed if defined and transition failed for non-bang fire' do
+ subj = StateMachineSubject.new
+ def subj.aasm_event_failed(event)
end
+
+ subj.expects(:event_failed)
+
+ subj.null
end
end
-uses_mocha 'StateMachineStateActionsTest' do
- class StateMachineStateActionsTest < ActiveModel::TestCase
- test "calls enter when entering state" do
- subj = StateMachineSubject.new
- subj.expects(:enter)
- subj.close
- end
+class StateMachineStateActionsTest < ActiveModel::TestCase
+ test "calls enter when entering state" do
+ subj = StateMachineSubject.new
+ subj.expects(:enter)
+ subj.close
+ end
- test "calls exit when exiting state" do
- subj = StateMachineSubject.new
- subj.expects(:exit)
- subj.close
- end
+ test "calls exit when exiting state" do
+ subj = StateMachineSubject.new
+ subj.expects(:exit)
+ subj.close
end
end
@@ -306,19 +296,17 @@ class StateMachineWithComplexTransitionsTest < ActiveModel::TestCase
assert_equal :working, @subj.current_state(:chetan_patil)
end
- uses_mocha "StateMachineWithComplexTransitionsTest on_transition tests" do
- test 'calls on_transition method with args' do
- @subj.wakeup! :showering
-
- @subj.expects(:wear_clothes).with('blue', 'jeans')
- @subj.dress! :working, 'blue', 'jeans'
- end
-
- test 'calls on_transition proc' do
- @subj.wakeup! :showering
-
- @subj.expects(:wear_clothes).with('purple', 'slacks')
- @subj.dress!(:dating, 'purple', 'slacks')
- end
+ test 'calls on_transition method with args' do
+ @subj.wakeup! :showering
+
+ @subj.expects(:wear_clothes).with('blue', 'jeans')
+ @subj.dress! :working, 'blue', 'jeans'
+ end
+
+ test 'calls on_transition proc' do
+ @subj.wakeup! :showering
+
+ @subj.expects(:wear_clothes).with('purple', 'slacks')
+ @subj.dress!(:dating, 'purple', 'slacks')
end
-end \ No newline at end of file
+end
diff --git a/activemodel/test/test_helper.rb b/activemodel/test/test_helper.rb
index ccf93280ec..5b5678e42d 100644
--- a/activemodel/test/test_helper.rb
+++ b/activemodel/test/test_helper.rb
@@ -1,39 +1,21 @@
-$:.unshift "#{File.dirname(__FILE__)}/../lib"
-$:.unshift File.dirname(__FILE__)
-
+require 'rubygems'
require 'test/unit'
+
+gem 'mocha', '>= 0.9.3'
+require 'mocha'
+
require 'active_model'
require 'active_model/state_machine'
-require 'active_support/callbacks' # needed by ActiveModel::TestCase
-require 'active_support/test_case'
-def uses_gem(gem_name, test_name, version = '> 0')
- require 'rubygems'
- gem gem_name.to_s, version
- require gem_name.to_s
- yield
-rescue LoadError
- $stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
-end
+$:.unshift File.dirname(__FILE__) + "/../../activesupport/lib"
+require 'active_support'
+require 'active_support/test_case'
-# Wrap tests that use Mocha and skip if unavailable.
-unless defined? uses_mocha
- def uses_mocha(test_name, &block)
- uses_gem('mocha', test_name, '>= 0.5.5', &block)
- end
+class ActiveModel::TestCase < ActiveSupport::TestCase
end
begin
- require 'rubygems'
require 'ruby-debug'
Debugger.start
rescue LoadError
end
-
-ActiveSupport::TestCase.send :include, ActiveSupport::Testing::Default
-
-module ActiveModel
- class TestCase < ActiveSupport::TestCase
- include ActiveSupport::Testing::Default
- end
-end \ No newline at end of file
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index 4ca062b535..cca70f1fb7 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -1,4 +1,22 @@
-*2.2.1 [RC2 or 2.2 final]*
+*2.3.0/3.0*
+
+* Add :having as a key to find and the relevant associations. [miloops]
+
+* Added default_scope to Base #1381 [Paweł Kondzior]. Example:
+
+ class Person < ActiveRecord::Base
+ default_scope :order => 'last_name, first_name'
+ end
+
+ class Company < ActiveRecord::Base
+ has_many :people
+ end
+
+ Person.all # => Person.find(:all, :order => 'last_name, first_name')
+ Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 })
+
+
+*2.2.1 [RC2] (November 14th, 2008)*
* Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster]
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
index f192646547..f47674d5b7 100644
--- a/activerecord/Rakefile
+++ b/activerecord/Rakefile
@@ -171,7 +171,7 @@ spec = Gem::Specification.new do |s|
s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
end
- s.add_dependency('activesupport', '= 2.2.0' + PKG_BUILD)
+ s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
s.files.delete FIXTURES_ROOT + "/fixture_database.sqlite"
s.files.delete FIXTURES_ROOT + "/fixture_database_2.sqlite"
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index 219cd30f94..348e5b94af 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -31,51 +31,47 @@ rescue LoadError
end
end
-require 'active_record/base'
-require 'active_record/named_scope'
-require 'active_record/observer'
-require 'active_record/query_cache'
-require 'active_record/validations'
-require 'active_record/callbacks'
-require 'active_record/reflection'
-require 'active_record/associations'
-require 'active_record/association_preload'
-require 'active_record/aggregations'
-require 'active_record/transactions'
-require 'active_record/timestamp'
-require 'active_record/locking/optimistic'
-require 'active_record/locking/pessimistic'
-require 'active_record/migration'
-require 'active_record/schema'
-require 'active_record/calculations'
-require 'active_record/serialization'
-require 'active_record/attribute_methods'
-require 'active_record/dirty'
-require 'active_record/dynamic_finder_match'
+module ActiveRecord
+ # TODO: Review explicit loads to see if they will automatically be handled by the initilizer.
+ def self.load_all!
+ [Base, DynamicFinderMatch, ConnectionAdapters::AbstractAdapter]
+ end
-ActiveRecord::Base.class_eval do
- extend ActiveRecord::QueryCache
- include ActiveRecord::Validations
- include ActiveRecord::Locking::Optimistic
- include ActiveRecord::Locking::Pessimistic
- include ActiveRecord::AttributeMethods
- include ActiveRecord::Dirty
- include ActiveRecord::Callbacks
- include ActiveRecord::Observing
- include ActiveRecord::Timestamp
- include ActiveRecord::Associations
- include ActiveRecord::NamedScope
- include ActiveRecord::AssociationPreload
- include ActiveRecord::Aggregations
- include ActiveRecord::Transactions
- include ActiveRecord::Reflection
- include ActiveRecord::Calculations
- include ActiveRecord::Serialization
-end
+ 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 :Base, 'active_record/base'
+ autoload :Calculations, 'active_record/calculations'
+ autoload :Callbacks, 'active_record/callbacks'
+ autoload :Dirty, 'active_record/dirty'
+ autoload :DynamicFinderMatch, 'active_record/dynamic_finder_match'
+ autoload :Migration, 'active_record/migration'
+ autoload :Migrator, 'active_record/migration'
+ autoload :NamedScope, 'active_record/named_scope'
+ autoload :Observing, '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 :TestCase, 'active_record/test_case'
+ autoload :Timestamp, 'active_record/timestamp'
+ autoload :Transactions, 'active_record/transactions'
+ autoload :Validations, 'active_record/validations'
-require 'active_record/connection_adapters/abstract_adapter'
+ module Locking
+ autoload :Optimistic, 'active_record/locking/optimistic'
+ autoload :Pessimistic, 'active_record/locking/pessimistic'
+ end
-require 'active_record/schema_dumper'
+ module ConnectionAdapters
+ autoload :AbstractAdapter, 'active_record/connection_adapters/abstract_adapter'
+ end
+end
require 'active_record/i18n_interpolation_deprecation'
-I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en-US.yml'
+I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb
index 6e194ab9b4..99c3ce5e62 100644
--- a/activerecord/lib/active_record/association_preload.rb
+++ b/activerecord/lib/active_record/association_preload.rb
@@ -185,7 +185,7 @@ module ActiveRecord
associated_records = reflection.klass.find(:all, :conditions => [conditions, ids],
:include => options[:include],
- :joins => "INNER JOIN #{connection.quote_table_name options[:join_table]} as t0 ON #{reflection.klass.quoted_table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}",
+ :joins => "INNER JOIN #{connection.quote_table_name options[:join_table]} t0 ON #{reflection.klass.quoted_table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}",
:select => "#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as the_parent_record_id",
:order => options[:order])
@@ -312,7 +312,7 @@ module ActiveRecord
table_name = klass.quoted_table_name
primary_key = klass.primary_key
column_type = klass.columns.detect{|c| c.name == primary_key}.type
- ids = id_map.keys.uniq.map do |id|
+ ids = id_map.keys.map do |id|
if column_type == :integer
id.to_i
elsif column_type == :float
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index c7cb6eb966..3fbbea43ed 100755
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -1,13 +1,3 @@
-require 'active_record/associations/association_proxy'
-require 'active_record/associations/association_collection'
-require 'active_record/associations/belongs_to_association'
-require 'active_record/associations/belongs_to_polymorphic_association'
-require 'active_record/associations/has_one_association'
-require 'active_record/associations/has_many_association'
-require 'active_record/associations/has_many_through_association'
-require 'active_record/associations/has_and_belongs_to_many_association'
-require 'active_record/associations/has_one_through_association'
-
module ActiveRecord
class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection)
@@ -75,6 +65,18 @@ module ActiveRecord
# See ActiveRecord::Associations::ClassMethods for documentation.
module Associations # :nodoc:
+ # These classes will be loaded when associatoins are created.
+ # So there is no need to eager load them.
+ autoload :AssociationCollection, 'active_record/associations/association_collection'
+ autoload :AssociationProxy, 'active_record/associations/association_proxy'
+ autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
+ autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
+ autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
+ autoload :HasManyAssociation, 'active_record/associations/has_many_association'
+ autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
+ autoload :HasOneAssociation, 'active_record/associations/has_one_association'
+ autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
+
def self.included(base)
base.extend(ClassMethods)
end
@@ -722,6 +724,8 @@ module ActiveRecord
# Specify second-order associations that should be eager loaded when the collection is loaded.
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
+ # [:having]
+ # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
@@ -1179,6 +1183,8 @@ module ActiveRecord
# Specify second-order associations that should be eager loaded when the collection is loaded.
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
+ # [:having]
+ # Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
@@ -1551,7 +1557,7 @@ module ActiveRecord
@@valid_keys_for_has_many_association = [
:class_name, :table_name, :foreign_key, :primary_key,
:dependent,
- :select, :conditions, :include, :order, :group, :limit, :offset,
+ :select, :conditions, :include, :order, :group, :having, :limit, :offset,
:as, :through, :source, :source_type,
:uniq,
:finder_sql, :counter_sql,
@@ -1607,9 +1613,9 @@ module ActiveRecord
mattr_accessor :valid_keys_for_has_and_belongs_to_many_association
@@valid_keys_for_has_and_belongs_to_many_association = [
:class_name, :table_name, :join_table, :foreign_key, :association_foreign_key,
- :select, :conditions, :include, :order, :group, :limit, :offset,
+ :select, :conditions, :include, :order, :group, :having, :limit, :offset,
:uniq,
- :finder_sql, :delete_sql, :insert_sql,
+ :finder_sql, :counter_sql, :delete_sql, :insert_sql,
:before_add, :after_add, :before_remove, :after_remove,
:extend, :readonly,
:validate
@@ -1656,7 +1662,7 @@ module ActiveRecord
add_conditions!(sql, options[:conditions], scope)
add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
- add_group!(sql, options[:group], scope)
+ add_group!(sql, options[:group], options[:having], scope)
add_order!(sql, options[:order], scope)
add_limit!(sql, options, scope) if using_limitable_reflections?(join_dependency.reflections)
add_lock!(sql, options, scope)
@@ -1712,7 +1718,7 @@ module ActiveRecord
end
add_conditions!(sql, options[:conditions], scope)
- add_group!(sql, options[:group], scope)
+ add_group!(sql, options[:group], options[:having], scope)
if order && is_distinct
connection.add_order_by_for_association_limiting!(sql, :order => order)
@@ -1731,6 +1737,7 @@ module ActiveRecord
case cond
when nil then all
when Array then all << cond.first
+ when Hash then all << cond.keys
else all << cond
end
end
diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb
index d1a79df6e6..75ec4fbb2e 100644
--- a/activerecord/lib/active_record/associations/association_proxy.rb
+++ b/activerecord/lib/active_record/associations/association_proxy.rb
@@ -188,6 +188,7 @@ module ActiveRecord
def merge_options_from_reflection!(options)
options.reverse_merge!(
:group => @reflection.options[:group],
+ :having => @reflection.options[:having],
:limit => @reflection.options[:limit],
:offset => @reflection.options[:offset],
:joins => @reflection.options[:joins],
diff --git a/activerecord/lib/active_record/associations/has_one_through_association.rb b/activerecord/lib/active_record/associations/has_one_through_association.rb
index b78bd5d931..8073ebaf9f 100644
--- a/activerecord/lib/active_record/associations/has_one_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_through_association.rb
@@ -8,11 +8,10 @@ module ActiveRecord
current_object = @owner.send(@reflection.through_reflection.name)
if current_object
- klass.destroy(current_object)
- @owner.clear_association_cache
+ current_object.update_attributes(construct_join_attributes(new_value))
+ else
+ @owner.send(@reflection.through_reflection.name, klass.send(:create, construct_join_attributes(new_value)))
end
-
- @owner.send(@reflection.through_reflection.name, klass.send(:create, construct_join_attributes(new_value)))
end
private
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index a36a137f0d..8f8ed241d5 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -495,6 +495,10 @@ module ActiveRecord #:nodoc:
superclass_delegating_accessor :store_full_sti_class
self.store_full_sti_class = false
+ # Stores the default scope for the class
+ class_inheritable_accessor :default_scoping, :instance_writer => false
+ self.default_scoping = []
+
class << self # Class methods
# Find operates with four different retrieval approaches:
#
@@ -517,6 +521,7 @@ module ActiveRecord #:nodoc:
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>[ "user_name = ?", username ]</tt>, or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
+ # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
# * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4.
# * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
@@ -1612,15 +1617,23 @@ module ActiveRecord #:nodoc:
end
end
+ def default_select(qualified)
+ if qualified
+ quoted_table_name + '.*'
+ else
+ '*'
+ end
+ end
+
def construct_finder_sql(options)
scope = scope(:find)
- sql = "SELECT #{options[:select] || (scope && scope[:select]) || ((options[:joins] || (scope && scope[:joins])) && quoted_table_name + '.*') || '*'} "
+ sql = "SELECT #{options[:select] || (scope && scope[:select]) || default_select(options[:joins] || (scope && scope[:joins]))} "
sql << "FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} "
add_joins!(sql, options[:joins], scope)
add_conditions!(sql, options[:conditions], scope)
- add_group!(sql, options[:group], scope)
+ add_group!(sql, options[:group], options[:having], scope)
add_order!(sql, options[:order], scope)
add_limit!(sql, options, scope)
add_lock!(sql, options, scope)
@@ -1676,13 +1689,15 @@ module ActiveRecord #:nodoc:
end
end
- def add_group!(sql, group, scope = :auto)
+ def add_group!(sql, group, having, scope = :auto)
if group
sql << " GROUP BY #{group}"
+ sql << " HAVING #{having}" if having
else
scope = scope(:find) if :auto == scope
if scope && (scoped_group = scope[:group])
sql << " GROUP BY #{scoped_group}"
+ sql << " HAVING #{scoped_having}" if (scoped_having = scope[:having])
end
end
end
@@ -2008,6 +2023,16 @@ module ActiveRecord #:nodoc:
@@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
end
+ # Sets the default options for the model. The format of the
+ # <tt>method_scoping</tt> argument is the same as in with_scope.
+ #
+ # class Person < ActiveRecord::Base
+ # default_scope :find => { :order => 'last_name, first_name' }
+ # end
+ def default_scope(options = {})
+ self.default_scoping << { :find => options, :create => (options.is_a?(Hash) && options.has_key?(:conditions)) ? options[:conditions] : {} }
+ end
+
# Test whether the given method and optional key are scoped.
def scoped?(method, key = nil) #:nodoc:
if current_scoped_methods && (scope = current_scoped_methods[method])
@@ -2023,8 +2048,7 @@ module ActiveRecord #:nodoc:
end
def scoped_methods #:nodoc:
- scoped_methods = (Thread.current[:scoped_methods] ||= {})
- scoped_methods[self] ||= []
+ Thread.current[:"#{self}_scoped_methods"] ||= self.default_scoping.dup
end
def current_scoped_methods #:nodoc:
@@ -2238,7 +2262,7 @@ module ActiveRecord #:nodoc:
end
VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset,
- :order, :select, :readonly, :group, :from, :lock ]
+ :order, :select, :readonly, :group, :having, :from, :lock ]
def validate_find_options(options) #:nodoc:
options.assert_valid_keys(VALID_FIND_OPTIONS)
@@ -2301,7 +2325,7 @@ module ActiveRecord #:nodoc:
# construct an URI with the user object's 'id' in it:
#
# user = User.find_by_name('Phusion')
- # user_path(path) # => "/users/1"
+ # user_path(user) # => "/users/1"
#
# You can override +to_param+ in your model to make +users_path+ construct
# an URI using the user's name instead of the user's id:
@@ -2313,7 +2337,7 @@ module ActiveRecord #:nodoc:
# end
#
# user = User.find_by_name('Phusion')
- # user_path(path) # => "/users/Phusion"
+ # user_path(user) # => "/users/Phusion"
def to_param
# We can't use alias_method here, because method 'id' optimizes itself on the fly.
(id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes
@@ -2957,4 +2981,18 @@ module ActiveRecord #:nodoc:
value
end
end
+
+ Base.class_eval do
+ extend QueryCache
+ include Validations
+ include Locking::Optimistic, Locking::Pessimistic
+ include AttributeMethods
+ include Dirty
+ include Callbacks, Observing, Timestamp
+ include Associations, AssociationPreload, NamedScope
+ include Aggregations, Transactions, Reflection, Calculations, Serialization
+ end
end
+
+# TODO: Remove this and make it work with LAZY flag
+require 'active_record/connection_adapters/abstract_adapter'
diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb
index 5e33cf1bd4..65512d534a 100644
--- a/activerecord/lib/active_record/calculations.rb
+++ b/activerecord/lib/active_record/calculations.rb
@@ -286,7 +286,7 @@ module ActiveRecord
case operation
when 'count' then value.to_i
when 'sum' then type_cast_using_column(value || '0', column)
- when 'avg' then value && value.to_d
+ when 'avg' then value && (value.is_a?(Fixnum) ? value.to_f : value).to_d
else type_cast_using_column(value, column)
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index 432c341e6c..901b17124c 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -65,15 +65,23 @@ module ActiveRecord
# The default ConnectionPool maximum size is 5.
def initialize(spec)
@spec = spec
+
# The cache of reserved connections mapped to threads
@reserved_connections = {}
+
# The mutex used to synchronize pool access
@connection_mutex = Monitor.new
@queue = @connection_mutex.new_cond
- # default 5 second timeout
- @timeout = spec.config[:wait_timeout] || 5
+
+ # default 5 second timeout unless on ruby 1.9
+ @timeout =
+ if RUBY_VERSION < '1.9'
+ spec.config[:wait_timeout] || 5
+ end
+
# default max pool size to 5
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
+
@connections = []
@checked_out = []
end
@@ -187,7 +195,7 @@ module ActiveRecord
# try looting dead threads
clear_stale_cached_connections!
if @size == @checked_out.size
- raise ConnectionTimeoutError, "could not obtain a database connection within #{@timeout} seconds. The pool size is currently #{@size}, perhaps you need to increase it?"
+ raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it."
end
end
end
@@ -292,10 +300,7 @@ module ActiveRecord
# and also returns connections to the pool cached by threads that are no
# longer alive.
def clear_active_connections!
- @connection_pools.each_value do |pool|
- pool.release_connection
- pool.clear_stale_cached_connections!
- end
+ @connection_pools.each_value {|pool| pool.release_connection }
end
# Clears the cache which maps classes
@@ -324,7 +329,8 @@ module ActiveRecord
# Returns true if a connection that's accessible to this class has
# already been opened.
def connected?(klass)
- retrieve_connection_pool(klass).connected?
+ conn = retrieve_connection_pool(klass)
+ conn ? conn.connected? : false
end
# Remove the connection for this class. This will close the active
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 a9a63e5a9f..cecbc6b3ac 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -31,13 +31,13 @@ module ActiveRecord
# Returns an array of arrays containing the field values.
# Order is the same as that returned by +columns+.
def select_rows(sql, name = nil)
- raise NotImplementedError, "select_rows is an abstract method"
end
+ undef_method :select_rows
# Executes the SQL statement in the context of this connection.
- def execute(sql, name = nil)
- raise NotImplementedError, "execute is an abstract method"
+ def execute(sql, name = nil, skip_logging = false)
end
+ undef_method :execute
# Returns the last auto-generated ID from the affected table.
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
@@ -246,8 +246,8 @@ module ActiveRecord
# Returns an array of record hashes with the column names as keys and
# column values as values.
def select(sql, name = nil)
- raise NotImplementedError, "select is an abstract method"
end
+ undef_method :select
# Returns the last auto-generated ID from the affected table.
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 81260eeecc..b26185580c 100755
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -3,6 +3,7 @@ require 'date'
require 'bigdecimal'
require 'bigdecimal/util'
+# TODO: Autoload these files
require 'active_record/connection_adapters/abstract/schema_definitions'
require 'active_record/connection_adapters/abstract/schema_statements'
require 'active_record/connection_adapters/abstract/database_statements'
@@ -31,7 +32,7 @@ module ActiveRecord
include QueryCache
include ActiveSupport::Callbacks
define_callbacks :checkout, :checkin
- checkout :reset!
+
@@row_even = true
def initialize(connection, logger = nil) #:nodoc:
@@ -131,9 +132,8 @@ module ActiveRecord
end
# Returns true if its safe to reload the connection between requests for development mode.
- # This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
def requires_reloading?
- false
+ true
end
# Checks whether the connection to the database is still active (i.e. not stale).
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 3d8b0e40a9..039d5a4e8e 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -1,6 +1,7 @@
require 'erb'
require 'yaml'
require 'csv'
+require 'active_support/dependencies'
require 'active_support/test_case'
if RUBY_VERSION < '1.9'
@@ -813,188 +814,192 @@ class Fixture #:nodoc:
end
end
-module Test #:nodoc:
- module Unit #:nodoc:
- class TestCase #:nodoc:
- setup :setup_fixtures
- teardown :teardown_fixtures
-
- superclass_delegating_accessor :fixture_path
- superclass_delegating_accessor :fixture_table_names
- superclass_delegating_accessor :fixture_class_names
- superclass_delegating_accessor :use_transactional_fixtures
- superclass_delegating_accessor :use_instantiated_fixtures # true, false, or :no_instances
- superclass_delegating_accessor :pre_loaded_fixtures
-
- self.fixture_table_names = []
- self.use_transactional_fixtures = false
- self.use_instantiated_fixtures = true
- self.pre_loaded_fixtures = false
-
- @@already_loaded_fixtures = {}
- self.fixture_class_names = {}
-
- class << self
- def set_fixture_class(class_names = {})
- self.fixture_class_names = self.fixture_class_names.merge(class_names)
- end
+module ActiveRecord
+ module TestFixtures
+ def self.included(base)
+ base.class_eval do
+ setup :setup_fixtures
+ teardown :teardown_fixtures
+
+ superclass_delegating_accessor :fixture_path
+ superclass_delegating_accessor :fixture_table_names
+ superclass_delegating_accessor :fixture_class_names
+ superclass_delegating_accessor :use_transactional_fixtures
+ superclass_delegating_accessor :use_instantiated_fixtures # true, false, or :no_instances
+ superclass_delegating_accessor :pre_loaded_fixtures
+
+ self.fixture_table_names = []
+ self.use_transactional_fixtures = false
+ self.use_instantiated_fixtures = true
+ self.pre_loaded_fixtures = false
+
+ self.fixture_class_names = {}
+ end
- def fixtures(*table_names)
- if table_names.first == :all
- table_names = Dir["#{fixture_path}/*.yml"] + Dir["#{fixture_path}/*.csv"]
- table_names.map! { |f| File.basename(f).split('.')[0..-2].join('.') }
- else
- table_names = table_names.flatten.map { |n| n.to_s }
- end
+ base.extend ClassMethods
+ end
+
+ module ClassMethods
+ def set_fixture_class(class_names = {})
+ self.fixture_class_names = self.fixture_class_names.merge(class_names)
+ end
- self.fixture_table_names |= table_names
- require_fixture_classes(table_names)
- setup_fixture_accessors(table_names)
+ def fixtures(*table_names)
+ if table_names.first == :all
+ table_names = Dir["#{fixture_path}/*.yml"] + Dir["#{fixture_path}/*.csv"]
+ table_names.map! { |f| File.basename(f).split('.')[0..-2].join('.') }
+ else
+ table_names = table_names.flatten.map { |n| n.to_s }
end
- def try_to_load_dependency(file_name)
- require_dependency file_name
- rescue LoadError => e
- # Let's hope the developer has included it himself
+ self.fixture_table_names |= table_names
+ require_fixture_classes(table_names)
+ setup_fixture_accessors(table_names)
+ end
+
+ def try_to_load_dependency(file_name)
+ require_dependency file_name
+ rescue LoadError => e
+ # Let's hope the developer has included it himself
- # Let's warn in case this is a subdependency, otherwise
- # subdependency error messages are totally cryptic
- if ActiveRecord::Base.logger
- ActiveRecord::Base.logger.warn("Unable to load #{file_name}, underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}")
- end
+ # Let's warn in case this is a subdependency, otherwise
+ # subdependency error messages are totally cryptic
+ if ActiveRecord::Base.logger
+ ActiveRecord::Base.logger.warn("Unable to load #{file_name}, underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}")
end
+ end
- def require_fixture_classes(table_names = nil)
- (table_names || fixture_table_names).each do |table_name|
- file_name = table_name.to_s
- file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names
- try_to_load_dependency(file_name)
- end
+ def require_fixture_classes(table_names = nil)
+ (table_names || fixture_table_names).each do |table_name|
+ file_name = table_name.to_s
+ file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names
+ try_to_load_dependency(file_name)
end
+ end
- def setup_fixture_accessors(table_names = nil)
- table_names = [table_names] if table_names && !table_names.respond_to?(:each)
- (table_names || fixture_table_names).each do |table_name|
- table_name = table_name.to_s.tr('.', '_')
+ def setup_fixture_accessors(table_names = nil)
+ table_names = [table_names] if table_names && !table_names.respond_to?(:each)
+ (table_names || fixture_table_names).each do |table_name|
+ table_name = table_name.to_s.tr('.', '_')
- define_method(table_name) do |*fixtures|
- force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload
+ define_method(table_name) do |*fixtures|
+ force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload
- @fixture_cache[table_name] ||= {}
+ @fixture_cache[table_name] ||= {}
- instances = fixtures.map do |fixture|
- @fixture_cache[table_name].delete(fixture) if force_reload
+ instances = fixtures.map do |fixture|
+ @fixture_cache[table_name].delete(fixture) if force_reload
- if @loaded_fixtures[table_name][fixture.to_s]
- @fixture_cache[table_name][fixture] ||= @loaded_fixtures[table_name][fixture.to_s].find
- else
- raise StandardError, "No fixture with name '#{fixture}' found for table '#{table_name}'"
- end
+ if @loaded_fixtures[table_name][fixture.to_s]
+ @fixture_cache[table_name][fixture] ||= @loaded_fixtures[table_name][fixture.to_s].find
+ else
+ raise StandardError, "No fixture with name '#{fixture}' found for table '#{table_name}'"
end
-
- instances.size == 1 ? instances.first : instances
end
- end
- end
- def uses_transaction(*methods)
- @uses_transaction = [] unless defined?(@uses_transaction)
- @uses_transaction.concat methods.map(&:to_s)
+ instances.size == 1 ? instances.first : instances
+ end
end
+ end
- def uses_transaction?(method)
- @uses_transaction = [] unless defined?(@uses_transaction)
- @uses_transaction.include?(method.to_s)
- end
+ def uses_transaction(*methods)
+ @uses_transaction = [] unless defined?(@uses_transaction)
+ @uses_transaction.concat methods.map(&:to_s)
end
- def use_transactional_fixtures?
- use_transactional_fixtures &&
- !self.class.uses_transaction?(method_name)
+ def uses_transaction?(method)
+ @uses_transaction = [] unless defined?(@uses_transaction)
+ @uses_transaction.include?(method.to_s)
end
+ end
- def setup_fixtures
- return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
+ def run_in_transaction?
+ use_transactional_fixtures &&
+ !self.class.uses_transaction?(method_name)
+ end
- if pre_loaded_fixtures && !use_transactional_fixtures
- raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
- end
+ def setup_fixtures
+ return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
- @fixture_cache = {}
+ if pre_loaded_fixtures && !use_transactional_fixtures
+ raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
+ end
- # Load fixtures once and begin transaction.
- if use_transactional_fixtures?
- if @@already_loaded_fixtures[self.class]
- @loaded_fixtures = @@already_loaded_fixtures[self.class]
- else
- load_fixtures
- @@already_loaded_fixtures[self.class] = @loaded_fixtures
- end
- ActiveRecord::Base.connection.increment_open_transactions
- ActiveRecord::Base.connection.begin_db_transaction
- ActiveRecord::Base.connection.transactional_fixtures = true
- # Load fixtures for every test.
+ @fixture_cache = {}
+ @@already_loaded_fixtures ||= {}
+
+ # Load fixtures once and begin transaction.
+ if run_in_transaction?
+ if @@already_loaded_fixtures[self.class]
+ @loaded_fixtures = @@already_loaded_fixtures[self.class]
else
- Fixtures.reset_cache
- @@already_loaded_fixtures[self.class] = nil
load_fixtures
+ @@already_loaded_fixtures[self.class] = @loaded_fixtures
end
-
- # Instantiate fixtures for every test if requested.
- instantiate_fixtures if use_instantiated_fixtures
+ ActiveRecord::Base.connection.increment_open_transactions
+ ActiveRecord::Base.connection.begin_db_transaction
+ ActiveRecord::Base.connection.transactional_fixtures = true
+ # Load fixtures for every test.
+ else
+ Fixtures.reset_cache
+ @@already_loaded_fixtures[self.class] = nil
+ load_fixtures
end
- def teardown_fixtures
- return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
+ # Instantiate fixtures for every test if requested.
+ instantiate_fixtures if use_instantiated_fixtures
+ end
+
+ def teardown_fixtures
+ return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
- unless use_transactional_fixtures?
- Fixtures.reset_cache
- end
+ unless run_in_transaction?
+ Fixtures.reset_cache
+ end
- # Rollback changes if a transaction is active.
- if use_transactional_fixtures? && ActiveRecord::Base.connection.open_transactions != 0
- ActiveRecord::Base.connection.rollback_db_transaction
- ActiveRecord::Base.connection.decrement_open_transactions
- ActiveRecord::Base.connection.transactional_fixtures = false
- end
- ActiveRecord::Base.clear_active_connections!
+ # Rollback changes if a transaction is active.
+ if run_in_transaction? && ActiveRecord::Base.connection.open_transactions != 0
+ ActiveRecord::Base.connection.rollback_db_transaction
+ ActiveRecord::Base.connection.decrement_open_transactions
+ ActiveRecord::Base.connection.transactional_fixtures = false
end
+ ActiveRecord::Base.clear_active_connections!
+ end
- private
- def load_fixtures
- @loaded_fixtures = {}
- fixtures = Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
- unless fixtures.nil?
- if fixtures.instance_of?(Fixtures)
- @loaded_fixtures[fixtures.name] = fixtures
- else
- fixtures.each { |f| @loaded_fixtures[f.name] = f }
- end
+ private
+ def load_fixtures
+ @loaded_fixtures = {}
+ fixtures = Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
+ unless fixtures.nil?
+ if fixtures.instance_of?(Fixtures)
+ @loaded_fixtures[fixtures.name] = fixtures
+ else
+ fixtures.each { |f| @loaded_fixtures[f.name] = f }
end
end
+ end
- # for pre_loaded_fixtures, only require the classes once. huge speed improvement
- @@required_fixture_classes = false
+ # for pre_loaded_fixtures, only require the classes once. huge speed improvement
+ @@required_fixture_classes = false
- def instantiate_fixtures
- if pre_loaded_fixtures
- raise RuntimeError, 'Load fixtures before instantiating them.' if Fixtures.all_loaded_fixtures.empty?
- unless @@required_fixture_classes
- self.class.require_fixture_classes Fixtures.all_loaded_fixtures.keys
- @@required_fixture_classes = true
- end
- Fixtures.instantiate_all_loaded_fixtures(self, load_instances?)
- else
- raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
- @loaded_fixtures.each do |table_name, fixtures|
- Fixtures.instantiate_fixtures(self, table_name, fixtures, load_instances?)
- end
+ def instantiate_fixtures
+ if pre_loaded_fixtures
+ raise RuntimeError, 'Load fixtures before instantiating them.' if Fixtures.all_loaded_fixtures.empty?
+ unless @@required_fixture_classes
+ self.class.require_fixture_classes Fixtures.all_loaded_fixtures.keys
+ @@required_fixture_classes = true
+ end
+ Fixtures.instantiate_all_loaded_fixtures(self, load_instances?)
+ else
+ raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
+ @loaded_fixtures.each do |table_name, fixtures|
+ Fixtures.instantiate_fixtures(self, table_name, fixtures, load_instances?)
end
end
+ end
- def load_instances?
- use_instantiated_fixtures != :no_instances
- end
- end
+ def load_instances?
+ use_instantiated_fixtures != :no_instances
+ end
end
end
diff --git a/activerecord/lib/active_record/locale/en-US.yml b/activerecord/lib/active_record/locale/en.yml
index 421f0ebd60..7e205435f7 100644
--- a/activerecord/lib/active_record/locale/en-US.yml
+++ b/activerecord/lib/active_record/locale/en.yml
@@ -1,4 +1,4 @@
-en-US:
+en:
activerecord:
errors:
# The values :model, :attribute and :value are always available for interpolation
diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb
index 332cda1e16..870b4b2dd4 100644
--- a/activerecord/lib/active_record/serialization.rb
+++ b/activerecord/lib/active_record/serialization.rb
@@ -1,3 +1,5 @@
+require 'active_support/json'
+
module ActiveRecord #:nodoc:
module Serialization
class Serializer #:nodoc:
@@ -95,4 +97,4 @@ module ActiveRecord #:nodoc:
end
require 'active_record/serializers/xml_serializer'
-require 'active_record/serializers/json_serializer' \ No newline at end of file
+require 'active_record/serializers/json_serializer'
diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb
index eabf06fc3b..149b93203e 100644
--- a/activerecord/lib/active_record/test_case.rb
+++ b/activerecord/lib/active_record/test_case.rb
@@ -1,21 +1,11 @@
require "active_support/test_case"
-module ActiveRecord
+module ActiveRecord
class TestCase < ActiveSupport::TestCase #:nodoc:
- self.fixture_path = FIXTURES_ROOT
- self.use_instantiated_fixtures = false
- self.use_transactional_fixtures = true
-
- def create_fixtures(*table_names, &block)
- Fixtures.create_fixtures(FIXTURES_ROOT, table_names, {}, &block)
- end
-
def assert_date_from_db(expected, actual, message = nil)
- # SQL Server doesn't have a separate column type just for dates,
+ # SybaseAdapter doesn't have a separate column type just for dates,
# so the time is in the string and incorrectly formatted
- if current_adapter?(:SQLServerAdapter)
- assert_equal expected.strftime("%Y/%m/%d 00:00:00"), actual.strftime("%Y/%m/%d 00:00:00")
- elsif current_adapter?(:SybaseAdapter)
+ if current_adapter?(:SybaseAdapter)
assert_equal expected.to_s, actual.to_date.to_s, message
else
assert_equal expected.to_s, actual.to_s, message
diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb
index 2479b75789..6ac4bdc905 100644
--- a/activerecord/lib/active_record/version.rb
+++ b/activerecord/lib/active_record/version.rb
@@ -1,7 +1,7 @@
module ActiveRecord
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 2
+ MINOR = 3
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
diff --git a/activerecord/test/cases/adapter_test_sqlserver.rb b/activerecord/test/cases/adapter_test_sqlserver.rb
deleted file mode 100644
index ea270fb7ee..0000000000
--- a/activerecord/test/cases/adapter_test_sqlserver.rb
+++ /dev/null
@@ -1,95 +0,0 @@
-require "cases/helper"
-require 'models/default'
-require 'models/post'
-require 'models/task'
-
-class SqlServerAdapterTest < ActiveRecord::TestCase
- class TableWithRealColumn < ActiveRecord::Base; end
-
- fixtures :posts, :tasks
-
- def setup
- @connection = ActiveRecord::Base.connection
- end
-
- def teardown
- @connection.execute("SET LANGUAGE us_english") rescue nil
- end
-
- def test_real_column_has_float_type
- assert_equal :float, TableWithRealColumn.columns_hash["real_number"].type
- end
-
- # SQL Server 2000 has a bug where some unambiguous date formats are not
- # correctly identified if the session language is set to german
- def test_date_insertion_when_language_is_german
- @connection.execute("SET LANGUAGE deutsch")
-
- assert_nothing_raised do
- Task.create(:starting => Time.utc(2000, 1, 31, 5, 42, 0), :ending => Date.new(2006, 12, 31))
- end
- end
-
- def test_indexes_with_descending_order
- # Make sure we have an index with descending order
- @connection.execute "CREATE INDEX idx_credit_limit ON accounts (credit_limit DESC)" rescue nil
- assert_equal ["credit_limit"], @connection.indexes('accounts').first.columns
- ensure
- @connection.execute "DROP INDEX accounts.idx_credit_limit"
- end
-
- def test_execute_without_block_closes_statement
- assert_all_statements_used_are_closed do
- @connection.execute("SELECT 1")
- end
- end
-
- def test_execute_with_block_closes_statement
- assert_all_statements_used_are_closed do
- @connection.execute("SELECT 1") do |sth|
- assert !sth.finished?, "Statement should still be alive within block"
- end
- end
- end
-
- def test_insert_with_identity_closes_statement
- assert_all_statements_used_are_closed do
- @connection.insert("INSERT INTO accounts ([id], [firm_id],[credit_limit]) values (999, 1, 50)")
- end
- end
-
- def test_insert_without_identity_closes_statement
- assert_all_statements_used_are_closed do
- @connection.insert("INSERT INTO accounts ([firm_id],[credit_limit]) values (1, 50)")
- end
- end
-
- def test_active_closes_statement
- assert_all_statements_used_are_closed do
- @connection.active?
- end
- end
-
- def assert_all_statements_used_are_closed(&block)
- existing_handles = []
- ObjectSpace.each_object(DBI::StatementHandle) {|handle| existing_handles << handle}
- GC.disable
-
- yield
-
- used_handles = []
- ObjectSpace.each_object(DBI::StatementHandle) {|handle| used_handles << handle unless existing_handles.include? handle}
-
- assert_block "No statements were used within given block" do
- used_handles.size > 0
- end
-
- ObjectSpace.each_object(DBI::StatementHandle) do |handle|
- assert_block "Statement should have been closed within given block" do
- handle.finished?
- end
- end
- ensure
- GC.enable
- end
-end
diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb
index 431dc7a141..4c1589d965 100644
--- a/activerecord/test/cases/ar_schema_test.rb
+++ b/activerecord/test/cases/ar_schema_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_record/schema'
if ActiveRecord::Base.connection.supports_migrations?
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 5f43975d5a..3c8408d14b 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -385,12 +385,28 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_equal count, posts.size
end
- def test_eager_with_has_many_and_limit_ond_high_offset
+ def test_eager_with_has_many_and_limit_and_high_offset
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ])
assert_equal 0, posts.size
end
- def test_count_eager_with_has_many_and_limit_ond_high_offset
+ def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions
+ assert_queries(1) do
+ posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10,
+ :conditions => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ])
+ assert_equal 0, posts.size
+ end
+ end
+
+ def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditions
+ assert_queries(1) do
+ posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10,
+ :conditions => { 'authors.name' => 'David', 'comments.body' => 'go crazy' })
+ assert_equal 0, posts.size
+ end
+ end
+
+ def test_count_eager_with_has_many_and_limit_and_high_offset
posts = Post.count(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ])
assert_equal 0, posts
end
@@ -667,7 +683,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_count_with_include
- if current_adapter?(:SQLServerAdapter, :SybaseAdapter)
+ if current_adapter?(:SybaseAdapter)
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15")
elsif current_adapter?(:OpenBaseAdapter)
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15")
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 2949f1d304..2f08e09d43 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -68,6 +68,16 @@ class DeveloperWithSymbolsForKeys < ActiveRecord::Base
:foreign_key => "developer_id"
end
+class DeveloperWithCounterSQL < ActiveRecord::Base
+ set_table_name 'developers'
+ has_and_belongs_to_many :projects,
+ :class_name => "DeveloperWithCounterSQL",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id",
+ :foreign_key => "developer_id",
+ :counter_sql => 'SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}'
+end
+
class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects,
:parrots, :pirates, :treasures, :price_estimates, :tags, :taggings
@@ -648,6 +658,11 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal 1, categories(:technology).posts_gruoped_by_title.size
end
+ def test_find_scoped_grouped_having
+ assert_equal 2, projects(:active_record).well_payed_salary_groups.size
+ assert projects(:active_record).well_payed_salary_groups.all? { |g| g.salary > 10000 }
+ end
+
def test_get_ids
assert_equal projects(:active_record, :action_controller).map(&:id).sort, developers(:david).project_ids.sort
assert_equal [projects(:active_record).id], developers(:jamis).project_ids
@@ -739,6 +754,19 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised { david.projects.count(:all, :conditions => '1=1') }
end
+ def test_count
+ david = Developer.find(1)
+ assert_equal 2, david.projects.count
+ end
+
+ def test_count_with_counter_sql
+ developer = DeveloperWithCounterSQL.create(:name => 'tekin')
+ developer.project_ids = [projects(:active_record).id]
+ developer.save
+ developer.reload
+ assert_equal 1, developer.projects.count
+ end
+
uses_mocha 'mocking Post.transaction' do
def test_association_proxy_transaction_method_starts_transaction_in_association_class
Post.expects(:transaction)
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 59784e1bcb..816ceb6855 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -255,6 +255,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 2, companies(:first_firm).clients_grouped_by_name.length
end
+ def test_find_scoped_grouped_having
+ assert_equal 1, authors(:david).popular_grouped_posts.length
+ assert_equal 0, authors(:mary).popular_grouped_posts.length
+ end
+
def test_adding
force_signal37_to_load_all_clients_of_firm
natural = Client.new("name" => "Natural Company")
diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb
index ff4021fe02..7d418de965 100644
--- a/activerecord/test/cases/associations/has_one_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -3,9 +3,11 @@ require 'models/club'
require 'models/member'
require 'models/membership'
require 'models/sponsor'
+require 'models/organization'
+require 'models/member_detail'
class HasOneThroughAssociationsTest < ActiveRecord::TestCase
- fixtures :members, :clubs, :memberships, :sponsors
+ fixtures :members, :clubs, :memberships, :sponsors, :organizations
def setup
@member = members(:groucho)
@@ -120,4 +122,40 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
clubs(:moustache_club).send(:private_method)
@member.club.send(:private_method)
end
+
+ def test_assigning_to_has_one_through_preserves_decorated_join_record
+ @organization = organizations(:nsa)
+ assert_difference 'MemberDetail.count', 1 do
+ @member_detail = MemberDetail.new(:extra_data => 'Extra')
+ @member.member_detail = @member_detail
+ @member.organization = @organization
+ end
+ assert_equal @organization, @member.organization
+ assert @organization.members.include?(@member)
+ assert_equal 'Extra', @member.member_detail.extra_data
+ end
+
+ def test_reassigning_has_one_through
+ @organization = organizations(:nsa)
+ @new_organization = organizations(:discordians)
+
+ assert_difference 'MemberDetail.count', 1 do
+ @member_detail = MemberDetail.new(:extra_data => 'Extra')
+ @member.member_detail = @member_detail
+ @member.organization = @organization
+ end
+ assert_equal @organization, @member.organization
+ assert_equal 'Extra', @member.member_detail.extra_data
+ assert @organization.members.include?(@member)
+ assert !@new_organization.members.include?(@member)
+
+ assert_no_difference 'MemberDetail.count' do
+ @member.organization = @new_organization
+ end
+ assert_equal @new_organization, @member.organization
+ assert_equal 'Extra', @member.member_detail.extra_data
+ assert !@organization.members.include?(@member)
+ assert @new_organization.members.include?(@member)
+ end
+
end
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index da9f2742d8..5f54931d00 100755
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -428,9 +428,6 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_preserving_date_objects
- # SQL Server doesn't have a separate column type just for dates, so all are returned as time
- return true if current_adapter?(:SQLServerAdapter)
-
if current_adapter?(:SybaseAdapter, :OracleAdapter)
# Sybase ctlib does not (yet?) support the date type; use datetime instead.
# Oracle treats all dates/times as Time.
@@ -777,8 +774,8 @@ class BasicsTest < ActiveRecord::TestCase
end
end
- # Oracle, SQLServer, and Sybase do not have a TIME datatype.
- unless current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
+ # Oracle, and Sybase do not have a TIME datatype.
+ unless current_adapter?(:OracleAdapter, :SybaseAdapter)
def test_utc_as_time_zone
Topic.default_timezone = :utc
attributes = { "bonus_time" => "5:42:00AM" }
@@ -1157,8 +1154,8 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_attributes_on_dummy_time
- # Oracle, SQL Server, and Sybase do not have a TIME datatype.
- return true if current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
+ # Oracle, and Sybase do not have a TIME datatype.
+ return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
attributes = {
"bonus_time" => "5:42:00AM"
@@ -1874,7 +1871,7 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "integer", xml.elements["//parent-id"].attributes['type']
assert_equal "true", xml.elements["//parent-id"].attributes['nil']
- if current_adapter?(:SybaseAdapter, :SQLServerAdapter, :OracleAdapter)
+ if current_adapter?(:SybaseAdapter, :OracleAdapter)
assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text
assert_equal "datetime" , xml.elements["//last-read"].attributes['type']
else
diff --git a/activerecord/test/cases/binary_test.rb b/activerecord/test/cases/binary_test.rb
index 7131532c05..8545ba97cc 100644
--- a/activerecord/test/cases/binary_test.rb
+++ b/activerecord/test/cases/binary_test.rb
@@ -1,13 +1,9 @@
require "cases/helper"
# Without using prepared statements, it makes no sense to test
-# BLOB data with SQL Server, because the length of a statement is
-# limited to 8KB.
-#
-# Without using prepared statements, it makes no sense to test
# BLOB data with DB2 or Firebird, because the length of a statement
# is limited to 32KB.
-unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :DB2Adapter, :FirebirdAdapter)
+unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter)
require 'models/binary'
class BinaryTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 0fa61500c0..8bd0dd0f6e 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -25,6 +25,11 @@ class CalculationsTest < ActiveRecord::TestCase
def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
+
+ def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
+ assert_equal 0, NumericData.send(:type_cast_calculated_value, 0, nil, 'avg')
+ assert_equal 53.0, NumericData.send(:type_cast_calculated_value, 53, nil, 'avg')
+ end
def test_should_get_maximum_of_field
assert_equal 60, Account.maximum(:credit_limit)
diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb
index 875b7f8dbc..b4032c23e6 100644
--- a/activerecord/test/cases/defaults_test.rb
+++ b/activerecord/test/cases/defaults_test.rb
@@ -18,12 +18,7 @@ class DefaultTest < ActiveRecord::TestCase
end
end
- if current_adapter?(:MysqlAdapter)
-
-
- end
-
- if current_adapter?(:PostgreSQLAdapter, :SQLServerAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter)
+ if current_adapter?(:PostgreSQLAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter)
def test_default_integers
default = Default.new
assert_instance_of Fixnum, default.positive_integer
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 153880afbd..d4d770b04e 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -175,6 +175,13 @@ class FinderTest < ActiveRecord::TestCase
assert_equal 4, developers.map(&:salary).uniq.size
end
+ def test_find_with_group_and_having
+ developers = Developer.find(:all, :group => "salary", :having => "sum(salary) > 10000", :select => "salary")
+ assert_equal 3, developers.size
+ assert_equal 3, developers.map(&:salary).uniq.size
+ assert developers.all? { |developer| developer.salary > 10000 }
+ end
+
def test_find_with_entire_select_statement
topics = Topic.find_by_sql "SELECT * FROM topics WHERE author_name = 'Mary'"
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index 6ba7597f56..ed2915b023 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -641,15 +641,15 @@ end
class FixtureLoadingTest < ActiveRecord::TestCase
uses_mocha 'reloading_fixtures_through_accessor_methods' do
def test_logs_message_for_failed_dependency_load
- Test::Unit::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError)
+ ActiveRecord::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError)
ActiveRecord::Base.logger.expects(:warn)
- Test::Unit::TestCase.try_to_load_dependency(:does_not_exist)
+ ActiveRecord::TestCase.try_to_load_dependency(:does_not_exist)
end
def test_does_not_logs_message_for_successful_dependency_load
- Test::Unit::TestCase.expects(:require_dependency).with(:works_out_fine)
+ ActiveRecord::TestCase.expects(:require_dependency).with(:works_out_fine)
ActiveRecord::Base.logger.expects(:warn).never
- Test::Unit::TestCase.try_to_load_dependency(:works_out_fine)
+ ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine)
end
end
end
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index 0c03d29dec..c18ecf6f8f 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -5,8 +5,8 @@ require 'config'
require 'test/unit'
require 'active_record'
-require 'active_record/fixtures'
require 'active_record/test_case'
+require 'active_record/fixtures'
require 'connection'
# Show backtraces for deprecated behavior for quicker cleanup.
@@ -48,15 +48,22 @@ class << ActiveRecord::Base
end
unless ENV['FIXTURE_DEBUG']
- module Test #:nodoc:
- module Unit #:nodoc:
- class << TestCase #:nodoc:
- def try_to_load_dependency_with_silence(*args)
- ActiveRecord::Base.logger.silence { try_to_load_dependency_without_silence(*args)}
- end
-
- alias_method_chain :try_to_load_dependency, :silence
- end
+ module ActiveRecord::TestFixtures::ClassMethods
+ def try_to_load_dependency_with_silence(*args)
+ ActiveRecord::Base.logger.silence { try_to_load_dependency_without_silence(*args)}
end
+
+ alias_method_chain :try_to_load_dependency, :silence
+ end
+end
+
+class ActiveSupport::TestCase
+ include ActiveRecord::TestFixtures
+ self.fixture_path = FIXTURES_ROOT
+ self.use_instantiated_fixtures = false
+ self.use_transactional_fixtures = true
+
+ def create_fixtures(*table_names, &block)
+ Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/cases/i18n_test.rb b/activerecord/test/cases/i18n_test.rb
index ea06e377e3..b1db662eca 100644
--- a/activerecord/test/cases/i18n_test.rb
+++ b/activerecord/test/cases/i18n_test.rb
@@ -9,32 +9,32 @@ class ActiveRecordI18nTests < Test::Unit::TestCase
end
def test_translated_model_attributes
- I18n.backend.store_translations 'en-US', :activerecord => {:attributes => {:topic => {:title => 'topic title attribute'} } }
+ I18n.backend.store_translations 'en', :activerecord => {:attributes => {:topic => {:title => 'topic title attribute'} } }
assert_equal 'topic title attribute', Topic.human_attribute_name('title')
end
def test_translated_model_attributes_with_sti
- I18n.backend.store_translations 'en-US', :activerecord => {:attributes => {:reply => {:title => 'reply title attribute'} } }
+ I18n.backend.store_translations 'en', :activerecord => {:attributes => {:reply => {:title => 'reply title attribute'} } }
assert_equal 'reply title attribute', Reply.human_attribute_name('title')
end
def test_translated_model_attributes_with_sti_fallback
- I18n.backend.store_translations 'en-US', :activerecord => {:attributes => {:topic => {:title => 'topic title attribute'} } }
+ I18n.backend.store_translations 'en', :activerecord => {:attributes => {:topic => {:title => 'topic title attribute'} } }
assert_equal 'topic title attribute', Reply.human_attribute_name('title')
end
def test_translated_model_names
- I18n.backend.store_translations 'en-US', :activerecord => {:models => {:topic => 'topic model'} }
+ I18n.backend.store_translations 'en', :activerecord => {:models => {:topic => 'topic model'} }
assert_equal 'topic model', Topic.human_name
end
def test_translated_model_names_with_sti
- I18n.backend.store_translations 'en-US', :activerecord => {:models => {:reply => 'reply model'} }
+ I18n.backend.store_translations 'en', :activerecord => {:models => {:reply => 'reply model'} }
assert_equal 'reply model', Reply.human_name
end
def test_translated_model_names_with_sti_fallback
- I18n.backend.store_translations 'en-US', :activerecord => {:models => {:topic => 'topic model'} }
+ I18n.backend.store_translations 'en', :activerecord => {:models => {:topic => 'topic model'} }
assert_equal 'topic model', Reply.human_name
end
end
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index a39415618d..3f59eb9706 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -59,13 +59,13 @@ class InheritanceTest < ActiveRecord::TestCase
def test_a_bad_type_column
#SQLServer need to turn Identity Insert On before manually inserting into the Identity column
- if current_adapter?(:SQLServerAdapter, :SybaseAdapter)
+ if current_adapter?(:SybaseAdapter)
Company.connection.execute "SET IDENTITY_INSERT companies ON"
end
Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')"
#We then need to turn it back Off before continuing.
- if current_adapter?(:SQLServerAdapter, :SybaseAdapter)
+ if current_adapter?(:SybaseAdapter)
Company.connection.execute "SET IDENTITY_INSERT companies OFF"
end
assert_raises(ActiveRecord::SubclassNotFound) { Company.find(100) }
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 0a14b1d906..077cac7747 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -200,9 +200,9 @@ end
# blocks, so separate script called by Kernel#system is needed.
# (See exec vs. async_exec in the PostgreSQL adapter.)
-# TODO: The SQL Server, Sybase, and OpenBase adapters currently have no support for pessimistic locking
+# TODO: The Sybase, and OpenBase adapters currently have no support for pessimistic locking
-unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :OpenBaseAdapter)
+unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
class PessimisticLockingTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
fixtures :people, :readers
diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb
index ff10bfaf3e..6372b4f6aa 100644
--- a/activerecord/test/cases/method_scoping_test.rb
+++ b/activerecord/test/cases/method_scoping_test.rb
@@ -522,6 +522,73 @@ class HasAndBelongsToManyScopingTest< ActiveRecord::TestCase
end
+class DefaultScopingTest < ActiveRecord::TestCase
+ fixtures :developers
+
+ def test_default_scope
+ expected = Developer.find(:all, :order => 'salary DESC').collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
+ assert_equal expected, received
+ end
+
+ def test_default_scoping_with_threads
+ scope = [{ :create => {}, :find => { :order => 'salary DESC' } }]
+
+ 2.times do
+ Thread.new { assert_equal scope, DeveloperOrderedBySalary.send(:scoped_methods) }.join
+ end
+ end
+
+ def test_default_scoping_with_inheritance
+ scope = [{ :create => {}, :find => { :order => 'salary DESC' } }]
+
+ # Inherit a class having a default scope and define a new default scope
+ klass = Class.new(DeveloperOrderedBySalary)
+ klass.send :default_scope, {}
+
+ # Scopes added on children should append to parent scope
+ expected_klass_scope = [{ :create => {}, :find => { :order => 'salary DESC' }}, { :create => {}, :find => {} }]
+ assert_equal expected_klass_scope, klass.send(:scoped_methods)
+
+ # Parent should still have the original scope
+ assert_equal scope, DeveloperOrderedBySalary.send(:scoped_methods)
+ end
+
+ def test_method_scope
+ expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.all_ordered_by_name.collect { |dev| dev.salary }
+ assert_equal expected, received
+ end
+
+ def test_nested_scope
+ expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.with_scope(:find => { :order => 'name DESC'}) do
+ DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
+ end
+ assert_equal expected, received
+ end
+
+ def test_named_scope
+ expected = Developer.find(:all, :order => 'name DESC').collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.by_name.find(:all).collect { |dev| dev.salary }
+ assert_equal expected, received
+ end
+
+ def test_nested_exclusive_scope
+ expected = Developer.find(:all, :limit => 100).collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.with_exclusive_scope(:find => { :limit => 100 }) do
+ DeveloperOrderedBySalary.find(:all).collect { |dev| dev.salary }
+ end
+ assert_equal expected, received
+ end
+
+ def test_overwriting_default_scope
+ expected = Developer.find(:all, :order => 'salary').collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.find(:all, :order => 'salary').collect { |dev| dev.salary }
+ assert_equal expected, received
+ end
+end
+
=begin
# We disabled the scoping for has_one and belongs_to as we can't think of a proper use case
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index ac44dd7ffe..2ec3d40332 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -271,9 +271,9 @@ if ActiveRecord::Base.connection.supports_migrations?
Person.connection.drop_table table_name rescue nil
end
- # SQL Server, Sybase, and SQLite3 will not allow you to add a NOT NULL
+ # Sybase, and SQLite3 will not allow you to add a NOT NULL
# column to a table without a default value.
- unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :SQLiteAdapter)
+ unless current_adapter?(:SybaseAdapter, :SQLiteAdapter)
def test_add_column_not_null_without_default
Person.connection.create_table :testings do |t|
t.column :foo, :string
@@ -410,7 +410,7 @@ if ActiveRecord::Base.connection.supports_migrations?
assert_equal Fixnum, bob.age.class
assert_equal Time, bob.birthday.class
- if current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
+ if current_adapter?(:OracleAdapter, :SybaseAdapter)
# Sybase, and Oracle don't differentiate between date/time
assert_equal Time, bob.favorite_day.class
else
@@ -851,10 +851,6 @@ if ActiveRecord::Base.connection.supports_migrations?
# - SQLite3 stores a float, in violation of SQL
assert_kind_of BigDecimal, b.value_of_e
assert_equal BigDecimal("2.71828182845905"), b.value_of_e
- elsif current_adapter?(:SQLServer)
- # - SQL Server rounds instead of truncating
- assert_kind_of Fixnum, b.value_of_e
- assert_equal 3, b.value_of_e
else
# - SQL standard is an integer
assert_kind_of Fixnum, b.value_of_e
diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb
index 078ca1d679..2649a9358a 100644
--- a/activerecord/test/cases/pooled_connections_test.rb
+++ b/activerecord/test/cases/pooled_connections_test.rb
@@ -28,10 +28,13 @@ class PooledConnectionsTest < ActiveRecord::TestCase
end
end
- def test_pooled_connection_checkout
- checkout_connections
- assert_equal @connections.length, 2
- assert_equal @timed_out, 2
+ # Will deadlock due to lack of Monitor timeouts in 1.9
+ if RUBY_VERSION < '1.9'
+ def test_pooled_connection_checkout
+ checkout_connections
+ assert_equal @connections.length, 2
+ assert_equal @timed_out, 2
+ end
end
def checkout_checkin_connections(pool_size, threads)
@@ -73,6 +76,19 @@ class PooledConnectionsTest < ActiveRecord::TestCase
assert ActiveRecord::ConnectionAdapters::AbstractAdapter === conn
conn_pool.checkin(conn)
end
+
+ def test_not_connected_defined_connection_returns_false
+ ActiveRecord::Base.establish_connection(@connection)
+ assert ! ActiveRecord::Base.connected?
+ end
+
+ def test_undefined_connection_returns_false
+ old_handler = ActiveRecord::Base.connection_handler
+ ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
+ assert_equal false, ActiveRecord::Base.connected?
+ ensure
+ ActiveRecord::Base.connection_handler = old_handler
+ end
end unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name
class AllowConcurrencyDeprecatedTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index ee7e285a73..17e4c755ce 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_record/schema_dumper'
require 'stringio'
diff --git a/activerecord/test/cases/table_name_test_sqlserver.rb b/activerecord/test/cases/table_name_test_sqlserver.rb
deleted file mode 100644
index fbf38a130e..0000000000
--- a/activerecord/test/cases/table_name_test_sqlserver.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-require "cases/helper"
-require 'active_record/schema'
-
-if ActiveRecord::Base.connection.supports_migrations?
- class Order < ActiveRecord::Base
- self.table_name = '[order]'
- end
-
- class TableNameTest < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
-
- # Ensures Model.columns works when using SQLServer escape characters.
- # Enables legacy schemas using SQL reserved words as table names.
- # Should work with table names with spaces as well ('table name').
- def test_escaped_table_name
- assert_nothing_raised do
- ActiveRecord::Base.connection.select_all 'SELECT * FROM [order]'
- end
- assert_equal '[order]', Order.table_name
- assert_equal 5, Order.columns.length
- end
- end
-end
diff --git a/activerecord/test/cases/validations_i18n_test.rb b/activerecord/test/cases/validations_i18n_test.rb
index 42246f18b6..f59e3f7001 100644
--- a/activerecord/test/cases/validations_i18n_test.rb
+++ b/activerecord/test/cases/validations_i18n_test.rb
@@ -2,14 +2,14 @@ require "cases/helper"
require 'models/topic'
require 'models/reply'
-class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
+class ActiveRecordValidationsI18nTests < ActiveSupport::TestCase
def setup
reset_callbacks Topic
@topic = Topic.new
@old_load_path, @old_backend = I18n.load_path, I18n.backend
I18n.load_path.clear
I18n.backend = I18n::Backend::Simple.new
- I18n.backend.store_translations('en-US', :activerecord => {:errors => {:messages => {:custom => nil}}})
+ I18n.backend.store_translations('en', :activerecord => {:errors => {:messages => {:custom => nil}}})
end
def teardown
@@ -165,7 +165,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
@topic.errors.instance_variable_set :@errors, { 'title' => ['empty'] }
I18n.expects(:translate).with(:"topic.title", :default => ['Title'], :scope => [:activerecord, :attributes], :count => 1).returns('Title')
- @topic.errors.full_messages :locale => 'en-US'
+ @topic.errors.full_messages :locale => 'en'
end
end
@@ -429,8 +429,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_confirmation_of w/o mocha
def test_validates_confirmation_of_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:confirmation => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:confirmation => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:confirmation => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:confirmation => 'global message'}}}
Topic.validates_confirmation_of :title
@topic.title_confirmation = 'foo'
@@ -439,7 +439,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_confirmation_of_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:confirmation => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:confirmation => 'global message'}}}
Topic.validates_confirmation_of :title
@topic.title_confirmation = 'foo'
@@ -450,8 +450,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_acceptance_of w/o mocha
def test_validates_acceptance_of_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:accepted => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:accepted => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:accepted => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:accepted => 'global message'}}}
Topic.validates_acceptance_of :title, :allow_nil => false
@topic.valid?
@@ -459,7 +459,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_acceptance_of_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:accepted => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:accepted => 'global message'}}}
Topic.validates_acceptance_of :title, :allow_nil => false
@topic.valid?
@@ -469,8 +469,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_presence_of w/o mocha
def test_validates_presence_of_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:blank => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:blank => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:blank => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:blank => 'global message'}}}
Topic.validates_presence_of :title
@topic.valid?
@@ -478,7 +478,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_presence_of_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:blank => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:blank => 'global message'}}}
Topic.validates_presence_of :title
@topic.valid?
@@ -488,8 +488,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_length_of :within w/o mocha
def test_validates_length_of_within_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:too_short => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:too_short => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:too_short => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:too_short => 'global message'}}}
Topic.validates_length_of :title, :within => 3..5
@topic.valid?
@@ -497,7 +497,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_length_of_within_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:too_short => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:too_short => 'global message'}}}
Topic.validates_length_of :title, :within => 3..5
@topic.valid?
@@ -507,8 +507,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_length_of :is w/o mocha
def test_validates_length_of_within_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:wrong_length => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:wrong_length => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
Topic.validates_length_of :title, :is => 5
@topic.valid?
@@ -516,7 +516,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_length_of_within_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
Topic.validates_length_of :title, :is => 5
@topic.valid?
@@ -526,8 +526,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_uniqueness_of w/o mocha
def test_validates_length_of_within_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:wrong_length => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:wrong_length => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
Topic.validates_length_of :title, :is => 5
@topic.valid?
@@ -535,7 +535,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_length_of_within_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:wrong_length => 'global message'}}}
Topic.validates_length_of :title, :is => 5
@topic.valid?
@@ -546,8 +546,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_format_of w/o mocha
def test_validates_format_of_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:invalid => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:invalid => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/
@topic.valid?
@@ -555,7 +555,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_format_of_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
Topic.validates_format_of :title, :with => /^[1-9][0-9]*$/
@topic.valid?
@@ -565,8 +565,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_inclusion_of w/o mocha
def test_validates_inclusion_of_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:inclusion => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:inclusion => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:inclusion => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:inclusion => 'global message'}}}
Topic.validates_inclusion_of :title, :in => %w(a b c)
@topic.valid?
@@ -574,7 +574,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_inclusion_of_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:inclusion => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:inclusion => 'global message'}}}
Topic.validates_inclusion_of :title, :in => %w(a b c)
@topic.valid?
@@ -584,8 +584,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_exclusion_of w/o mocha
def test_validates_exclusion_of_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:exclusion => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:exclusion => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:exclusion => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:exclusion => 'global message'}}}
Topic.validates_exclusion_of :title, :in => %w(a b c)
@topic.title = 'a'
@@ -594,7 +594,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_exclusion_of_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:exclusion => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:exclusion => 'global message'}}}
Topic.validates_exclusion_of :title, :in => %w(a b c)
@topic.title = 'a'
@@ -605,8 +605,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_numericality_of without :only_integer w/o mocha
def test_validates_numericality_of_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:not_a_number => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:not_a_number => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
Topic.validates_numericality_of :title
@topic.title = 'a'
@@ -615,7 +615,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_numericality_of_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
Topic.validates_numericality_of :title, :only_integer => true
@topic.title = 'a'
@@ -626,8 +626,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_numericality_of with :only_integer w/o mocha
def test_validates_numericality_of_only_integer_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:not_a_number => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:not_a_number => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
Topic.validates_numericality_of :title, :only_integer => true
@topic.title = 'a'
@@ -636,7 +636,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_numericality_of_only_integer_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:not_a_number => 'global message'}}}
Topic.validates_numericality_of :title, :only_integer => true
@topic.title = 'a'
@@ -647,8 +647,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_numericality_of :odd w/o mocha
def test_validates_numericality_of_odd_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:odd => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:odd => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:odd => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:odd => 'global message'}}}
Topic.validates_numericality_of :title, :only_integer => true, :odd => true
@topic.title = 0
@@ -657,7 +657,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_numericality_of_odd_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:odd => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:odd => 'global message'}}}
Topic.validates_numericality_of :title, :only_integer => true, :odd => true
@topic.title = 0
@@ -668,8 +668,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_numericality_of :less_than w/o mocha
def test_validates_numericality_of_less_than_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:less_than => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:less_than => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:less_than => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:less_than => 'global message'}}}
Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0
@topic.title = 1
@@ -678,7 +678,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_numericality_of_less_than_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:less_than => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:less_than => 'global message'}}}
Topic.validates_numericality_of :title, :only_integer => true, :less_than => 0
@topic.title = 1
@@ -690,8 +690,8 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
# validates_associated w/o mocha
def test_validates_associated_finds_custom_model_key_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:replies => {:invalid => 'custom message'}}}}}}
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:replies => {:invalid => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
Topic.validates_associated :replies
replied_topic.valid?
@@ -699,7 +699,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_associated_finds_global_default_translation
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
Topic.validates_associated :replies
replied_topic.valid?
@@ -707,7 +707,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validations_with_message_symbol_must_translate
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:custom_error => "I am a custom error"}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:custom_error => "I am a custom error"}}}
Topic.validates_presence_of :title, :message => :custom_error
@topic.title = nil
@topic.valid?
@@ -715,7 +715,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_with_message_symbol_must_translate_per_attribute
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:custom_error => "I am a custom error"}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:custom_error => "I am a custom error"}}}}}}
Topic.validates_presence_of :title, :message => :custom_error
@topic.title = nil
@topic.valid?
@@ -723,7 +723,7 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase
end
def test_validates_with_message_symbol_must_translate_per_model
- I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:custom_error => "I am a custom error"}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:custom_error => "I am a custom error"}}}}
Topic.validates_presence_of :title, :message => :custom_error
@topic.title = nil
@topic.valid?
@@ -743,7 +743,7 @@ class ActiveRecordValidationsGenerateMessageI18nTests < Test::Unit::TestCase
def setup
reset_callbacks Topic
@topic = Topic.new
- I18n.backend.store_translations :'en-US', {
+ I18n.backend.store_translations :'en', {
:activerecord => {
:errors => {
:messages => {
diff --git a/activerecord/test/fixtures/organizations.yml b/activerecord/test/fixtures/organizations.yml
new file mode 100644
index 0000000000..25295bff87
--- /dev/null
+++ b/activerecord/test/fixtures/organizations.yml
@@ -0,0 +1,5 @@
+nsa:
+ name: No Such Agency
+discordians:
+ name: Discordians
+
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index e5b19ff9e4..4ffac4fe32 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -1,6 +1,7 @@
class Author < ActiveRecord::Base
has_many :posts
has_many :posts_with_comments, :include => :comments, :class_name => "Post"
+ has_many :popular_grouped_posts, :include => :comments, :class_name => "Post", :group => "type", :having => "SUM(comments_count) > 1", :select => "type"
has_many :posts_with_comments_sorted_by_comment_id, :include => :comments, :class_name => "Post", :order => 'comments.id'
has_many :posts_sorted_by_id_limited, :class_name => "Post", :order => 'posts.id', :limit => 1
has_many :posts_with_categories, :include => :categories, :class_name => "Post"
diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb
index 4e9d247a4e..5efce6aaa6 100644
--- a/activerecord/test/models/category.rb
+++ b/activerecord/test/models/category.rb
@@ -14,6 +14,7 @@ class Category < ActiveRecord::Base
:class_name => 'Post',
:conditions => { :title => 'Yet Another Testing Title' }
+ has_and_belongs_to_many :popular_grouped_posts, :class_name => "Post", :group => "posts.type", :having => "sum(comments.post_id) > 2", :include => :comments
has_and_belongs_to_many :posts_gruoped_by_title, :class_name => "Post", :group => "title", :select => "title"
def self.what_are_you
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
index c08476f728..92039a4f54 100644
--- a/activerecord/test/models/developer.rb
+++ b/activerecord/test/models/developer.rb
@@ -77,3 +77,15 @@ class DeveloperWithBeforeDestroyRaise < ActiveRecord::Base
raise if projects.empty?
end
end
+
+class DeveloperOrderedBySalary < ActiveRecord::Base
+ self.table_name = 'developers'
+ default_scope :order => 'salary DESC'
+ named_scope :by_name, :order => 'name DESC'
+
+ def self.all_ordered_by_name
+ with_scope(:find => { :order => 'name DESC' }) do
+ find(:all)
+ end
+ end
+end
diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb
index 688725f200..77a37abb38 100644
--- a/activerecord/test/models/member.rb
+++ b/activerecord/test/models/member.rb
@@ -6,4 +6,6 @@ class Member < ActiveRecord::Base
has_one :favourite_club, :through => :memberships, :conditions => ["memberships.favourite = ?", true], :source => :club
has_one :sponsor, :as => :sponsorable
has_one :sponsor_club, :through => :sponsor
+ has_one :member_detail
+ has_one :organization, :through => :member_detail
end \ No newline at end of file
diff --git a/activerecord/test/models/member_detail.rb b/activerecord/test/models/member_detail.rb
new file mode 100644
index 0000000000..e731454556
--- /dev/null
+++ b/activerecord/test/models/member_detail.rb
@@ -0,0 +1,4 @@
+class MemberDetail < ActiveRecord::Base
+ belongs_to :member
+ belongs_to :organization
+end
diff --git a/activerecord/test/models/organization.rb b/activerecord/test/models/organization.rb
new file mode 100644
index 0000000000..d79d5037c8
--- /dev/null
+++ b/activerecord/test/models/organization.rb
@@ -0,0 +1,4 @@
+class Organization < ActiveRecord::Base
+ has_many :member_details
+ has_many :members, :through => :member_details
+end \ No newline at end of file
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
index 44c692b5e7..550d4ae23c 100644
--- a/activerecord/test/models/project.rb
+++ b/activerecord/test/models/project.rb
@@ -13,6 +13,7 @@ class Project < ActiveRecord::Base
:after_add => Proc.new {|o, r| o.developers_log << "after_adding#{r.id || '<new>'}"},
:before_remove => Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"},
:after_remove => Proc.new {|o, r| o.developers_log << "after_removing#{r.id}"}
+ has_and_belongs_to_many :well_payed_salary_groups, :class_name => "Developer", :group => "salary", :having => "SUM(salary) > 10000", :select => "SUM(salary) as salary"
attr_accessor :developers_log
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index ab5c7c520b..6217e3bc1c 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -197,6 +197,12 @@ ActiveRecord::Schema.define do
t.string :name
end
+ create_table :member_details, :force => true do |t|
+ t.integer :member_id
+ t.integer :organization_id
+ t.string :extra_data
+ end
+
create_table :memberships, :force => true do |t|
t.datetime :joined_on
t.integer :club_id, :member_id
@@ -249,6 +255,10 @@ ActiveRecord::Schema.define do
t.integer :shipping_customer_id
end
+ create_table :organizations, :force => true do |t|
+ t.string :name
+ end
+
create_table :owners, :primary_key => :owner_id ,:force => true do |t|
t.string :name
end
diff --git a/activerecord/test/schema/sqlserver_specific_schema.rb b/activerecord/test/schema/sqlserver_specific_schema.rb
deleted file mode 100644
index cd8aca2fe5..0000000000
--- a/activerecord/test/schema/sqlserver_specific_schema.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-ActiveRecord::Schema.define do
- create_table :table_with_real_columns, :force => true do |t|
- t.column :real_number, :real
- end
-end \ No newline at end of file
diff --git a/activeresource/CHANGELOG b/activeresource/CHANGELOG
index 114a63c415..e05a634a12 100644
--- a/activeresource/CHANGELOG
+++ b/activeresource/CHANGELOG
@@ -1,4 +1,4 @@
-*2.2.1 [RC2 or 2.2 final]*
+*2.2.1 [RC2] (November 14th, 2008)*
* Fixed that ActiveResource#post would post an empty string when it shouldn't be posting anything #525 [Paolo Angelini]
diff --git a/activeresource/Rakefile b/activeresource/Rakefile
index ef6efd4903..ef99caea67 100644
--- a/activeresource/Rakefile
+++ b/activeresource/Rakefile
@@ -65,7 +65,7 @@ spec = Gem::Specification.new do |s|
s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
end
- s.add_dependency('activesupport', '= 2.2.0' + PKG_BUILD)
+ s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
s.require_path = 'lib'
s.autorequire = 'active_resource'
diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb
index bb284803d8..ad9ae6df1f 100644
--- a/activeresource/lib/active_resource/base.rb
+++ b/activeresource/lib/active_resource/base.rb
@@ -704,6 +704,7 @@ module ActiveResource
def new?
id.nil?
end
+ alias :new_record? :new?
# Gets the <tt>\id</tt> attribute of the resource.
def id
diff --git a/activeresource/lib/active_resource/version.rb b/activeresource/lib/active_resource/version.rb
index d56f4cf17e..c420ac813e 100644
--- a/activeresource/lib/active_resource/version.rb
+++ b/activeresource/lib/active_resource/version.rb
@@ -1,7 +1,7 @@
module ActiveResource
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 2
+ MINOR = 3
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
diff --git a/activeresource/test/base_test.rb b/activeresource/test/base_test.rb
index bb08098683..d37a6d4ed2 100644
--- a/activeresource/test/base_test.rb
+++ b/activeresource/test/base_test.rb
@@ -688,39 +688,39 @@ class BaseTest < Test::Unit::TestCase
end
def test_clone
- matz = Person.find(1)
- matz_c = matz.clone
- assert matz_c.new?
- matz.attributes.each do |k, v|
- assert_equal v, matz_c.send(k) if k != Person.primary_key
- end
- end
-
- def test_nested_clone
- addy = StreetAddress.find(1, :params => {:person_id => 1})
- addy_c = addy.clone
- assert addy_c.new?
- addy.attributes.each do |k, v|
- assert_equal v, addy_c.send(k) if k != StreetAddress.primary_key
- end
- assert_equal addy.prefix_options, addy_c.prefix_options
- end
-
- def test_complex_clone
- matz = Person.find(1)
- matz.address = StreetAddress.find(1, :params => {:person_id => matz.id})
- matz.non_ar_hash = {:not => "an ARes instance"}
- matz.non_ar_arr = ["not", "ARes"]
- matz_c = matz.clone
- assert matz_c.new?
- assert_raises(NoMethodError) {matz_c.address}
- assert_equal matz.non_ar_hash, matz_c.non_ar_hash
- assert_equal matz.non_ar_arr, matz_c.non_ar_arr
-
- # Test that actual copy, not just reference copy
- matz.non_ar_hash[:not] = "changed"
- assert_not_equal matz.non_ar_hash, matz_c.non_ar_hash
- end
+ matz = Person.find(1)
+ matz_c = matz.clone
+ assert matz_c.new?
+ matz.attributes.each do |k, v|
+ assert_equal v, matz_c.send(k) if k != Person.primary_key
+ end
+ end
+
+ def test_nested_clone
+ addy = StreetAddress.find(1, :params => {:person_id => 1})
+ addy_c = addy.clone
+ assert addy_c.new?
+ addy.attributes.each do |k, v|
+ assert_equal v, addy_c.send(k) if k != StreetAddress.primary_key
+ end
+ assert_equal addy.prefix_options, addy_c.prefix_options
+ end
+
+ def test_complex_clone
+ matz = Person.find(1)
+ matz.address = StreetAddress.find(1, :params => {:person_id => matz.id})
+ matz.non_ar_hash = {:not => "an ARes instance"}
+ matz.non_ar_arr = ["not", "ARes"]
+ matz_c = matz.clone
+ assert matz_c.new?
+ assert_raises(NoMethodError) {matz_c.address}
+ assert_equal matz.non_ar_hash, matz_c.non_ar_hash
+ assert_equal matz.non_ar_arr, matz_c.non_ar_arr
+
+ # Test that actual copy, not just reference copy
+ matz.non_ar_hash[:not] = "changed"
+ assert_not_equal matz.non_ar_hash, matz_c.non_ar_hash
+ end
def test_update
matz = Person.find(:first)
@@ -811,9 +811,9 @@ class BaseTest < Test::Unit::TestCase
def test_exists_with_redefined_to_param
Person.module_eval do
alias_method :original_to_param_exists, :to_param
- def to_param
- name
- end
+ def to_param
+ name
+ end
end
# Class method.
@@ -828,13 +828,13 @@ class BaseTest < Test::Unit::TestCase
# Nested instance method.
assert StreetAddress.find(1, :params => { :person_id => Person.find('Greg').to_param }).exists?
- ensure
- # revert back to original
- Person.module_eval do
- # save the 'new' to_param so we don't get a warning about discarding the method
- alias_method :exists_to_param, :to_param
- alias_method :to_param, :original_to_param_exists
- end
+ ensure
+ # revert back to original
+ Person.module_eval do
+ # save the 'new' to_param so we don't get a warning about discarding the method
+ alias_method :exists_to_param, :to_param
+ alias_method :to_param, :original_to_param_exists
+ end
end
def test_to_xml
diff --git a/activeresource/test/format_test.rb b/activeresource/test/format_test.rb
index a564ee01b5..c3733e13d8 100644
--- a/activeresource/test/format_test.rb
+++ b/activeresource/test/format_test.rb
@@ -15,7 +15,7 @@ class FormatTest < Test::Unit::TestCase
assert_equal 'Accept', header_name
headers_names = [ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:put], ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:post]]
- headers_names.each{|header_name| assert_equal 'Content-Type', header_name}
+ headers_names.each{ |name| assert_equal 'Content-Type', name }
end
def test_formats_on_single_element
@@ -85,20 +85,20 @@ class FormatTest < Test::Unit::TestCase
end
def test_serialization_of_nested_resource
- address = { :street => '12345 Street' }
- person = { :name=> 'Rus', :address => address}
+ address = { :street => '12345 Street' }
+ person = { :name=> 'Rus', :address => address}
- [:json, :xml].each do |format|
- encoded_person = ActiveResource::Formats[format].encode(person)
- assert_match /12345 Street/, encoded_person
- remote_person = Person.new(person.update({:address => StreetAddress.new(address)}))
- assert_kind_of StreetAddress, remote_person.address
- using_format(Person, format) do
- ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, encoded_person, 201, {'Location' => "/people/5.#{format}"}
- remote_person.save
- end
- end
- end
+ [:json, :xml].each do |format|
+ encoded_person = ActiveResource::Formats[format].encode(person)
+ assert_match(/12345 Street/, encoded_person)
+ remote_person = Person.new(person.update({:address => StreetAddress.new(address)}))
+ assert_kind_of StreetAddress, remote_person.address
+ using_format(Person, format) do
+ ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, encoded_person, 201, {'Location' => "/people/5.#{format}"}
+ remote_person.save
+ end
+ end
+ end
private
def using_format(klass, mime_type_reference)
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
index e77affc315..d142f21d61 100644
--- a/activesupport/CHANGELOG
+++ b/activesupport/CHANGELOG
@@ -1,6 +1,25 @@
-*2.2.1 [RC2 or 2.2 final]*
+*2.3.0 [Edge]*
-* Added render :js for people who want to render inline JavaScript replies without using RJS [DHH]
+* Added ActiveSupport::OrderedHash#each_key and ActiveSupport::OrderedHash#each_value #1410 [Christoffer Sawicki]
+
+* Added ActiveSupport::MessageVerifier and MessageEncryptor to aid users who need to store signed and/or encrypted messages. [Koz]
+
+* Added ActiveSupport::BacktraceCleaner to cut down on backtrace noise according to filters and silencers [DHH]
+
+* Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath]
+
+* Added Enumerable#none? to check that none of the elements match the block #1408 [Damian Janowski]
+
+* TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date [Geoff Buesing]
+
+* Update bundled TZInfo to 0.3.12 [Geoff Buesing]
+
+* Added lambda merging to OptionMerger (especially useful with named_scope and with_options) #726 [Paweł Kondzior]
+
+
+*2.2.1 [RC2] (November 14th, 2008)*
+
+* Increment the version of our altered memcache-client to prevent confusion caused when the 1.5.0 gem is installed.
* Fixed the option merging in Array#to_xml #1126 [Rudolf Gavlas]
@@ -57,7 +76,7 @@
* Added TimeZone #=~, to support matching zones by regex in time_zone_select. #195 [Ernie Miller]
-* Added Array#second through Array#tenth as aliases for Array#[1] through Array#[9] [DHH]
+* Added Array#second through Array#fifth as aliases for Array#[1] through Array#[4] + Array#forty_two as alias for Array[41] [DHH]
* Added test/do declaration style testing to ActiveSupport::TestCase [DHH via Jay Fields]
diff --git a/activesupport/Rakefile b/activesupport/Rakefile
index 1961fb43cf..ccbab525ba 100644
--- a/activesupport/Rakefile
+++ b/activesupport/Rakefile
@@ -1,7 +1,6 @@
require 'rake/testtask'
require 'rake/rdoctask'
require 'rake/gempackagetask'
-require 'rake/contrib/sshpublisher'
require File.join(File.dirname(__FILE__), 'lib', 'active_support', 'version')
@@ -65,12 +64,14 @@ end
desc "Publish the beta gem"
task :pgem => [:package] do
+ require 'rake/contrib/sshpublisher'
Rake::SshFilePublisher.new("gems.rubyonrails.org", "/u/sites/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload
`ssh gems.rubyonrails.org '/u/sites/gems/gemupdate.sh'`
end
desc "Publish the API documentation"
task :pdoc => [:rdoc] do
+ require 'rake/contrib/sshpublisher'
Rake::SshDirPublisher.new("wrath.rubyonrails.org", "public_html/as", "doc").upload
end
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 202f4ce6ab..7ebb3c48e0 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -21,41 +21,39 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-require 'active_support/vendor'
-require 'active_support/basic_object'
-require 'active_support/inflector'
-require 'active_support/callbacks'
+module ActiveSupport
+ def self.load_all!
+ [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom, TimeWithZone]
+ end
+
+ autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
+ autoload :Base64, 'active_support/base64'
+ autoload :BasicObject, 'active_support/basic_object'
+ autoload :BufferedLogger, 'active_support/buffered_logger'
+ autoload :Cache, 'active_support/cache'
+ autoload :Callbacks, 'active_support/callbacks'
+ autoload :Deprecation, 'active_support/deprecation'
+ autoload :Duration, 'active_support/duration'
+ 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 :Rescuable, 'active_support/rescuable'
+ autoload :SecureRandom, 'active_support/secure_random'
+ autoload :StringInquirer, 'active_support/string_inquirer'
+ autoload :TimeWithZone, 'active_support/time_with_zone'
+ autoload :TimeZone, 'active_support/values/time_zone'
+ autoload :XmlMini, 'active_support/xml_mini'
+end
+require 'active_support/vendor'
require 'active_support/core_ext'
-
-require 'active_support/buffered_logger'
-
-require 'active_support/gzip'
-require 'active_support/cache'
-
require 'active_support/dependencies'
-require 'active_support/deprecation'
-
-require 'active_support/ordered_hash'
-require 'active_support/ordered_options'
-require 'active_support/option_merger'
-
-require 'active_support/memoizable'
-require 'active_support/string_inquirer'
-
-require 'active_support/values/time_zone'
-require 'active_support/duration'
-
require 'active_support/json'
-require 'active_support/multibyte'
-
-require 'active_support/base64'
-
-require 'active_support/time_with_zone'
-
-require 'active_support/secure_random'
-
-require 'active_support/rescuable'
-
-I18n.load_path << File.dirname(__FILE__) + '/active_support/locale/en-US.yml'
+I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml"
diff --git a/activesupport/lib/active_support/backtrace_cleaner.rb b/activesupport/lib/active_support/backtrace_cleaner.rb
new file mode 100644
index 0000000000..0e262c003e
--- /dev/null
+++ b/activesupport/lib/active_support/backtrace_cleaner.rb
@@ -0,0 +1,72 @@
+module ActiveSupport
+ # Many backtraces include too much information that's not relevant for the context. This makes it hard to find the signal
+ # in the backtrace and adds debugging time. With a BacktraceCleaner, you can setup filters and silencers for your particular
+ # context, so only the relevant lines are included.
+ #
+ # If you need to reconfigure an existing BacktraceCleaner, like the one in Rails, to show as much as possible, you can always
+ # call BacktraceCleaner#remove_silencers!
+ #
+ # Example:
+ #
+ # bc = BacktraceCleaner.new
+ # bc.add_filter { |line| line.gsub(Rails.root, '') }
+ # bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
+ # bc.clean(exception.backtrace) # will strip the Rails.root prefix and skip any lines from mongrel or rubygems
+ #
+ # Inspired by the Quiet Backtrace gem by Thoughtbot.
+ class BacktraceCleaner
+ def initialize
+ @filters, @silencers = [], []
+ end
+
+ # Returns the backtrace after all filters and silencers has been run against it. Filters run first, then silencers.
+ def clean(backtrace)
+ silence(filter(backtrace))
+ end
+
+ # Adds a filter from the block provided. Each line in the backtrace will be mapped against this filter.
+ #
+ # Example:
+ #
+ # # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
+ # backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
+ def add_filter(&block)
+ @filters << block
+ end
+
+ # Adds a silencer from the block provided. If the silencer returns true for a given line, it'll be excluded from the
+ # clean backtrace.
+ #
+ # Example:
+ #
+ # # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
+ # backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
+ def add_silencer(&block)
+ @silencers << block
+ end
+
+ # Will remove all silencers, but leave in the filters. This is useful if your context of debugging suddenly expands as
+ # you suspect a bug in the libraries you use.
+ def remove_silencers!
+ @silencers = []
+ end
+
+
+ private
+ def filter(backtrace)
+ @filters.each do |f|
+ backtrace = backtrace.map { |line| f.call(line) }
+ end
+
+ backtrace
+ end
+
+ def silence(backtrace)
+ @silencers.each do |s|
+ backtrace = backtrace.reject { |line| s.call(line) }
+ end
+
+ backtrace
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index e62cec6fcb..10281d60eb 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -3,6 +3,13 @@ require 'benchmark'
module ActiveSupport
# See ActiveSupport::Cache::Store for documentation.
module Cache
+ autoload :FileStore, 'active_support/cache/file_store'
+ autoload :MemoryStore, 'active_support/cache/memory_store'
+ autoload :SynchronizedMemoryStore, 'active_support/cache/synchronized_memory_store'
+ autoload :DRbStore, 'active_support/cache/drb_store'
+ autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
+ autoload :CompressedMemCacheStore, 'active_support/cache/compressed_mem_cache_store'
+
# Creates a new CacheStore object according to the given options.
#
# If no arguments are passed to this method, then a new
@@ -215,9 +222,3 @@ module ActiveSupport
end
end
end
-
-require 'active_support/cache/file_store'
-require 'active_support/cache/memory_store'
-require 'active_support/cache/drb_store'
-require 'active_support/cache/mem_cache_store'
-require 'active_support/cache/compressed_mem_cache_store'
diff --git a/activesupport/lib/active_support/cache/drb_store.rb b/activesupport/lib/active_support/cache/drb_store.rb
index b80c2ee4d5..b16ed25aa3 100644
--- a/activesupport/lib/active_support/cache/drb_store.rb
+++ b/activesupport/lib/active_support/cache/drb_store.rb
@@ -1,15 +1,14 @@
-require 'drb'
-
module ActiveSupport
module Cache
class DRbStore < MemoryStore #:nodoc:
attr_reader :address
def initialize(address = 'druby://localhost:9192')
+ require 'drb' unless defined?(DRbObject)
super()
@address = address
@data = DRbObject.new(nil, address)
end
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/core_ext.rb b/activesupport/lib/active_support/core_ext.rb
index 4deef8c7a5..f2f976df9b 100644
--- a/activesupport/lib/active_support/core_ext.rb
+++ b/activesupport/lib/active_support/core_ext.rb
@@ -1,4 +1,4 @@
Dir[File.dirname(__FILE__) + "/core_ext/*.rb"].sort.each do |path|
- filename = File.basename(path)
+ filename = File.basename(path, '.rb')
require "active_support/core_ext/#{filename}"
end
diff --git a/activesupport/lib/active_support/core_ext/array/access.rb b/activesupport/lib/active_support/core_ext/array/access.rb
index a3b2a54c7d..6de338bfcc 100644
--- a/activesupport/lib/active_support/core_ext/array/access.rb
+++ b/activesupport/lib/active_support/core_ext/array/access.rb
@@ -43,29 +43,9 @@ module ActiveSupport #:nodoc:
self[4]
end
- # Equal to <tt>self[5]</tt>.
- def sixth
- self[5]
- end
-
- # Equal to <tt>self[6]</tt>.
- def seventh
- self[6]
- end
-
- # Equal to <tt>self[7]</tt>.
- def eighth
- self[7]
- end
-
- # Equal to <tt>self[8]</tt>.
- def ninth
- self[8]
- end
-
- # Equal to <tt>self[9]</tt>.
- def tenth
- self[9]
+ # Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
+ def forty_two
+ self[41]
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 cf3e03f62c..f0d6591135 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -1,5 +1,3 @@
-require 'builder'
-
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Array #:nodoc:
@@ -149,6 +147,7 @@ module ActiveSupport #:nodoc:
#
def to_xml(options = {})
raise "Not all elements respond to to_xml" unless all? { |e| e.respond_to? :to_xml }
+ require 'builder' unless defined?(Builder)
options[:root] ||= all? { |e| e.is_a?(first.class) && first.class.to_s != "Hash" } ? first.class.to_s.underscore.pluralize : "records"
options[:children] ||= options[:root].singularize
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 a21e98fa80..1edb3771a2 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
@@ -2,11 +2,20 @@ module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module CGI #:nodoc:
module EscapeSkippingSlashes #:nodoc:
- def escape_skipping_slashes(str)
- str = str.join('/') if str.respond_to? :join
- str.gsub(/([^ \/a-zA-Z0-9_.-])/n) do
- "%#{$1.unpack('H2').first.upcase}"
- end.tr(' ', '+')
+ if RUBY_VERSION >= '1.9'
+ def escape_skipping_slashes(str)
+ str = str.join('/') if str.respond_to? :join
+ str.gsub(/([^ \/a-zA-Z0-9_.-])/n) do
+ "%#{$1.unpack('H2' * $1.bytesize).join('%').upcase}"
+ end.tr(' ', '+')
+ end
+ else
+ def escape_skipping_slashes(str)
+ str = str.join('/') if str.respond_to? :join
+ str.gsub(/([^ \/a-zA-Z0-9_.-])/n) do
+ "%#{$1.unpack('H2').first.upcase}"
+ end.tr(' ', '+')
+ end
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index 788f3a7e9e..a7eaccfed7 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -104,4 +104,13 @@ module Enumerable
size = block_given? ? select(&block).size : self.size
size > 1
end
+
+ # Returns true if none of the elements match the given block.
+ #
+ # success = responses.none? {|r| r.status / 100 == 5 }
+ #
+ # This is a builtin method in Ruby 1.8.7 and later.
+ def none?(&block)
+ !any?(&block)
+ end unless [].respond_to?(:none?)
end
diff --git a/activesupport/lib/active_support/core_ext/exception.rb b/activesupport/lib/active_support/core_ext/exception.rb
index 57c8568334..73470cbe05 100644
--- a/activesupport/lib/active_support/core_ext/exception.rb
+++ b/activesupport/lib/active_support/core_ext/exception.rb
@@ -6,6 +6,7 @@ module ActiveSupport
end
end
+# TODO: Turn all this into using the BacktraceCleaner.
class Exception # :nodoc:
def clean_message
Pathname.clean_within message
diff --git a/activesupport/lib/active_support/core_ext/file/atomic.rb b/activesupport/lib/active_support/core_ext/file/atomic.rb
index f988eff3d9..976d462e8e 100644
--- a/activesupport/lib/active_support/core_ext/file/atomic.rb
+++ b/activesupport/lib/active_support/core_ext/file/atomic.rb
@@ -1,5 +1,3 @@
-require 'tempfile'
-
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module File #:nodoc:
@@ -18,6 +16,8 @@ module ActiveSupport #:nodoc:
# file.write("hello")
# end
def atomic_write(file_name, temp_dir = Dir.tmpdir)
+ require 'tempfile' unless defined?(Tempfile)
+
temp_file = Tempfile.new(basename(file_name), temp_dir)
yield temp_file
temp_file.close
diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb
index 50dc7c61fc..437b44c51c 100644
--- a/activesupport/lib/active_support/core_ext/hash/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb
@@ -1,47 +1,22 @@
require 'date'
-require 'cgi'
-require 'builder'
-require 'xmlsimple'
-
-# Locked down XmlSimple#xml_in_string
-class XmlSimple
- # Same as xml_in but doesn't try to smartly shoot itself in the foot.
- def xml_in_string(string, options = nil)
- handle_options('in', options)
-
- @doc = parse(string)
- result = collapse(@doc.root)
-
- if @options['keeproot']
- merge({}, @doc.root.name, result)
- else
- result
- end
- end
-
- def self.xml_in_string(string, options = nil)
- new.xml_in_string(string, options)
- end
-end
-
-# This module exists to decorate files deserialized using Hash.from_xml with
-# the <tt>original_filename</tt> and <tt>content_type</tt> methods.
-module FileLike #:nodoc:
- attr_writer :original_filename, :content_type
-
- def original_filename
- @original_filename || 'untitled'
- end
-
- def content_type
- @content_type || 'application/octet-stream'
- end
-end
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Hash #:nodoc:
module Conversions
+ # This module exists to decorate files deserialized using Hash.from_xml with
+ # the <tt>original_filename</tt> and <tt>content_type</tt> methods.
+ module FileLike #:nodoc:
+ attr_writer :original_filename, :content_type
+
+ def original_filename
+ @original_filename || 'untitled'
+ end
+
+ def content_type
+ @content_type || 'application/octet-stream'
+ end
+ end
XML_TYPE_NAMES = {
"Symbol" => "symbol",
@@ -113,6 +88,8 @@ module ActiveSupport #:nodoc:
alias_method :to_param, :to_query
def to_xml(options = {})
+ require 'builder' unless defined?(Builder)
+
options[:indent] ||= 2
options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]),
:root => "hash" })
@@ -167,13 +144,7 @@ module ActiveSupport #:nodoc:
module ClassMethods
def from_xml(xml)
- # TODO: Refactor this into something much cleaner that doesn't rely on XmlSimple
- typecast_xml_value(undasherize_keys(XmlSimple.xml_in_string(xml,
- 'forcearray' => false,
- 'forcecontent' => true,
- 'keeproot' => true,
- 'contentkey' => '__content__')
- ))
+ typecast_xml_value(undasherize_keys(XmlMini.parse(xml)))
end
private
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index 1ad18402e5..2905eebc85 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -78,6 +78,10 @@ class Module
raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
end
+ if options[:prefix] == true && options[:to].to_s =~ /^[^a-z_]/
+ raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
+ end
+
prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_"
methods.each do |method|
diff --git a/activesupport/lib/active_support/core_ext/object/conversions.rb b/activesupport/lib/active_support/core_ext/object/conversions.rb
index ad752f0fc5..278b856c45 100644
--- a/activesupport/lib/active_support/core_ext/object/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/object/conversions.rb
@@ -9,6 +9,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)}"
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb
index cd0a04d32a..46f9c7d676 100644
--- a/activesupport/lib/active_support/core_ext/object/misc.rb
+++ b/activesupport/lib/active_support/core_ext/object/misc.rb
@@ -71,4 +71,22 @@ class Object
def acts_like?(duck)
respond_to? "acts_like_#{duck}?"
end
+
+ # Tries to send the method only if object responds to it. Return +nil+ otherwise.
+ # It will also forward any arguments and/or block like Object#send does.
+ #
+ # ==== Example :
+ #
+ # # Without try
+ # @person ? @person.name : nil
+ #
+ # With try
+ # @person.try(:name)
+ #
+ # # try also accepts arguments/blocks for the method it is trying
+ # Person.try(:find, 1)
+ # @people.try(:map) {|p| p.name}
+ def try(method, *args, &block)
+ send(method, *args, &block) if respond_to?(method, true)
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/rexml.rb b/activesupport/lib/active_support/core_ext/rexml.rb
index 187f3e0f5e..b4891a9153 100644
--- a/activesupport/lib/active_support/core_ext/rexml.rb
+++ b/activesupport/lib/active_support/core_ext/rexml.rb
@@ -1,34 +1,39 @@
-require 'rexml/document'
-require 'rexml/entity'
-
# Fixes the rexml vulnerability disclosed at:
# http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/
# This fix is identical to rexml-expansion-fix version 1.0.1
+require 'rexml/rexml'
# Earlier versions of rexml defined REXML::Version, newer ones REXML::VERSION
unless (defined?(REXML::VERSION) ? REXML::VERSION : REXML::Version) > "3.1.7.2"
- module REXML
- class Entity < Child
- undef_method :unnormalized
- def unnormalized
- document.record_entity_expansion! if document
- v = value()
- return nil if v.nil?
- @unnormalized = Text::unnormalize(v, parent)
- @unnormalized
- end
- end
- class Document < Element
- @@entity_expansion_limit = 10_000
- def self.entity_expansion_limit= val
- @@entity_expansion_limit = val
+ require 'rexml/document'
+
+ # REXML in 1.8.7 has the patch but didn't update Version from 3.1.7.2.
+ unless REXML::Document.respond_to?(:entity_expansion_limit=)
+ require 'rexml/entity'
+
+ module REXML
+ class Entity < Child
+ undef_method :unnormalized
+ def unnormalized
+ document.record_entity_expansion! if document
+ v = value()
+ return nil if v.nil?
+ @unnormalized = Text::unnormalize(v, parent)
+ @unnormalized
+ end
end
+ class Document < Element
+ @@entity_expansion_limit = 10_000
+ def self.entity_expansion_limit= val
+ @@entity_expansion_limit = val
+ end
- def record_entity_expansion!
- @number_of_expansions ||= 0
- @number_of_expansions += 1
- if @number_of_expansions > @@entity_expansion_limit
- raise "Number of entity expansions exceeded, processing aborted."
+ def record_entity_expansion!
+ @number_of_expansions ||= 0
+ @number_of_expansions += 1
+ if @number_of_expansions > @@entity_expansion_limit
+ raise "Number of entity expansions exceeded, processing aborted."
+ end
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/string/iterators.rb b/activesupport/lib/active_support/core_ext/string/iterators.rb
index 66a08a5cd0..fe17d140ca 100644
--- a/activesupport/lib/active_support/core_ext/string/iterators.rb
+++ b/activesupport/lib/active_support/core_ext/string/iterators.rb
@@ -13,7 +13,9 @@ module ActiveSupport #:nodoc:
# When $KCODE = 'UTF8', multi-byte characters are yielded appropriately.
def each_char
scanner, char = StringScanner.new(self), /./mu
- loop { yield(scanner.scan(char) || break) }
+ while c = scanner.scan(char)
+ yield c
+ end
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index 00078de692..5ed750afcc 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -1,3 +1,5 @@
+require 'active_support/duration'
+
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Time #:nodoc:
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 3d871eec11..293450c180 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -138,14 +138,22 @@ module ActiveSupport #:nodoc:
end
def load_with_new_constant_marking(file, *extras) #:nodoc:
- Dependencies.new_constants_in(Object) { load_without_new_constant_marking(file, *extras) }
+ if Dependencies.load?
+ Dependencies.new_constants_in(Object) { load_without_new_constant_marking(file, *extras) }
+ else
+ load_without_new_constant_marking(file, *extras)
+ end
rescue Exception => exception # errors from loading file
exception.blame_file! file
raise
end
def require(file, *extras) #:nodoc:
- Dependencies.new_constants_in(Object) { super }
+ if Dependencies.load?
+ Dependencies.new_constants_in(Object) { super }
+ else
+ super
+ end
rescue Exception => exception # errors from required file
exception.blame_file! file
raise
@@ -305,12 +313,13 @@ module ActiveSupport #:nodoc:
nesting = expanded_path[(expanded_root.size)..-1]
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
next if nesting.blank?
-
- [
- nesting.camelize,
- # Special case: application.rb might define ApplicationControlller.
- ('ApplicationController' if nesting == 'application')
- ]
+ nesting_camel = nesting.camelize
+ begin
+ qualified_const_defined?(nesting_camel)
+ rescue NameError
+ next
+ end
+ [ nesting_camel ]
end.flatten.compact.uniq
end
@@ -491,7 +500,7 @@ module ActiveSupport #:nodoc:
initial_constants = if qualified_const_defined?(mod_name)
mod_name.constantize.local_constant_names
else
- []
+ []
end
else
raise Argument, "#{desc.inspect} does not describe a module!"
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index b4d8f61b8c..543e3b08d2 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -113,37 +113,6 @@ module ActiveSupport
end
end
- module Assertions #:nodoc:
- def assert_deprecated(match = nil, &block)
- result, warnings = collect_deprecations(&block)
- assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
- if match
- match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
- assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
- end
- result
- end
-
- def assert_not_deprecated(&block)
- result, deprecations = collect_deprecations(&block)
- assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
- result
- end
-
- private
- def collect_deprecations
- old_behavior = ActiveSupport::Deprecation.behavior
- deprecations = []
- ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
- deprecations << message
- end
- result = yield
- [result, deprecations]
- ensure
- ActiveSupport::Deprecation.behavior = old_behavior
- end
- end
-
class DeprecationProxy #:nodoc:
silence_warnings do
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
@@ -220,24 +189,3 @@ end
class Module
include ActiveSupport::Deprecation::ClassMethods
end
-
-require 'test/unit/error'
-
-module Test
- module Unit
- class TestCase
- include ActiveSupport::Deprecation::Assertions
- end
-
- class Error # :nodoc:
- # Silence warnings when reporting test errors.
- def message_with_silenced_deprecation
- ActiveSupport::Deprecation.silence do
- message_without_silenced_deprecation
- end
- end
-
- alias_method_chain :message, :silenced_deprecation
- end
- end
-end
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 8eae85d38e..c41e86dfd1 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -1,3 +1,5 @@
+require 'active_support/basic_object'
+
module ActiveSupport
# Provides accurate date and time measurements using Date#advance and
# Time#advance, respectively. It mainly supports the methods on Numeric,
diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb
index 1ccfec4000..683af4556e 100644
--- a/activesupport/lib/active_support/inflector.rb
+++ b/activesupport/lib/active_support/inflector.rb
@@ -1,3 +1,4 @@
+# encoding: utf-8
require 'singleton'
require 'iconv'
@@ -133,7 +134,6 @@ module ActiveSupport
# "octopus".pluralize # => "octopi"
# "sheep".pluralize # => "sheep"
# "words".pluralize # => "words"
- # "the blue mailman".pluralize # => "the blue mailmen"
# "CamelOctopus".pluralize # => "CamelOctopi"
def pluralize(word)
result = word.to_s.dup
@@ -153,7 +153,6 @@ module ActiveSupport
# "octopi".singularize # => "octopus"
# "sheep".singluarize # => "sheep"
# "word".singularize # => "word"
- # "the blue mailmen".singularize # => "the blue mailman"
# "CamelOctopi".singularize # => "CamelOctopus"
def singularize(word)
result = word.to_s.dup
@@ -276,9 +275,16 @@ module ActiveSupport
Iconv.iconv('ascii//ignore//translit', 'utf-8', string).to_s
end
+ if RUBY_VERSION >= '1.9'
+ undef_method :transliterate
+ def transliterate(string)
+ warn "Ruby 1.9 doesn't support Unicode normalization yet"
+ string.dup
+ end
+
# The iconv transliteration code doesn't function correctly
# on some platforms, but it's very fast where it does function.
- if "foo" != Inflector.transliterate("föö")
+ elsif "foo" != Inflector.transliterate("föö")
undef_method :transliterate
def transliterate(string)
string.mb_chars.normalize(:kd). # Decompose accented characters
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 8650e34228..aaaa3cdfd2 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -1,37 +1,31 @@
-require 'active_support/json/variable'
-require 'active_support/json/encoders/object' # Require explicitly for rdoc.
-Dir["#{File.dirname(__FILE__)}/encoders/**/*.rb"].each do |file|
- basename = File.basename(file, '.rb')
- unless basename == 'object'
- require "active_support/json/encoders/#{basename}"
- end
-end
-
module ActiveSupport
module JSON
class CircularReferenceError < StandardError
end
- class << self
- REFERENCE_STACK_VARIABLE = :json_reference_stack #:nodoc:
-
- # Converts a Ruby object into a JSON string.
- def encode(value, options = {})
- raise_on_circular_reference(value) do
- value.send(:to_json, options)
- end
- end
-
- protected
- def raise_on_circular_reference(value) #:nodoc:
- stack = Thread.current[REFERENCE_STACK_VARIABLE] ||= []
- raise CircularReferenceError, 'object references itself' if
- stack.include? value
- stack << value
- yield
- ensure
- stack.pop
- end
+ # Converts a Ruby object into a JSON string.
+ def self.encode(value, options = {})
+ seen = (options[:seen] ||= [])
+ raise CircularReferenceError, 'object references itself' if seen.include?(value)
+ seen << value
+ value.send(:to_json, options)
+ ensure
+ seen.pop
end
end
end
+
+require 'active_support/json/variable'
+require 'active_support/json/encoders/date'
+require 'active_support/json/encoders/date_time'
+require 'active_support/json/encoders/enumerable'
+require 'active_support/json/encoders/false_class'
+require 'active_support/json/encoders/hash'
+require 'active_support/json/encoders/nil_class'
+require 'active_support/json/encoders/numeric'
+require 'active_support/json/encoders/object'
+require 'active_support/json/encoders/regexp'
+require 'active_support/json/encoders/string'
+require 'active_support/json/encoders/symbol'
+require 'active_support/json/encoders/time'
+require 'active_support/json/encoders/true_class'
diff --git a/activesupport/lib/active_support/locale/en-US.yml b/activesupport/lib/active_support/locale/en.yml
index c31694b9d6..92132cacd5 100644
--- a/activesupport/lib/active_support/locale/en-US.yml
+++ b/activesupport/lib/active_support/locale/en.yml
@@ -1,4 +1,4 @@
-en-US:
+en:
date:
formats:
# Use the strftime parameters for formats.
diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb
index cd5c01cda2..9f2fd3a401 100644
--- a/activesupport/lib/active_support/memoizable.rb
+++ b/activesupport/lib/active_support/memoizable.rb
@@ -1,10 +1,10 @@
module ActiveSupport
module Memoizable
- MEMOIZED_IVAR = Proc.new do |symbol|
+ def self.memoized_ivar_for(symbol)
"@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}".to_sym
end
- module Freezable
+ module InstanceMethods
def self.included(base)
base.class_eval do
unless base.method_defined?(:freeze_without_memoizable)
@@ -19,23 +19,35 @@ module ActiveSupport
end
def memoize_all
- methods.each do |m|
- if m.to_s =~ /^_unmemoized_(.*)/
- if method(m).arity == 0
- __send__($1)
- else
- ivar = MEMOIZED_IVAR.call($1)
- instance_variable_set(ivar, {})
+ prime_cache ".*"
+ end
+
+ def unmemoize_all
+ flush_cache ".*"
+ end
+
+ def prime_cache(*syms)
+ syms.each do |sym|
+ methods.each do |m|
+ if m.to_s =~ /^_unmemoized_(#{sym})/
+ if method(m).arity == 0
+ __send__($1)
+ else
+ ivar = ActiveSupport::Memoizable.memoized_ivar_for($1)
+ instance_variable_set(ivar, {})
+ end
end
end
end
end
- def unmemoize_all
- methods.each do |m|
- if m.to_s =~ /^_unmemoized_(.*)/
- ivar = MEMOIZED_IVAR.call($1)
- instance_variable_get(ivar).clear if instance_variable_defined?(ivar)
+ def flush_cache(*syms, &block)
+ syms.each do |sym|
+ methods.each do |m|
+ if m.to_s =~ /^_unmemoized_(#{sym})/
+ ivar = ActiveSupport::Memoizable.memoized_ivar_for($1)
+ instance_variable_get(ivar).clear if instance_variable_defined?(ivar)
+ end
end
end
end
@@ -44,10 +56,10 @@ module ActiveSupport
def memoize(*symbols)
symbols.each do |symbol|
original_method = :"_unmemoized_#{symbol}"
- memoized_ivar = MEMOIZED_IVAR.call(symbol)
+ memoized_ivar = ActiveSupport::Memoizable.memoized_ivar_for(symbol)
class_eval <<-EOS, __FILE__, __LINE__
- include Freezable
+ include InstanceMethods
raise "Already memoized #{symbol}" if method_defined?(:#{original_method})
alias #{original_method} #{symbol}
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
new file mode 100644
index 0000000000..347af9dc76
--- /dev/null
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -0,0 +1,70 @@
+require 'openssl'
+
+module ActiveSupport
+ # MessageEncryptor is a simple way to encrypt values which get stored somewhere
+ # you don't trust.
+ #
+ # The cipher text and initialization vector are base64 encoded and returned to you.
+ #
+ # This can be used in situations similar to the MessageVerifier, but where you don't
+ # want users to be able to determine the value of the payload.
+ class MessageEncryptor
+ class InvalidMessage < StandardError; end
+ OpenSSLCipherError = OpenSSL::Cipher.const_defined?(:CipherError) ? OpenSSL::Cipher::CipherError : OpenSSL::CipherError
+
+ def initialize(secret, cipher = 'aes-256-cbc')
+ @secret = secret
+ @cipher = cipher
+ end
+
+ def encrypt(value)
+ cipher = new_cipher
+ # Rely on OpenSSL for the initialization vector
+ iv = cipher.random_iv
+
+ cipher.encrypt
+ cipher.key = @secret
+ cipher.iv = iv
+
+ encrypted_data = cipher.update(Marshal.dump(value))
+ encrypted_data << cipher.final
+
+ [encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--")
+ end
+
+ def decrypt(encrypted_message)
+ cipher = new_cipher
+ encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)}
+
+ cipher.decrypt
+ cipher.key = @secret
+ cipher.iv = iv
+
+ decrypted_data = cipher.update(encrypted_data)
+ decrypted_data << cipher.final
+
+ Marshal.load(decrypted_data)
+ rescue OpenSSLCipherError, TypeError
+ raise InvalidMessage
+ end
+
+ def encrypt_and_sign(value)
+ verifier.generate(encrypt(value))
+ end
+
+ def decrypt_and_verify(value)
+ decrypt(verifier.verify(value))
+ end
+
+
+
+ private
+ def new_cipher
+ OpenSSL::Cipher::Cipher.new(@cipher)
+ end
+
+ def verifier
+ MessageVerifier.new(@secret)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
new file mode 100644
index 0000000000..b24acb9f47
--- /dev/null
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -0,0 +1,46 @@
+module ActiveSupport
+ # MessageVerifier makes it easy to generate and verify messages which are signed
+ # to prevent tampering.
+ #
+ # This is useful for cases like remember-me tokens and auto-unsubscribe links where the
+ # session store isn't suitable or available.
+ #
+ # Remember Me:
+ # cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
+ #
+ # In the authentication filter:
+ #
+ # id, time = @verifier.verify(cookies[:remember_me])
+ # if time < Time.now
+ # self.current_user = User.find(id)
+ # end
+ #
+ class MessageVerifier
+ class InvalidSignature < StandardError; end
+
+ def initialize(secret, digest = 'SHA1')
+ @secret = secret
+ @digest = digest
+ end
+
+ def verify(signed_message)
+ data, digest = signed_message.split("--")
+ if digest != generate_digest(data)
+ raise InvalidSignature
+ else
+ Marshal.load(ActiveSupport::Base64.decode64(data))
+ end
+ end
+
+ def generate(value)
+ data = ActiveSupport::Base64.encode64s(Marshal.dump(value))
+ "#{data}--#{generate_digest(data)}"
+ end
+
+ private
+ def generate_digest(data)
+ require 'openssl' unless defined?(OpenSSL)
+ OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(@digest), @secret, data)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/option_merger.rb b/activesupport/lib/active_support/option_merger.rb
index b563b093ed..63662b75c7 100644
--- a/activesupport/lib/active_support/option_merger.rb
+++ b/activesupport/lib/active_support/option_merger.rb
@@ -10,7 +10,13 @@ module ActiveSupport
private
def method_missing(method, *arguments, &block)
- arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
+ if arguments.last.is_a?(Proc)
+ proc = arguments.pop
+ arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
+ else
+ arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
+ end
+
@context.__send__(method, *arguments, &block)
end
end
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 9757054e43..5de94c67e0 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -53,6 +53,14 @@ module ActiveSupport
end
alias_method :value?, :has_value?
+
+ def each_key
+ each { |key, value| yield key }
+ end
+
+ def each_value
+ each { |key, value| yield value }
+ end
end
end
end
diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
index f2bc12e832..c27c4ddb1a 100644
--- a/activesupport/lib/active_support/rescuable.rb
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -78,7 +78,7 @@ module ActiveSupport
def handler_for_rescue(exception)
# We go from right to left because pairs are pushed onto rescue_handlers
# as rescue_from declarations are found.
- _, handler = Array(rescue_handlers).reverse.detect do |klass_name, handler|
+ _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
# The purpose of allowing strings in rescue_from is to support the
# declaration of handler associations for exception classes whose
# definition is yet unknown.
@@ -97,11 +97,11 @@ module ActiveSupport
exception.is_a?(klass) if klass
end
- case handler
+ case rescuer
when Symbol
- method(handler)
+ method(rescuer)
when Proc
- handler.bind(self)
+ rescuer.bind(self)
end
end
end
diff --git a/activesupport/lib/active_support/secure_random.rb b/activesupport/lib/active_support/secure_random.rb
index 97971e8830..cfbce4d754 100644
--- a/activesupport/lib/active_support/secure_random.rb
+++ b/activesupport/lib/active_support/secure_random.rb
@@ -1,16 +1,11 @@
begin
- require 'openssl'
-rescue LoadError
-end
-
-begin
require 'securerandom'
rescue LoadError
end
module ActiveSupport
if defined?(::SecureRandom)
- # Use Ruby 1.9's SecureRandom library whenever possible.
+ # Use Ruby's SecureRandom library if available.
SecureRandom = ::SecureRandom # :nodoc:
else
# = Secure random number generator interface.
@@ -64,6 +59,13 @@ module ActiveSupport
def self.random_bytes(n=nil)
n ||= 16
+ unless defined? OpenSSL
+ begin
+ require 'openssl'
+ rescue LoadError
+ end
+ end
+
if defined? OpenSSL::Random
return OpenSSL::Random.random_bytes(n)
end
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index 197e73b3e8..97b2b6ef9c 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -1,24 +1,39 @@
-require 'test/unit/testcase'
-require 'active_support/testing/default'
-require 'active_support/testing/core_ext/test'
+begin
+ gem 'mocha', '>= 0.9.3'
+ require 'mocha'
+rescue LoadError
+ # Fake Mocha::ExpectationError so we can rescue it in #run. Bleh.
+ Object.const_set :Mocha, Module.new
+ Mocha.const_set :ExpectationError, Class.new(StandardError)
+end
+require 'test/unit/testcase'
+require 'active_support/testing/setup_and_teardown'
+require 'active_support/testing/assertions'
+require 'active_support/testing/deprecation'
+require 'active_support/testing/declarative'
module ActiveSupport
- class TestCase < Test::Unit::TestCase
- # test "verify something" do
- # ...
- # end
- def self.test(name, &block)
- test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
- defined = instance_method(test_name) rescue false
- raise "#{test_name} is already defined in #{self}" if defined
- if block_given?
- define_method(test_name, &block)
- else
- define_method(test_name) do
- flunk "No implementation provided for #{name}"
- end
+ class TestCase < ::Test::Unit::TestCase
+ if defined? MiniTest
+ Assertion = MiniTest::Assertion
+ alias_method :method_name, :name
+ else
+ # TODO: Figure out how to get the Rails::BacktraceFilter into minitest/unit
+ if defined?(Rails)
+ require 'rails/backtrace_cleaner'
+ Test::Unit::Util::BacktraceFilter.module_eval { include Rails::BacktraceFilterForTestUnit }
end
+
+ Assertion = Test::Unit::AssertionFailedError
+
+ require 'active_support/testing/default'
+ include ActiveSupport::Testing::Default
end
+
+ include ActiveSupport::Testing::SetupAndTeardown
+ include ActiveSupport::Testing::Assertions
+ include ActiveSupport::Testing::Deprecation
+ extend ActiveSupport::Testing::Declarative
end
end
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
new file mode 100644
index 0000000000..ce2f44efd6
--- /dev/null
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -0,0 +1,61 @@
+module ActiveSupport
+ module Testing
+ module Assertions
+ # Test numeric difference between the return value of an expression as a result of what is evaluated
+ # in the yielded block.
+ #
+ # assert_difference 'Article.count' do
+ # post :create, :article => {...}
+ # end
+ #
+ # An arbitrary expression is passed in and evaluated.
+ #
+ # assert_difference 'assigns(:article).comments(:reload).size' do
+ # post :create, :comment => {...}
+ # end
+ #
+ # An arbitrary positive or negative difference can be specified. The default is +1.
+ #
+ # assert_difference 'Article.count', -1 do
+ # post :delete, :id => ...
+ # end
+ #
+ # An array of expressions can also be passed in and evaluated.
+ #
+ # assert_difference [ 'Article.count', 'Post.count' ], +2 do
+ # post :create, :article => {...}
+ # end
+ #
+ # A error message can be specified.
+ #
+ # assert_difference 'Article.count', -1, "An Article should be destroyed" do
+ # post :delete, :id => ...
+ # end
+ def assert_difference(expressions, difference = 1, message = nil, &block)
+ expression_evaluations = Array(expressions).collect{ |expression| lambda { eval(expression, block.send(:binding)) } }
+
+ original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression.call }
+ yield
+ expression_evaluations.each_with_index do |expression, i|
+ assert_equal original_values[i] + difference, expression.call, message
+ end
+ end
+
+ # Assertion that the numeric result of evaluating an expression is not changed before and after
+ # invoking the passed in block.
+ #
+ # assert_no_difference 'Article.count' do
+ # post :create, :article => invalid_attributes
+ # end
+ #
+ # A error message can be specified.
+ #
+ # assert_no_difference 'Article.count', "An Article should not be destroyed" do
+ # post :create, :article => invalid_attributes
+ # end
+ def assert_no_difference(expressions, message = nil, &block)
+ assert_difference expressions, 0, message, &block
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/declarative.rb b/activesupport/lib/active_support/testing/declarative.rb
new file mode 100644
index 0000000000..cb6a5844eb
--- /dev/null
+++ b/activesupport/lib/active_support/testing/declarative.rb
@@ -0,0 +1,21 @@
+module ActiveSupport
+ module Testing
+ module Declarative
+ # test "verify something" do
+ # ...
+ # end
+ def test(name, &block)
+ test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
+ defined = instance_method(test_name) rescue false
+ raise "#{test_name} is already defined in #{self}" if defined
+ if block_given?
+ define_method(test_name, &block)
+ else
+ define_method(test_name) do
+ flunk "No implementation provided for #{name}"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/deprecation.rb b/activesupport/lib/active_support/testing/deprecation.rb
new file mode 100644
index 0000000000..e9220605bd
--- /dev/null
+++ b/activesupport/lib/active_support/testing/deprecation.rb
@@ -0,0 +1,55 @@
+module ActiveSupport
+ module Testing
+ module Deprecation #:nodoc:
+ def assert_deprecated(match = nil, &block)
+ result, warnings = collect_deprecations(&block)
+ assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
+ if match
+ match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
+ assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
+ end
+ result
+ end
+
+ def assert_not_deprecated(&block)
+ result, deprecations = collect_deprecations(&block)
+ assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
+ result
+ end
+
+ private
+ def collect_deprecations
+ old_behavior = ActiveSupport::Deprecation.behavior
+ deprecations = []
+ ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
+ deprecations << message
+ end
+ result = yield
+ [result, deprecations]
+ ensure
+ ActiveSupport::Deprecation.behavior = old_behavior
+ end
+ end
+ end
+end
+
+begin
+ require 'test/unit/error'
+
+ module Test
+ module Unit
+ class Error # :nodoc:
+ # Silence warnings when reporting test errors.
+ def message_with_silenced_deprecation
+ ActiveSupport::Deprecation.silence do
+ message_without_silenced_deprecation
+ end
+ end
+
+ alias_method_chain :message, :silenced_deprecation
+ end
+ end
+ end
+rescue LoadError
+ # Using miniunit, ignore.
+end
diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb
index a514b61fea..245f57a7b0 100644
--- a/activesupport/lib/active_support/testing/setup_and_teardown.rb
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -1,119 +1,85 @@
+require 'active_support/callbacks'
+
module ActiveSupport
module Testing
module SetupAndTeardown
- # For compatibility with Ruby < 1.8.6
- PASSTHROUGH_EXCEPTIONS =
- if defined?(Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS)
- Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS
- else
- [NoMemoryError, SignalException, Interrupt, SystemExit]
- end
-
def self.included(base)
base.class_eval do
include ActiveSupport::Callbacks
define_callbacks :setup, :teardown
- if defined?(::Mini)
- undef_method :run
- alias_method :run, :run_with_callbacks_and_miniunit
+ if defined? MiniTest
+ include ForMiniTest
else
- begin
- require 'mocha'
- undef_method :run
- alias_method :run, :run_with_callbacks_and_mocha
- rescue LoadError
- undef_method :run
- alias_method :run, :run_with_callbacks_and_testunit
- end
+ include ForClassicTestUnit
end
end
end
- def run_with_callbacks_and_miniunit(runner)
- result = '.'
- begin
- run_callbacks :setup
- result = super
- rescue Exception => e
- result = runner.puke(self.class, self.name, e)
- ensure
+ module ForMiniTest
+ def run(runner)
+ result = '.'
begin
- teardown
- run_callbacks :teardown, :enumerator => :reverse_each
+ run_callbacks :setup
+ result = super
rescue Exception => e
result = runner.puke(self.class, self.name, e)
+ ensure
+ begin
+ run_callbacks :teardown, :enumerator => :reverse_each
+ rescue Exception => e
+ result = runner.puke(self.class, self.name, e)
+ end
end
+ result
end
- result
end
- # This redefinition is unfortunate but test/unit shows us no alternative.
- def run_with_callbacks_and_testunit(result) #:nodoc:
- return if @method_name.to_s == "default_test"
+ module ForClassicTestUnit
+ # For compatibility with Ruby < 1.8.6
+ PASSTHROUGH_EXCEPTIONS = Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS rescue [NoMemoryError, SignalException, Interrupt, SystemExit]
- yield(Test::Unit::TestCase::STARTED, name)
- @_result = result
- begin
- run_callbacks :setup
- setup
- __send__(@method_name)
- rescue Test::Unit::AssertionFailedError => e
- add_failure(e.message, e.backtrace)
- rescue *PASSTHROUGH_EXCEPTIONS
- raise
- rescue Exception
- add_error($!)
- ensure
- begin
- teardown
- run_callbacks :teardown, :enumerator => :reverse_each
- rescue Test::Unit::AssertionFailedError => e
- add_failure(e.message, e.backtrace)
- rescue *PASSTHROUGH_EXCEPTIONS
- raise
- rescue Exception
- add_error($!)
- end
- end
- result.add_run
- yield(Test::Unit::TestCase::FINISHED, name)
- end
+ # This redefinition is unfortunate but test/unit shows us no alternative.
+ # Doubly unfortunate: hax to support Mocha's hax.
+ def run(result)
+ return if @method_name.to_s == "default_test"
- # Doubly unfortunate: mocha does the same so we have to hax their hax.
- def run_with_callbacks_and_mocha(result)
- return if @method_name.to_s == "default_test"
+ if using_mocha = respond_to?(:mocha_verify)
+ assertion_counter = Mocha::TestCaseAdapter::AssertionCounter.new(result)
+ end
- yield(Test::Unit::TestCase::STARTED, name)
- @_result = result
- begin
- mocha_setup
+ yield(Test::Unit::TestCase::STARTED, name)
+ @_result = result
begin
- run_callbacks :setup
- setup
- __send__(@method_name)
- mocha_verify { add_assertion }
- rescue Mocha::ExpectationError => e
- add_failure(e.message, e.backtrace)
- 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
+ run_callbacks :setup
+ setup
+ __send__(@method_name)
+ mocha_verify(assertion_counter) if using_mocha
+ rescue Mocha::ExpectationError => e
+ add_failure(e.message, e.backtrace)
rescue Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
- rescue StandardError, ScriptError
- add_error($!)
+ rescue Exception => e
+ raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
+ add_error(e)
+ ensure
+ begin
+ teardown
+ run_callbacks :teardown, :enumerator => :reverse_each
+ rescue Test::Unit::AssertionFailedError => e
+ add_failure(e.message, e.backtrace)
+ rescue Exception => e
+ raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
+ add_error(e)
+ end
end
+ ensure
+ mocha_teardown if using_mocha
end
- ensure
- mocha_teardown
+ result.add_run
+ yield(Test::Unit::TestCase::FINISHED, name)
end
- result.add_run
- yield(Test::Unit::TestCase::FINISHED, name)
end
end
end
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index a02cd81f72..9a2d283b30 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -1,4 +1,5 @@
require 'tzinfo'
+
module ActiveSupport
# A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are
# limited to UTC and the system's <tt>ENV['TZ']</tt> zone.
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index 4991f71683..836f469df7 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -288,6 +288,7 @@ module ActiveSupport
# TODO: Preload instead of lazy load for thread safety
def tzinfo
+ require 'tzinfo' unless defined?(TZInfo)
@tzinfo ||= TZInfo::Timezone.get(MAPPING[name])
end
@@ -304,7 +305,8 @@ module ActiveSupport
"Mexico City", "Monterrey", "Central America" ],
[-18_000, "Eastern Time (US & Canada)", "Indiana (East)", "Bogota",
"Lima", "Quito" ],
- [-14_400, "Atlantic Time (Canada)", "Caracas", "La Paz", "Santiago" ],
+ [-16_200, "Caracas" ],
+ [-14_400, "Atlantic Time (Canada)", "La Paz", "Santiago" ],
[-12_600, "Newfoundland" ],
[-10_800, "Brasilia", "Buenos Aires", "Georgetown", "Greenland" ],
[ -7_200, "Mid-Atlantic" ],
@@ -325,9 +327,9 @@ module ActiveSupport
[ 14_400, "Abu Dhabi", "Muscat", "Baku", "Tbilisi", "Yerevan" ],
[ 16_200, "Kabul" ],
[ 18_000, "Ekaterinburg", "Islamabad", "Karachi", "Tashkent" ],
- [ 19_800, "Chennai", "Kolkata", "Mumbai", "New Delhi" ],
+ [ 19_800, "Chennai", "Kolkata", "Mumbai", "New Delhi", "Sri Jayawardenepura" ],
[ 20_700, "Kathmandu" ],
- [ 21_600, "Astana", "Dhaka", "Sri Jayawardenepura", "Almaty",
+ [ 21_600, "Astana", "Dhaka", "Almaty",
"Novosibirsk" ],
[ 23_400, "Rangoon" ],
[ 25_200, "Bangkok", "Hanoi", "Jakarta", "Krasnoyarsk" ],
diff --git a/activesupport/lib/active_support/vendor.rb b/activesupport/lib/active_support/vendor.rb
index 633eb2ef08..463610722c 100644
--- a/activesupport/lib/active_support/vendor.rb
+++ b/activesupport/lib/active_support/vendor.rb
@@ -6,23 +6,18 @@ begin
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/builder-2.1.2"
end
+require 'builder'
begin
- gem 'xml-simple', '~> 1.0.11'
+ gem 'memcache-client', '~> 1.5.1'
rescue Gem::LoadError
- $:.unshift "#{File.dirname(__FILE__)}/vendor/xml-simple-1.0.11"
+ $:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.5.1"
end
begin
- gem 'memcache-client', '~> 1.5.0'
+ gem 'tzinfo', '~> 0.3.12'
rescue Gem::LoadError
- $:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.5.0"
-end
-
-begin
- gem 'tzinfo', '~> 0.3.11'
-rescue Gem::LoadError
- $:.unshift "#{File.dirname(__FILE__)}/vendor/tzinfo-0.3.11"
+ $:.unshift "#{File.dirname(__FILE__)}/vendor/tzinfo-0.3.12"
end
# TODO I18n gem has not been released yet
@@ -31,4 +26,4 @@ end
# rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/i18n-0.0.1"
require 'i18n'
-# end \ No newline at end of file
+# end
diff --git a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb
index 40e82d8225..2ffe3618b5 100755
--- a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb
+++ b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n.rb
@@ -11,7 +11,7 @@ require 'i18n/exceptions'
module I18n
@@backend = nil
@@load_path = nil
- @@default_locale = :'en-US'
+ @@default_locale = :'en'
@@exception_handler = :default_exception_handler
class << self
@@ -25,7 +25,7 @@ module I18n
@@backend = backend
end
- # Returns the current default locale. Defaults to 'en-US'
+ # Returns the current default locale. Defaults to 'en'
def default_locale
@@default_locale
end
@@ -57,7 +57,7 @@ module I18n
# 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-US.yml'
+ # I18n.load_path << 'path/to/locale/en.yml'
def load_path
@@load_path ||= []
end
diff --git a/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb b/activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb
index 30113201a6..99c9af0398 100644
--- a/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb
+++ b/activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb
@@ -1,10 +1,10 @@
# All original code copyright 2005, 2006, 2007 Bob Cottrell, Eric Hodel,
# The Robot Co-op. All rights reserved.
-#
+#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
-#
+#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
@@ -13,7 +13,7 @@
# 3. Neither the names of the authors nor the names of their contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
-#
+#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Argentina/San_Juan.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Argentina/San_Juan.rb
deleted file mode 100644
index 4a9663684d..0000000000
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Argentina/San_Juan.rb
+++ /dev/null
@@ -1,170 +0,0 @@
-require 'tzinfo/timezone_definition'
-
-module TZInfo
- module Definitions
- module America
- module Argentina
- module San_Juan
- include TimezoneDefinition
-
- timezone 'America/Argentina/San_Juan' do |tz|
- tz.offset :o0, -16444, 0, :LMT
- tz.offset :o1, -15408, 0, :CMT
- tz.offset :o2, -14400, 0, :ART
- tz.offset :o3, -14400, 3600, :ARST
- tz.offset :o4, -10800, 0, :ART
- tz.offset :o5, -10800, 3600, :ARST
- tz.offset :o6, -14400, 0, :WART
-
- tz.transition 1894, 10, :o1, 52123666111, 21600
- tz.transition 1920, 5, :o2, 1453467407, 600
- tz.transition 1930, 12, :o3, 7278935, 3
- tz.transition 1931, 4, :o2, 19411461, 8
- tz.transition 1931, 10, :o3, 7279889, 3
- tz.transition 1932, 3, :o2, 19414141, 8
- tz.transition 1932, 11, :o3, 7281038, 3
- tz.transition 1933, 3, :o2, 19417061, 8
- tz.transition 1933, 11, :o3, 7282133, 3
- tz.transition 1934, 3, :o2, 19419981, 8
- tz.transition 1934, 11, :o3, 7283228, 3
- tz.transition 1935, 3, :o2, 19422901, 8
- tz.transition 1935, 11, :o3, 7284323, 3
- tz.transition 1936, 3, :o2, 19425829, 8
- tz.transition 1936, 11, :o3, 7285421, 3
- tz.transition 1937, 3, :o2, 19428749, 8
- tz.transition 1937, 11, :o3, 7286516, 3
- tz.transition 1938, 3, :o2, 19431669, 8
- tz.transition 1938, 11, :o3, 7287611, 3
- tz.transition 1939, 3, :o2, 19434589, 8
- tz.transition 1939, 11, :o3, 7288706, 3
- tz.transition 1940, 3, :o2, 19437517, 8
- tz.transition 1940, 7, :o3, 7289435, 3
- tz.transition 1941, 6, :o2, 19441285, 8
- tz.transition 1941, 10, :o3, 7290848, 3
- tz.transition 1943, 8, :o2, 19447501, 8
- tz.transition 1943, 10, :o3, 7293038, 3
- tz.transition 1946, 3, :o2, 19455045, 8
- tz.transition 1946, 10, :o3, 7296284, 3
- tz.transition 1963, 10, :o2, 19506429, 8
- tz.transition 1963, 12, :o3, 7315136, 3
- tz.transition 1964, 3, :o2, 19507645, 8
- tz.transition 1964, 10, :o3, 7316051, 3
- tz.transition 1965, 3, :o2, 19510565, 8
- tz.transition 1965, 10, :o3, 7317146, 3
- tz.transition 1966, 3, :o2, 19513485, 8
- tz.transition 1966, 10, :o3, 7318241, 3
- tz.transition 1967, 4, :o2, 19516661, 8
- tz.transition 1967, 10, :o3, 7319294, 3
- tz.transition 1968, 4, :o2, 19519629, 8
- tz.transition 1968, 10, :o3, 7320407, 3
- tz.transition 1969, 4, :o2, 19522541, 8
- tz.transition 1969, 10, :o4, 7321499, 3
- tz.transition 1974, 1, :o5, 128142000
- tz.transition 1974, 5, :o4, 136605600
- tz.transition 1988, 12, :o5, 596948400
- tz.transition 1989, 3, :o4, 605066400
- tz.transition 1989, 10, :o5, 624423600
- tz.transition 1990, 3, :o4, 636516000
- tz.transition 1990, 10, :o5, 656478000
- tz.transition 1991, 3, :o6, 667792800
- tz.transition 1991, 5, :o4, 673588800
- tz.transition 1991, 10, :o5, 687927600
- tz.transition 1992, 3, :o4, 699415200
- tz.transition 1992, 10, :o5, 719377200
- tz.transition 1993, 3, :o4, 731469600
- tz.transition 1999, 10, :o3, 938919600
- tz.transition 2000, 3, :o4, 952052400
- tz.transition 2004, 5, :o6, 1085972400
- tz.transition 2004, 7, :o4, 1090728000
- tz.transition 2007, 12, :o5, 1198983600
- tz.transition 2008, 3, :o4, 1205632800
- tz.transition 2008, 10, :o5, 1224385200
- tz.transition 2009, 3, :o4, 1237082400
- tz.transition 2009, 10, :o5, 1255834800
- tz.transition 2010, 3, :o4, 1269136800
- tz.transition 2010, 10, :o5, 1287284400
- tz.transition 2011, 3, :o4, 1300586400
- tz.transition 2011, 10, :o5, 1318734000
- tz.transition 2012, 3, :o4, 1332036000
- tz.transition 2012, 10, :o5, 1350788400
- tz.transition 2013, 3, :o4, 1363485600
- tz.transition 2013, 10, :o5, 1382238000
- tz.transition 2014, 3, :o4, 1394935200
- tz.transition 2014, 10, :o5, 1413687600
- tz.transition 2015, 3, :o4, 1426384800
- tz.transition 2015, 10, :o5, 1445137200
- tz.transition 2016, 3, :o4, 1458439200
- tz.transition 2016, 10, :o5, 1476586800
- tz.transition 2017, 3, :o4, 1489888800
- tz.transition 2017, 10, :o5, 1508036400
- tz.transition 2018, 3, :o4, 1521338400
- tz.transition 2018, 10, :o5, 1540090800
- tz.transition 2019, 3, :o4, 1552788000
- tz.transition 2019, 10, :o5, 1571540400
- tz.transition 2020, 3, :o4, 1584237600
- tz.transition 2020, 10, :o5, 1602990000
- tz.transition 2021, 3, :o4, 1616292000
- tz.transition 2021, 10, :o5, 1634439600
- tz.transition 2022, 3, :o4, 1647741600
- tz.transition 2022, 10, :o5, 1665889200
- tz.transition 2023, 3, :o4, 1679191200
- tz.transition 2023, 10, :o5, 1697338800
- tz.transition 2024, 3, :o4, 1710640800
- tz.transition 2024, 10, :o5, 1729393200
- tz.transition 2025, 3, :o4, 1742090400
- tz.transition 2025, 10, :o5, 1760842800
- tz.transition 2026, 3, :o4, 1773540000
- tz.transition 2026, 10, :o5, 1792292400
- tz.transition 2027, 3, :o4, 1805594400
- tz.transition 2027, 10, :o5, 1823742000
- tz.transition 2028, 3, :o4, 1837044000
- tz.transition 2028, 10, :o5, 1855191600
- tz.transition 2029, 3, :o4, 1868493600
- tz.transition 2029, 10, :o5, 1887246000
- tz.transition 2030, 3, :o4, 1899943200
- tz.transition 2030, 10, :o5, 1918695600
- tz.transition 2031, 3, :o4, 1931392800
- tz.transition 2031, 10, :o5, 1950145200
- tz.transition 2032, 3, :o4, 1963447200
- tz.transition 2032, 10, :o5, 1981594800
- tz.transition 2033, 3, :o4, 1994896800
- tz.transition 2033, 10, :o5, 2013044400
- tz.transition 2034, 3, :o4, 2026346400
- tz.transition 2034, 10, :o5, 2044494000
- tz.transition 2035, 3, :o4, 2057796000
- tz.transition 2035, 10, :o5, 2076548400
- tz.transition 2036, 3, :o4, 2089245600
- tz.transition 2036, 10, :o5, 2107998000
- tz.transition 2037, 3, :o4, 2120695200
- tz.transition 2037, 10, :o5, 2139447600
- tz.transition 2038, 3, :o4, 29586043, 12
- tz.transition 2038, 10, :o5, 19725709, 8
- tz.transition 2039, 3, :o4, 29590411, 12
- tz.transition 2039, 10, :o5, 19728621, 8
- tz.transition 2040, 3, :o4, 29594779, 12
- tz.transition 2040, 10, :o5, 19731589, 8
- tz.transition 2041, 3, :o4, 29599147, 12
- tz.transition 2041, 10, :o5, 19734501, 8
- tz.transition 2042, 3, :o4, 29603515, 12
- tz.transition 2042, 10, :o5, 19737413, 8
- tz.transition 2043, 3, :o4, 29607883, 12
- tz.transition 2043, 10, :o5, 19740325, 8
- tz.transition 2044, 3, :o4, 29612335, 12
- tz.transition 2044, 10, :o5, 19743237, 8
- tz.transition 2045, 3, :o4, 29616703, 12
- tz.transition 2045, 10, :o5, 19746149, 8
- tz.transition 2046, 3, :o4, 29621071, 12
- tz.transition 2046, 10, :o5, 19749117, 8
- tz.transition 2047, 3, :o4, 29625439, 12
- tz.transition 2047, 10, :o5, 19752029, 8
- tz.transition 2048, 3, :o4, 29629807, 12
- tz.transition 2048, 10, :o5, 19754941, 8
- tz.transition 2049, 3, :o4, 29634259, 12
- tz.transition 2049, 10, :o5, 19757853, 8
- tz.transition 2050, 3, :o4, 29638627, 12
- end
- end
- end
- end
- end
-end
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo.rb
index c8bdbeec5d..c8bdbeec5d 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/data_timezone.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/data_timezone.rb
index 5eccbdf0db..5eccbdf0db 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/data_timezone.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/data_timezone.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/data_timezone_info.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/data_timezone_info.rb
index a45d94554b..a45d94554b 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/data_timezone_info.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/data_timezone_info.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Algiers.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Algiers.rb
index 8c5f25577f..8c5f25577f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Algiers.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Algiers.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Cairo.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Cairo.rb
index 6e6daf3522..6e6daf3522 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Cairo.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Cairo.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Casablanca.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Casablanca.rb
index d1eb5c5724..d1eb5c5724 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Casablanca.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Casablanca.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Harare.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Harare.rb
index 070c95ae0f..070c95ae0f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Harare.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Harare.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Johannesburg.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Johannesburg.rb
index f0af0d8e33..f0af0d8e33 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Johannesburg.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Johannesburg.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Monrovia.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Monrovia.rb
index 40e711fa44..40e711fa44 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Monrovia.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Monrovia.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Nairobi.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Nairobi.rb
index 7b0a2f43be..7b0a2f43be 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Africa/Nairobi.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Africa/Nairobi.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Argentina/Buenos_Aires.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Argentina/Buenos_Aires.rb
index 8f4dd31dbb..8f4dd31dbb 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Argentina/Buenos_Aires.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Argentina/Buenos_Aires.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Argentina/San_Juan.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Argentina/San_Juan.rb
new file mode 100644
index 0000000000..ba8be4705f
--- /dev/null
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Argentina/San_Juan.rb
@@ -0,0 +1,86 @@
+require 'tzinfo/timezone_definition'
+
+module TZInfo
+ module Definitions
+ module America
+ module Argentina
+ module San_Juan
+ include TimezoneDefinition
+
+ timezone 'America/Argentina/San_Juan' do |tz|
+ tz.offset :o0, -16444, 0, :LMT
+ tz.offset :o1, -15408, 0, :CMT
+ tz.offset :o2, -14400, 0, :ART
+ tz.offset :o3, -14400, 3600, :ARST
+ tz.offset :o4, -10800, 0, :ART
+ tz.offset :o5, -10800, 3600, :ARST
+ tz.offset :o6, -14400, 0, :WART
+
+ tz.transition 1894, 10, :o1, 52123666111, 21600
+ tz.transition 1920, 5, :o2, 1453467407, 600
+ tz.transition 1930, 12, :o3, 7278935, 3
+ tz.transition 1931, 4, :o2, 19411461, 8
+ tz.transition 1931, 10, :o3, 7279889, 3
+ tz.transition 1932, 3, :o2, 19414141, 8
+ tz.transition 1932, 11, :o3, 7281038, 3
+ tz.transition 1933, 3, :o2, 19417061, 8
+ tz.transition 1933, 11, :o3, 7282133, 3
+ tz.transition 1934, 3, :o2, 19419981, 8
+ tz.transition 1934, 11, :o3, 7283228, 3
+ tz.transition 1935, 3, :o2, 19422901, 8
+ tz.transition 1935, 11, :o3, 7284323, 3
+ tz.transition 1936, 3, :o2, 19425829, 8
+ tz.transition 1936, 11, :o3, 7285421, 3
+ tz.transition 1937, 3, :o2, 19428749, 8
+ tz.transition 1937, 11, :o3, 7286516, 3
+ tz.transition 1938, 3, :o2, 19431669, 8
+ tz.transition 1938, 11, :o3, 7287611, 3
+ tz.transition 1939, 3, :o2, 19434589, 8
+ tz.transition 1939, 11, :o3, 7288706, 3
+ tz.transition 1940, 3, :o2, 19437517, 8
+ tz.transition 1940, 7, :o3, 7289435, 3
+ tz.transition 1941, 6, :o2, 19441285, 8
+ tz.transition 1941, 10, :o3, 7290848, 3
+ tz.transition 1943, 8, :o2, 19447501, 8
+ tz.transition 1943, 10, :o3, 7293038, 3
+ tz.transition 1946, 3, :o2, 19455045, 8
+ tz.transition 1946, 10, :o3, 7296284, 3
+ tz.transition 1963, 10, :o2, 19506429, 8
+ tz.transition 1963, 12, :o3, 7315136, 3
+ tz.transition 1964, 3, :o2, 19507645, 8
+ tz.transition 1964, 10, :o3, 7316051, 3
+ tz.transition 1965, 3, :o2, 19510565, 8
+ tz.transition 1965, 10, :o3, 7317146, 3
+ tz.transition 1966, 3, :o2, 19513485, 8
+ tz.transition 1966, 10, :o3, 7318241, 3
+ tz.transition 1967, 4, :o2, 19516661, 8
+ tz.transition 1967, 10, :o3, 7319294, 3
+ tz.transition 1968, 4, :o2, 19519629, 8
+ tz.transition 1968, 10, :o3, 7320407, 3
+ tz.transition 1969, 4, :o2, 19522541, 8
+ tz.transition 1969, 10, :o4, 7321499, 3
+ tz.transition 1974, 1, :o5, 128142000
+ tz.transition 1974, 5, :o4, 136605600
+ tz.transition 1988, 12, :o5, 596948400
+ tz.transition 1989, 3, :o4, 605066400
+ tz.transition 1989, 10, :o5, 624423600
+ tz.transition 1990, 3, :o4, 636516000
+ tz.transition 1990, 10, :o5, 656478000
+ tz.transition 1991, 3, :o6, 667792800
+ tz.transition 1991, 5, :o4, 673588800
+ tz.transition 1991, 10, :o5, 687927600
+ tz.transition 1992, 3, :o4, 699415200
+ tz.transition 1992, 10, :o5, 719377200
+ tz.transition 1993, 3, :o4, 731469600
+ tz.transition 1999, 10, :o3, 938919600
+ tz.transition 2000, 3, :o4, 952052400
+ tz.transition 2004, 5, :o6, 1085972400
+ tz.transition 2004, 7, :o4, 1090728000
+ tz.transition 2007, 12, :o5, 1198983600
+ tz.transition 2008, 3, :o4, 1205632800
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Bogota.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Bogota.rb
index ef96435c6a..ef96435c6a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Bogota.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Bogota.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Caracas.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Caracas.rb
index 27392a540a..27392a540a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Caracas.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Caracas.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Chicago.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Chicago.rb
index 0996857cf0..0996857cf0 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Chicago.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Chicago.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Chihuahua.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Chihuahua.rb
index 1710b57c79..1710b57c79 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Chihuahua.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Chihuahua.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Denver.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Denver.rb
index 1c1efb5ff3..1c1efb5ff3 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Denver.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Denver.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Godthab.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Godthab.rb
index 1e05518b0d..1e05518b0d 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Godthab.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Godthab.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Guatemala.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Guatemala.rb
index a2bf73401c..a2bf73401c 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Guatemala.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Guatemala.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Halifax.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Halifax.rb
index d25ae775b3..d25ae775b3 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Halifax.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Halifax.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Indiana/Indianapolis.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Indiana/Indianapolis.rb
index f1430f6c24..f1430f6c24 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Indiana/Indianapolis.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Indiana/Indianapolis.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Juneau.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Juneau.rb
index f646f3f54a..f646f3f54a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Juneau.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Juneau.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/La_Paz.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/La_Paz.rb
index 45c907899f..45c907899f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/La_Paz.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/La_Paz.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Lima.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Lima.rb
index af68ac29f7..af68ac29f7 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Lima.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Lima.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Los_Angeles.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Los_Angeles.rb
index 16007fd675..16007fd675 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Los_Angeles.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Los_Angeles.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Mazatlan.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Mazatlan.rb
index ba9e6efcf1..ba9e6efcf1 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Mazatlan.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Mazatlan.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Mexico_City.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Mexico_City.rb
index 2347fce647..2347fce647 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Mexico_City.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Mexico_City.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Monterrey.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Monterrey.rb
index 5816a9eab1..5816a9eab1 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Monterrey.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Monterrey.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/New_York.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/New_York.rb
index 7d802bd2de..7d802bd2de 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/New_York.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/New_York.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Phoenix.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Phoenix.rb
index b514e0c0f9..b514e0c0f9 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Phoenix.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Phoenix.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Regina.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Regina.rb
index ebdb68814a..ebdb68814a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Regina.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Regina.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Santiago.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Santiago.rb
index 0287c9ebc4..0287c9ebc4 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Santiago.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Santiago.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Sao_Paulo.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Sao_Paulo.rb
index 0524f81c04..0524f81c04 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Sao_Paulo.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Sao_Paulo.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/St_Johns.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/St_Johns.rb
index e4a3599d35..e4a3599d35 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/St_Johns.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/St_Johns.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Tijuana.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Tijuana.rb
index 423059da46..423059da46 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/America/Tijuana.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/America/Tijuana.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Almaty.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Almaty.rb
index 9ee18970f1..9ee18970f1 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Almaty.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Almaty.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Baghdad.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Baghdad.rb
index 774dca1587..774dca1587 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Baghdad.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Baghdad.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Baku.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Baku.rb
index e86340ebfa..e86340ebfa 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Baku.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Baku.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Bangkok.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Bangkok.rb
index 139194e5e5..139194e5e5 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Bangkok.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Bangkok.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Chongqing.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Chongqing.rb
index 8c94b4ba86..8c94b4ba86 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Chongqing.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Chongqing.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Colombo.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Colombo.rb
index f6531fa819..f6531fa819 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Colombo.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Colombo.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Dhaka.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Dhaka.rb
index ccd0265503..ccd0265503 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Dhaka.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Dhaka.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Hong_Kong.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Hong_Kong.rb
index f1edd75ac8..f1edd75ac8 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Hong_Kong.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Hong_Kong.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Irkutsk.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Irkutsk.rb
index 2d47d9580b..2d47d9580b 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Irkutsk.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Irkutsk.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Jakarta.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Jakarta.rb
index cc58fa173b..cc58fa173b 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Jakarta.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Jakarta.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Jerusalem.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Jerusalem.rb
index 9b737b899e..9b737b899e 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Jerusalem.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Jerusalem.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kabul.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kabul.rb
index 669c09790a..669c09790a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kabul.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kabul.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kamchatka.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kamchatka.rb
index 2f1690b3a9..2f1690b3a9 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kamchatka.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kamchatka.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Karachi.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Karachi.rb
index b906cc9893..b906cc9893 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Karachi.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Karachi.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Katmandu.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Katmandu.rb
index 37dbea1f41..37dbea1f41 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Katmandu.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Katmandu.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kolkata.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kolkata.rb
index 1b6ffbd59d..1b6ffbd59d 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kolkata.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kolkata.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Krasnoyarsk.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Krasnoyarsk.rb
index d6c503c155..d6c503c155 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Krasnoyarsk.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Krasnoyarsk.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kuala_Lumpur.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kuala_Lumpur.rb
index 77a0c206fa..77a0c206fa 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kuala_Lumpur.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kuala_Lumpur.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kuwait.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kuwait.rb
index 5bd5283197..5bd5283197 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Kuwait.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Kuwait.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Magadan.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Magadan.rb
index 302093693e..302093693e 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Magadan.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Magadan.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Muscat.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Muscat.rb
index 604f651dfa..604f651dfa 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Muscat.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Muscat.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Novosibirsk.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Novosibirsk.rb
index a4e7796e75..a4e7796e75 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Novosibirsk.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Novosibirsk.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Rangoon.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Rangoon.rb
index 759b82d77a..759b82d77a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Rangoon.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Rangoon.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Riyadh.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Riyadh.rb
index 7add410620..7add410620 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Riyadh.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Riyadh.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Seoul.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Seoul.rb
index 795d2a75df..795d2a75df 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Seoul.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Seoul.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Shanghai.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Shanghai.rb
index 34b13d59ae..34b13d59ae 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Shanghai.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Shanghai.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Singapore.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Singapore.rb
index b323a78f74..b323a78f74 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Singapore.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Singapore.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Taipei.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Taipei.rb
index 3ba12108fb..3ba12108fb 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Taipei.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Taipei.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tashkent.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tashkent.rb
index c205c7934d..c205c7934d 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tashkent.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tashkent.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tbilisi.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tbilisi.rb
index 15792a5651..15792a5651 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tbilisi.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tbilisi.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tehran.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tehran.rb
index d8df964a46..d8df964a46 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tehran.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tehran.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tokyo.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tokyo.rb
index 51c9e16421..51c9e16421 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Tokyo.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Tokyo.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Ulaanbaatar.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Ulaanbaatar.rb
index 2854f5c5fd..2854f5c5fd 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Ulaanbaatar.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Ulaanbaatar.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Urumqi.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Urumqi.rb
index d793ff1341..d793ff1341 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Urumqi.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Urumqi.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Vladivostok.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Vladivostok.rb
index bd9e3d60ec..bd9e3d60ec 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Vladivostok.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Vladivostok.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yakutsk.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yakutsk.rb
index 56435a788f..56435a788f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yakutsk.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yakutsk.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yekaterinburg.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yekaterinburg.rb
index 8ef8df4a41..8ef8df4a41 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yekaterinburg.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yekaterinburg.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yerevan.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yerevan.rb
index e7f160861f..e7f160861f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Asia/Yerevan.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Asia/Yerevan.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/Azores.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/Azores.rb
index 1bd16a75ac..1bd16a75ac 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/Azores.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/Azores.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/Cape_Verde.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/Cape_Verde.rb
index 61c8c15043..61c8c15043 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/Cape_Verde.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/Cape_Verde.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/South_Georgia.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/South_Georgia.rb
index 6a4cbafb9f..6a4cbafb9f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Atlantic/South_Georgia.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Atlantic/South_Georgia.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Adelaide.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Adelaide.rb
index c5d561cc1e..c5d561cc1e 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Adelaide.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Adelaide.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Brisbane.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Brisbane.rb
index dd85ddae94..dd85ddae94 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Brisbane.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Brisbane.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Darwin.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Darwin.rb
index 17de88124d..17de88124d 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Darwin.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Darwin.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Hobart.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Hobart.rb
index 11384b9840..11384b9840 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Hobart.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Hobart.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Melbourne.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Melbourne.rb
index c1304488ea..c1304488ea 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Melbourne.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Melbourne.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Perth.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Perth.rb
index d9e66f14a8..d9e66f14a8 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Perth.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Perth.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Sydney.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Sydney.rb
index 9062bd7c3c..9062bd7c3c 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Australia/Sydney.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Australia/Sydney.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Etc/UTC.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Etc/UTC.rb
index 28b2c6a04c..28b2c6a04c 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Etc/UTC.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Etc/UTC.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Amsterdam.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Amsterdam.rb
index 2d0c95c4bc..2d0c95c4bc 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Amsterdam.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Amsterdam.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Athens.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Athens.rb
index 4e21e535ca..4e21e535ca 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Athens.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Athens.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Belgrade.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Belgrade.rb
index 4dbd893d75..4dbd893d75 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Belgrade.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Belgrade.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Berlin.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Berlin.rb
index 721054236c..721054236c 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Berlin.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Berlin.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Bratislava.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Bratislava.rb
index 7a731a0b6a..7a731a0b6a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Bratislava.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Bratislava.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Brussels.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Brussels.rb
index 6b0a242944..6b0a242944 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Brussels.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Brussels.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Bucharest.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Bucharest.rb
index 521c3c932e..521c3c932e 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Bucharest.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Bucharest.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Budapest.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Budapest.rb
index 1f3a9738b7..1f3a9738b7 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Budapest.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Budapest.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Copenhagen.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Copenhagen.rb
index 47cbaf14a7..47cbaf14a7 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Copenhagen.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Copenhagen.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Dublin.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Dublin.rb
index 0560bb5436..0560bb5436 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Dublin.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Dublin.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Helsinki.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Helsinki.rb
index 13a806bcc7..13a806bcc7 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Helsinki.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Helsinki.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Istanbul.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Istanbul.rb
index 8306c47536..8306c47536 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Istanbul.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Istanbul.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Kiev.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Kiev.rb
index 513d3308be..513d3308be 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Kiev.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Kiev.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Lisbon.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Lisbon.rb
index 1c6d2a3d30..1c6d2a3d30 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Lisbon.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Lisbon.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Ljubljana.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Ljubljana.rb
index a9828e6ef8..a9828e6ef8 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Ljubljana.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Ljubljana.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/London.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/London.rb
index 64ce41e900..64ce41e900 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/London.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/London.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Madrid.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Madrid.rb
index 1fb568239a..1fb568239a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Madrid.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Madrid.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Minsk.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Minsk.rb
index fa15816cc8..fa15816cc8 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Minsk.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Minsk.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Moscow.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Moscow.rb
index ef269b675b..ef269b675b 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Moscow.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Moscow.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Paris.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Paris.rb
index e3236c0ba1..e3236c0ba1 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Paris.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Paris.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Prague.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Prague.rb
index bcabee96c1..bcabee96c1 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Prague.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Prague.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Riga.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Riga.rb
index 784837f758..784837f758 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Riga.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Riga.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Rome.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Rome.rb
index aa7b43d9d2..aa7b43d9d2 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Rome.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Rome.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Sarajevo.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Sarajevo.rb
index 068c5fe6ad..068c5fe6ad 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Sarajevo.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Sarajevo.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Skopje.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Skopje.rb
index 10b71f285e..10b71f285e 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Skopje.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Skopje.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Sofia.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Sofia.rb
index 38a70eceb9..38a70eceb9 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Sofia.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Sofia.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Stockholm.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Stockholm.rb
index 43db70fa61..43db70fa61 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Stockholm.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Stockholm.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Tallinn.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Tallinn.rb
index de5a8569f3..de5a8569f3 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Tallinn.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Tallinn.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Vienna.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Vienna.rb
index 990aabab66..990aabab66 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Vienna.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Vienna.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Vilnius.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Vilnius.rb
index d89d095a75..d89d095a75 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Vilnius.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Vilnius.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Warsaw.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Warsaw.rb
index 7fa51c2691..7fa51c2691 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Warsaw.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Warsaw.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Zagreb.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Zagreb.rb
index ecdd903d28..ecdd903d28 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Europe/Zagreb.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Europe/Zagreb.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Auckland.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Auckland.rb
index a524fd6b6b..a524fd6b6b 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Auckland.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Auckland.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Fiji.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Fiji.rb
index 5fe9bbd9a6..5fe9bbd9a6 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Fiji.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Fiji.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Guam.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Guam.rb
index d4c1a0a682..d4c1a0a682 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Guam.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Guam.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Honolulu.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Honolulu.rb
index 204b226537..204b226537 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Honolulu.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Honolulu.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Majuro.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Majuro.rb
index 32adad92c1..32adad92c1 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Majuro.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Majuro.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Midway.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Midway.rb
index 97784fcc10..97784fcc10 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Midway.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Midway.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Noumea.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Noumea.rb
index 70173db8ab..70173db8ab 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Noumea.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Noumea.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Pago_Pago.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Pago_Pago.rb
index c8fcd7d527..c8fcd7d527 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Pago_Pago.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Pago_Pago.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Port_Moresby.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Port_Moresby.rb
index f06cf6d54f..f06cf6d54f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Port_Moresby.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Port_Moresby.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Tongatapu.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Tongatapu.rb
index 7578d92f38..7578d92f38 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/definitions/Pacific/Tongatapu.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/definitions/Pacific/Tongatapu.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/info_timezone.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/info_timezone.rb
index 001303c594..001303c594 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/info_timezone.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/info_timezone.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/linked_timezone.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/linked_timezone.rb
index f8ec4fca87..f8ec4fca87 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/linked_timezone.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/linked_timezone.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/linked_timezone_info.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/linked_timezone_info.rb
index 8197ff3e81..8197ff3e81 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/linked_timezone_info.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/linked_timezone_info.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/offset_rationals.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/offset_rationals.rb
index b1f10b2b63..b1f10b2b63 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/offset_rationals.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/offset_rationals.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/ruby_core_support.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/ruby_core_support.rb
index 9a0441206b..9a0441206b 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/ruby_core_support.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/ruby_core_support.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/time_or_datetime.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/time_or_datetime.rb
index 264517f3ee..264517f3ee 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/time_or_datetime.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/time_or_datetime.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone.rb
index f87fb6fb70..f87fb6fb70 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_definition.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_definition.rb
index 39ca8bfa53..39ca8bfa53 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_definition.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_definition.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_info.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_info.rb
index 68e38c35fb..68e38c35fb 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_info.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_info.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_offset_info.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_offset_info.rb
index 6a0bbca46f..6a0bbca46f 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_offset_info.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_offset_info.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_period.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_period.rb
index 00888fcfdc..00888fcfdc 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_period.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_period.rb
diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_transition_info.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_transition_info.rb
index 6b0669cc4a..6b0669cc4a 100644
--- a/activesupport/lib/active_support/vendor/tzinfo-0.3.11/tzinfo/timezone_transition_info.rb
+++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.12/tzinfo/timezone_transition_info.rb
diff --git a/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb b/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb
deleted file mode 100644
index ec6dab513f..0000000000
--- a/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb
+++ /dev/null
@@ -1,1021 +0,0 @@
-# = XmlSimple
-#
-# Author:: Maik Schmidt <contact@maik-schmidt.de>
-# Copyright:: Copyright (c) 2003-2006 Maik Schmidt
-# License:: Distributes under the same terms as Ruby.
-#
-require 'rexml/document'
-require 'stringio'
-
-# Easy API to maintain XML (especially configuration files).
-class XmlSimple
- include REXML
-
- @@VERSION = '1.0.11'
-
- # A simple cache for XML documents that were already transformed
- # by xml_in.
- class Cache
- # Creates and initializes a new Cache object.
- def initialize
- @mem_share_cache = {}
- @mem_copy_cache = {}
- end
-
- # Saves a data structure into a file.
- #
- # data::
- # Data structure to be saved.
- # filename::
- # Name of the file belonging to the data structure.
- def save_storable(data, filename)
- cache_file = get_cache_filename(filename)
- File.open(cache_file, "w+") { |f| Marshal.dump(data, f) }
- end
-
- # Restores a data structure from a file. If restoring the data
- # structure failed for any reason, nil will be returned.
- #
- # filename::
- # Name of the file belonging to the data structure.
- def restore_storable(filename)
- cache_file = get_cache_filename(filename)
- return nil unless File::exist?(cache_file)
- return nil unless File::mtime(cache_file).to_i > File::mtime(filename).to_i
- data = nil
- File.open(cache_file) { |f| data = Marshal.load(f) }
- data
- end
-
- # Saves a data structure in a shared memory cache.
- #
- # data::
- # Data structure to be saved.
- # filename::
- # Name of the file belonging to the data structure.
- def save_mem_share(data, filename)
- @mem_share_cache[filename] = [Time::now.to_i, data]
- end
-
- # Restores a data structure from a shared memory cache. You
- # should consider these elements as "read only". If restoring
- # the data structure failed for any reason, nil will be
- # returned.
- #
- # filename::
- # Name of the file belonging to the data structure.
- def restore_mem_share(filename)
- get_from_memory_cache(filename, @mem_share_cache)
- end
-
- # Copies a data structure to a memory cache.
- #
- # data::
- # Data structure to be copied.
- # filename::
- # Name of the file belonging to the data structure.
- def save_mem_copy(data, filename)
- @mem_share_cache[filename] = [Time::now.to_i, Marshal.dump(data)]
- end
-
- # Restores a data structure from a memory cache. If restoring
- # the data structure failed for any reason, nil will be
- # returned.
- #
- # filename::
- # Name of the file belonging to the data structure.
- def restore_mem_copy(filename)
- data = get_from_memory_cache(filename, @mem_share_cache)
- data = Marshal.load(data) unless data.nil?
- data
- end
-
- private
-
- # Returns the "cache filename" belonging to a filename, i.e.
- # the extension '.xml' in the original filename will be replaced
- # by '.stor'. If filename does not have this extension, '.stor'
- # will be appended.
- #
- # filename::
- # Filename to get "cache filename" for.
- def get_cache_filename(filename)
- filename.sub(/(\.xml)?$/, '.stor')
- end
-
- # Returns a cache entry from a memory cache belonging to a
- # certain filename. If no entry could be found for any reason,
- # nil will be returned.
- #
- # filename::
- # Name of the file the cache entry belongs to.
- # cache::
- # Memory cache to get entry from.
- def get_from_memory_cache(filename, cache)
- return nil unless cache[filename]
- return nil unless cache[filename][0] > File::mtime(filename).to_i
- return cache[filename][1]
- end
- end
-
- # Create a "global" cache.
- @@cache = Cache.new
-
- # Creates and initializes a new XmlSimple object.
- #
- # defaults::
- # Default values for options.
- def initialize(defaults = nil)
- unless defaults.nil? || defaults.instance_of?(Hash)
- raise ArgumentError, "Options have to be a Hash."
- end
- @default_options = normalize_option_names(defaults, (KNOWN_OPTIONS['in'] + KNOWN_OPTIONS['out']).uniq)
- @options = Hash.new
- @_var_values = nil
- end
-
- # Converts an XML document in the same way as the Perl module XML::Simple.
- #
- # string::
- # XML source. Could be one of the following:
- #
- # - nil: Tries to load and parse '<scriptname>.xml'.
- # - filename: Tries to load and parse filename.
- # - IO object: Reads from object until EOF is detected and parses result.
- # - XML string: Parses string.
- #
- # options::
- # Options to be used.
- def xml_in(string = nil, options = nil)
- handle_options('in', options)
-
- # If no XML string or filename was supplied look for scriptname.xml.
- if string.nil?
- string = File::basename($0)
- string.sub!(/\.[^.]+$/, '')
- string += '.xml'
-
- directory = File::dirname($0)
- @options['searchpath'].unshift(directory) unless directory.nil?
- end
-
- if string.instance_of?(String)
- if string =~ /<.*?>/m
- @doc = parse(string)
- elsif string == '-'
- @doc = parse($stdin.readlines.to_s)
- else
- filename = find_xml_file(string, @options['searchpath'])
-
- if @options.has_key?('cache')
- @options['cache'].each { |scheme|
- case(scheme)
- when 'storable'
- content = @@cache.restore_storable(filename)
- when 'mem_share'
- content = @@cache.restore_mem_share(filename)
- when 'mem_copy'
- content = @@cache.restore_mem_copy(filename)
- else
- raise ArgumentError, "Unsupported caching scheme: <#{scheme}>."
- end
- return content if content
- }
- end
-
- @doc = load_xml_file(filename)
- end
- elsif string.kind_of?(IO) || string.kind_of?(StringIO)
- @doc = parse(string.readlines.to_s)
- else
- raise ArgumentError, "Could not parse object of type: <#{string.type}>."
- end
-
- result = collapse(@doc.root)
- result = @options['keeproot'] ? merge({}, @doc.root.name, result) : result
- put_into_cache(result, filename)
- result
- end
-
- # This is the functional version of the instance method xml_in.
- def XmlSimple.xml_in(string = nil, options = nil)
- xml_simple = XmlSimple.new
- xml_simple.xml_in(string, options)
- end
-
- # Converts a data structure into an XML document.
- #
- # ref::
- # Reference to data structure to be converted into XML.
- # options::
- # Options to be used.
- def xml_out(ref, options = nil)
- handle_options('out', options)
- if ref.instance_of?(Array)
- ref = { @options['anonymoustag'] => ref }
- end
-
- if @options['keeproot']
- keys = ref.keys
- if keys.size == 1
- ref = ref[keys[0]]
- @options['rootname'] = keys[0]
- end
- elsif @options['rootname'] == ''
- if ref.instance_of?(Hash)
- refsave = ref
- ref = {}
- refsave.each { |key, value|
- if !scalar(value)
- ref[key] = value
- else
- ref[key] = [ value.to_s ]
- end
- }
- end
- end
-
- @ancestors = []
- xml = value_to_xml(ref, @options['rootname'], '')
- @ancestors = nil
-
- if @options['xmldeclaration']
- xml = @options['xmldeclaration'] + "\n" + xml
- end
-
- if @options.has_key?('outputfile')
- if @options['outputfile'].kind_of?(IO)
- return @options['outputfile'].write(xml)
- else
- File.open(@options['outputfile'], "w") { |file| file.write(xml) }
- end
- end
- xml
- end
-
- # This is the functional version of the instance method xml_out.
- def XmlSimple.xml_out(hash, options = nil)
- xml_simple = XmlSimple.new
- xml_simple.xml_out(hash, options)
- end
-
- private
-
- # Declare options that are valid for xml_in and xml_out.
- KNOWN_OPTIONS = {
- 'in' => %w(
- keyattr keeproot forcecontent contentkey noattr
- searchpath forcearray suppressempty anonymoustag
- cache grouptags normalisespace normalizespace
- variables varattr keytosymbol
- ),
- 'out' => %w(
- keyattr keeproot contentkey noattr rootname
- xmldeclaration outputfile noescape suppressempty
- anonymoustag indent grouptags noindent
- )
- }
-
- # Define some reasonable defaults.
- DEF_KEY_ATTRIBUTES = []
- DEF_ROOT_NAME = 'opt'
- DEF_CONTENT_KEY = 'content'
- DEF_XML_DECLARATION = "<?xml version='1.0' standalone='yes'?>"
- DEF_ANONYMOUS_TAG = 'anon'
- DEF_FORCE_ARRAY = true
- DEF_INDENTATION = ' '
- DEF_KEY_TO_SYMBOL = false
-
- # Normalizes option names in a hash, i.e., turns all
- # characters to lower case and removes all underscores.
- # Additionally, this method checks, if an unknown option
- # was used and raises an according exception.
- #
- # options::
- # Hash to be normalized.
- # known_options::
- # List of known options.
- def normalize_option_names(options, known_options)
- return nil if options.nil?
- result = Hash.new
- options.each { |key, value|
- lkey = key.downcase
- lkey.gsub!(/_/, '')
- if !known_options.member?(lkey)
- raise ArgumentError, "Unrecognised option: #{lkey}."
- end
- result[lkey] = value
- }
- result
- end
-
- # Merges a set of options with the default options.
- #
- # direction::
- # 'in': If options should be handled for xml_in.
- # 'out': If options should be handled for xml_out.
- # options::
- # Options to be merged with the default options.
- def handle_options(direction, options)
- @options = options || Hash.new
-
- raise ArgumentError, "Options must be a Hash!" unless @options.instance_of?(Hash)
-
- unless KNOWN_OPTIONS.has_key?(direction)
- raise ArgumentError, "Unknown direction: <#{direction}>."
- end
-
- known_options = KNOWN_OPTIONS[direction]
- @options = normalize_option_names(@options, known_options)
-
- unless @default_options.nil?
- known_options.each { |option|
- unless @options.has_key?(option)
- if @default_options.has_key?(option)
- @options[option] = @default_options[option]
- end
- end
- }
- end
-
- unless @options.has_key?('noattr')
- @options['noattr'] = false
- end
-
- if @options.has_key?('rootname')
- @options['rootname'] = '' if @options['rootname'].nil?
- else
- @options['rootname'] = DEF_ROOT_NAME
- end
-
- if @options.has_key?('xmldeclaration') && @options['xmldeclaration'] == true
- @options['xmldeclaration'] = DEF_XML_DECLARATION
- end
-
- @options['keytosymbol'] = DEF_KEY_TO_SYMBOL unless @options.has_key?('keytosymbol')
-
- if @options.has_key?('contentkey')
- if @options['contentkey'] =~ /^-(.*)$/
- @options['contentkey'] = $1
- @options['collapseagain'] = true
- end
- else
- @options['contentkey'] = DEF_CONTENT_KEY
- end
-
- unless @options.has_key?('normalisespace')
- @options['normalisespace'] = @options['normalizespace']
- end
- @options['normalisespace'] = 0 if @options['normalisespace'].nil?
-
- if @options.has_key?('searchpath')
- unless @options['searchpath'].instance_of?(Array)
- @options['searchpath'] = [ @options['searchpath'] ]
- end
- else
- @options['searchpath'] = []
- end
-
- if @options.has_key?('cache') && scalar(@options['cache'])
- @options['cache'] = [ @options['cache'] ]
- end
-
- @options['anonymoustag'] = DEF_ANONYMOUS_TAG unless @options.has_key?('anonymoustag')
-
- if !@options.has_key?('indent') || @options['indent'].nil?
- @options['indent'] = DEF_INDENTATION
- end
-
- @options['indent'] = '' if @options.has_key?('noindent')
-
- # Special cleanup for 'keyattr' which could be an array or
- # a hash or left to default to array.
- if @options.has_key?('keyattr')
- if !scalar(@options['keyattr'])
- # Convert keyattr => { elem => '+attr' }
- # to keyattr => { elem => ['attr', '+'] }
- if @options['keyattr'].instance_of?(Hash)
- @options['keyattr'].each { |key, value|
- if value =~ /^([-+])?(.*)$/
- @options['keyattr'][key] = [$2, $1 ? $1 : '']
- end
- }
- elsif !@options['keyattr'].instance_of?(Array)
- raise ArgumentError, "'keyattr' must be String, Hash, or Array!"
- end
- else
- @options['keyattr'] = [ @options['keyattr'] ]
- end
- else
- @options['keyattr'] = DEF_KEY_ATTRIBUTES
- end
-
- if @options.has_key?('forcearray')
- if @options['forcearray'].instance_of?(Regexp)
- @options['forcearray'] = [ @options['forcearray'] ]
- end
-
- if @options['forcearray'].instance_of?(Array)
- force_list = @options['forcearray']
- unless force_list.empty?
- @options['forcearray'] = {}
- force_list.each { |tag|
- if tag.instance_of?(Regexp)
- unless @options['forcearray']['_regex'].instance_of?(Array)
- @options['forcearray']['_regex'] = []
- end
- @options['forcearray']['_regex'] << tag
- else
- @options['forcearray'][tag] = true
- end
- }
- else
- @options['forcearray'] = false
- end
- else
- @options['forcearray'] = @options['forcearray'] ? true : false
- end
- else
- @options['forcearray'] = DEF_FORCE_ARRAY
- end
-
- if @options.has_key?('grouptags') && !@options['grouptags'].instance_of?(Hash)
- raise ArgumentError, "Illegal value for 'GroupTags' option - expected a Hash."
- end
-
- if @options.has_key?('variables') && !@options['variables'].instance_of?(Hash)
- raise ArgumentError, "Illegal value for 'Variables' option - expected a Hash."
- end
-
- if @options.has_key?('variables')
- @_var_values = @options['variables']
- elsif @options.has_key?('varattr')
- @_var_values = {}
- end
- end
-
- # Actually converts an XML document element into a data structure.
- #
- # element::
- # The document element to be collapsed.
- def collapse(element)
- result = @options['noattr'] ? {} : get_attributes(element)
-
- if @options['normalisespace'] == 2
- result.each { |k, v| result[k] = normalise_space(v) }
- end
-
- if element.has_elements?
- element.each_element { |child|
- value = collapse(child)
- if empty(value) && (element.attributes.empty? || @options['noattr'])
- next if @options.has_key?('suppressempty') && @options['suppressempty'] == true
- end
- result = merge(result, child.name, value)
- }
- if has_mixed_content?(element)
- # normalisespace?
- content = element.texts.map { |x| x.to_s }
- content = content[0] if content.size == 1
- result[@options['contentkey']] = content
- end
- elsif element.has_text? # i.e. it has only text.
- return collapse_text_node(result, element)
- end
-
- # Turn Arrays into Hashes if key fields present.
- count = fold_arrays(result)
-
- # Disintermediate grouped tags.
- if @options.has_key?('grouptags')
- result.each { |key, value|
- next unless (value.instance_of?(Hash) && (value.size == 1))
- child_key, child_value = value.to_a[0]
- if @options['grouptags'][key] == child_key
- result[key] = child_value
- end
- }
- end
-
- # Fold Hashes containing a single anonymous Array up into just the Array.
- if count == 1
- anonymoustag = @options['anonymoustag']
- if result.has_key?(anonymoustag) && result[anonymoustag].instance_of?(Array)
- return result[anonymoustag]
- end
- end
-
- if result.empty? && @options.has_key?('suppressempty')
- return @options['suppressempty'] == '' ? '' : nil
- end
-
- result
- end
-
- # Collapses a text node and merges it with an existing Hash, if
- # possible.
- # Thanks to Curtis Schofield for reporting a subtle bug.
- #
- # hash::
- # Hash to merge text node value with, if possible.
- # element::
- # Text node to be collapsed.
- def collapse_text_node(hash, element)
- value = node_to_text(element)
- if empty(value) && !element.has_attributes?
- return {}
- end
-
- if element.has_attributes? && !@options['noattr']
- return merge(hash, @options['contentkey'], value)
- else
- if @options['forcecontent']
- return merge(hash, @options['contentkey'], value)
- else
- return value
- end
- end
- end
-
- # Folds all arrays in a Hash.
- #
- # hash::
- # Hash to be folded.
- def fold_arrays(hash)
- fold_amount = 0
- keyattr = @options['keyattr']
- if (keyattr.instance_of?(Array) || keyattr.instance_of?(Hash))
- hash.each { |key, value|
- if value.instance_of?(Array)
- if keyattr.instance_of?(Array)
- hash[key] = fold_array(value)
- else
- hash[key] = fold_array_by_name(key, value)
- end
- fold_amount += 1
- end
- }
- end
- fold_amount
- end
-
- # Folds an Array to a Hash, if possible. Folding happens
- # according to the content of keyattr, which has to be
- # an array.
- #
- # array::
- # Array to be folded.
- def fold_array(array)
- hash = Hash.new
- array.each { |x|
- return array unless x.instance_of?(Hash)
- key_matched = false
- @options['keyattr'].each { |key|
- if x.has_key?(key)
- key_matched = true
- value = x[key]
- return array if value.instance_of?(Hash) || value.instance_of?(Array)
- value = normalise_space(value) if @options['normalisespace'] == 1
- x.delete(key)
- hash[value] = x
- break
- end
- }
- return array unless key_matched
- }
- hash = collapse_content(hash) if @options['collapseagain']
- hash
- end
-
- # Folds an Array to a Hash, if possible. Folding happens
- # according to the content of keyattr, which has to be
- # a Hash.
- #
- # name::
- # Name of the attribute to be folded upon.
- # array::
- # Array to be folded.
- def fold_array_by_name(name, array)
- return array unless @options['keyattr'].has_key?(name)
- key, flag = @options['keyattr'][name]
-
- hash = Hash.new
- array.each { |x|
- if x.instance_of?(Hash) && x.has_key?(key)
- value = x[key]
- return array if value.instance_of?(Hash) || value.instance_of?(Array)
- value = normalise_space(value) if @options['normalisespace'] == 1
- hash[value] = x
- hash[value]["-#{key}"] = hash[value][key] if flag == '-'
- hash[value].delete(key) unless flag == '+'
- else
- $stderr.puts("Warning: <#{name}> element has no '#{key}' attribute.")
- return array
- end
- }
- hash = collapse_content(hash) if @options['collapseagain']
- hash
- end
-
- # Tries to collapse a Hash even more ;-)
- #
- # hash::
- # Hash to be collapsed again.
- def collapse_content(hash)
- content_key = @options['contentkey']
- hash.each_value { |value|
- return hash unless value.instance_of?(Hash) && value.size == 1 && value.has_key?(content_key)
- hash.each_key { |key| hash[key] = hash[key][content_key] }
- }
- hash
- end
-
- # Adds a new key/value pair to an existing Hash. If the key to be added
- # does already exist and the existing value associated with key is not
- # an Array, it will be converted into an Array. Then the new value is
- # appended to that Array.
- #
- # hash::
- # Hash to add key/value pair to.
- # key::
- # Key to be added.
- # value::
- # Value to be associated with key.
- def merge(hash, key, value)
- if value.instance_of?(String)
- value = normalise_space(value) if @options['normalisespace'] == 2
-
- # do variable substitutions
- unless @_var_values.nil? || @_var_values.empty?
- value.gsub!(/\$\{(\w+)\}/) { |x| get_var($1) }
- end
-
- # look for variable definitions
- if @options.has_key?('varattr')
- varattr = @options['varattr']
- if hash.has_key?(varattr)
- set_var(hash[varattr], value)
- end
- end
- end
-
- #patch for converting keys to symbols
- if @options.has_key?('keytosymbol')
- if @options['keytosymbol'] == true
- key = key.to_s.downcase.to_sym
- end
- end
-
- if hash.has_key?(key)
- if hash[key].instance_of?(Array)
- hash[key] << value
- else
- hash[key] = [ hash[key], value ]
- end
- elsif value.instance_of?(Array) # Handle anonymous arrays.
- hash[key] = [ value ]
- else
- if force_array?(key)
- hash[key] = [ value ]
- else
- hash[key] = value
- end
- end
- hash
- end
-
- # Checks, if the 'forcearray' option has to be used for
- # a certain key.
- def force_array?(key)
- return false if key == @options['contentkey']
- return true if @options['forcearray'] == true
- forcearray = @options['forcearray']
- if forcearray.instance_of?(Hash)
- return true if forcearray.has_key?(key)
- return false unless forcearray.has_key?('_regex')
- forcearray['_regex'].each { |x| return true if key =~ x }
- end
- return false
- end
-
- # Converts the attributes array of a document node into a Hash.
- # Returns an empty Hash, if node has no attributes.
- #
- # node::
- # Document node to extract attributes from.
- def get_attributes(node)
- attributes = {}
- node.attributes.each { |n,v| attributes[n] = v }
- attributes
- end
-
- # Determines, if a document element has mixed content.
- #
- # element::
- # Document element to be checked.
- def has_mixed_content?(element)
- if element.has_text? && element.has_elements?
- return true if element.texts.join('') !~ /^\s*$/s
- end
- false
- end
-
- # Called when a variable definition is encountered in the XML.
- # A variable definition looks like
- # <element attrname="name">value</element>
- # where attrname matches the varattr setting.
- def set_var(name, value)
- @_var_values[name] = value
- end
-
- # Called during variable substitution to get the value for the
- # named variable.
- def get_var(name)
- if @_var_values.has_key?(name)
- return @_var_values[name]
- else
- return "${#{name}}"
- end
- end
-
- # Recurses through a data structure building up and returning an
- # XML representation of that structure as a string.
- #
- # ref::
- # Reference to the data structure to be encoded.
- # name::
- # The XML tag name to be used for this item.
- # indent::
- # A string of spaces for use as the current indent level.
- def value_to_xml(ref, name, indent)
- named = !name.nil? && name != ''
- nl = @options.has_key?('noindent') ? '' : "\n"
-
- if !scalar(ref)
- if @ancestors.member?(ref)
- raise ArgumentError, "Circular data structures not supported!"
- end
- @ancestors << ref
- else
- if named
- return [indent, '<', name, '>', @options['noescape'] ? ref.to_s : escape_value(ref.to_s), '</', name, '>', nl].join('')
- else
- return ref.to_s + nl
- end
- end
-
- # Unfold hash to array if possible.
- if ref.instance_of?(Hash) && !ref.empty? && !@options['keyattr'].empty? && indent != ''
- ref = hash_to_array(name, ref)
- end
-
- result = []
- if ref.instance_of?(Hash)
- # Reintermediate grouped values if applicable.
- if @options.has_key?('grouptags')
- ref.each { |key, value|
- if @options['grouptags'].has_key?(key)
- ref[key] = { @options['grouptags'][key] => value }
- end
- }
- end
-
- nested = []
- text_content = nil
- if named
- result << indent << '<' << name
- end
-
- if !ref.empty?
- ref.each { |key, value|
- next if !key.nil? && key[0, 1] == '-'
- if value.nil?
- unless @options.has_key?('suppressempty') && @options['suppressempty'].nil?
- raise ArgumentError, "Use of uninitialized value!"
- end
- value = {}
- end
-
- if !scalar(value) || @options['noattr']
- nested << value_to_xml(value, key, indent + @options['indent'])
- else
- value = value.to_s
- value = escape_value(value) unless @options['noescape']
- if key == @options['contentkey']
- text_content = value
- else
- result << ' ' << key << '="' << value << '"'
- end
- end
- }
- else
- text_content = ''
- end
-
- if !nested.empty? || !text_content.nil?
- if named
- result << '>'
- if !text_content.nil?
- result << text_content
- nested[0].sub!(/^\s+/, '') if !nested.empty?
- else
- result << nl
- end
- if !nested.empty?
- result << nested << indent
- end
- result << '</' << name << '>' << nl
- else
- result << nested
- end
- else
- result << ' />' << nl
- end
- elsif ref.instance_of?(Array)
- ref.each { |value|
- if scalar(value)
- result << indent << '<' << name << '>'
- result << (@options['noescape'] ? value.to_s : escape_value(value.to_s))
- result << '</' << name << '>' << nl
- elsif value.instance_of?(Hash)
- result << value_to_xml(value, name, indent)
- else
- result << indent << '<' << name << '>' << nl
- result << value_to_xml(value, @options['anonymoustag'], indent + @options['indent'])
- result << indent << '</' << name << '>' << nl
- end
- }
- else
- # Probably, this is obsolete.
- raise ArgumentError, "Can't encode a value of type: #{ref.type}."
- end
- @ancestors.pop if !scalar(ref)
- result.join('')
- end
-
- # Checks, if a certain value is a "scalar" value. Whatever
- # that will be in Ruby ... ;-)
- #
- # value::
- # Value to be checked.
- def scalar(value)
- return false if value.instance_of?(Hash) || value.instance_of?(Array)
- return true
- end
-
- # Attempts to unfold a hash of hashes into an array of hashes. Returns
- # a reference to th array on success or the original hash, if unfolding
- # is not possible.
- #
- # parent::
- #
- # hashref::
- # Reference to the hash to be unfolded.
- def hash_to_array(parent, hashref)
- arrayref = []
- hashref.each { |key, value|
- return hashref unless value.instance_of?(Hash)
-
- if @options['keyattr'].instance_of?(Hash)
- return hashref unless @options['keyattr'].has_key?(parent)
- arrayref << { @options['keyattr'][parent][0] => key }.update(value)
- else
- arrayref << { @options['keyattr'][0] => key }.update(value)
- end
- }
- arrayref
- end
-
- # Replaces XML markup characters by their external entities.
- #
- # data::
- # The string to be escaped.
- def escape_value(data)
- Text::normalize(data)
- end
-
- # Removes leading and trailing whitespace and sequences of
- # whitespaces from a string.
- #
- # text::
- # String to be normalised.
- def normalise_space(text)
- text.strip.gsub(/\s\s+/, ' ')
- end
-
- # Checks, if an object is nil, an empty String or an empty Hash.
- # Thanks to Norbert Gawor for a bugfix.
- #
- # value::
- # Value to be checked for emptiness.
- def empty(value)
- case value
- when Hash
- return value.empty?
- when String
- return value !~ /\S/m
- else
- return value.nil?
- end
- end
-
- # Converts a document node into a String.
- # If the node could not be converted into a String
- # for any reason, default will be returned.
- #
- # node::
- # Document node to be converted.
- # default::
- # Value to be returned, if node could not be converted.
- def node_to_text(node, default = nil)
- if node.instance_of?(REXML::Element)
- node.texts.map { |t| t.value }.join('')
- elsif node.instance_of?(REXML::Attribute)
- node.value.nil? ? default : node.value.strip
- elsif node.instance_of?(REXML::Text)
- node.value.strip
- else
- default
- end
- end
-
- # Parses an XML string and returns the according document.
- #
- # xml_string::
- # XML string to be parsed.
- #
- # The following exception may be raised:
- #
- # REXML::ParseException::
- # If the specified file is not wellformed.
- def parse(xml_string)
- Document.new(xml_string)
- end
-
- # Searches in a list of paths for a certain file. Returns
- # the full path to the file, if it could be found. Otherwise,
- # an exception will be raised.
- #
- # filename::
- # Name of the file to search for.
- # searchpath::
- # List of paths to search in.
- def find_xml_file(file, searchpath)
- filename = File::basename(file)
-
- if filename != file
- return file if File::file?(file)
- else
- searchpath.each { |path|
- full_path = File::join(path, filename)
- return full_path if File::file?(full_path)
- }
- end
-
- if searchpath.empty?
- return file if File::file?(file)
- raise ArgumentError, "File does not exist: #{file}."
- end
- raise ArgumentError, "Could not find <#{filename}> in <#{searchpath.join(':')}>"
- end
-
- # Loads and parses an XML configuration file.
- #
- # filename::
- # Name of the configuration file to be loaded.
- #
- # The following exceptions may be raised:
- #
- # Errno::ENOENT::
- # If the specified file does not exist.
- # REXML::ParseException::
- # If the specified file is not wellformed.
- def load_xml_file(filename)
- parse(File.readlines(filename).to_s)
- end
-
- # Caches the data belonging to a certain file.
- #
- # data::
- # Data to be cached.
- # filename::
- # Name of file the data was read from.
- def put_into_cache(data, filename)
- if @options.has_key?('cache')
- @options['cache'].each { |scheme|
- case(scheme)
- when 'storable'
- @@cache.save_storable(data, filename)
- when 'mem_share'
- @@cache.save_mem_share(data, filename)
- when 'mem_copy'
- @@cache.save_mem_copy(data, filename)
- else
- raise ArgumentError, "Unsupported caching scheme: <#{scheme}>."
- end
- }
- end
- end
-end
-
-# vim:sw=2
diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb
index 8f5395fca6..3e2b29b327 100644
--- a/activesupport/lib/active_support/version.rb
+++ b/activesupport/lib/active_support/version.rb
@@ -1,7 +1,7 @@
module ActiveSupport
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 2
+ MINOR = 3
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb
new file mode 100644
index 0000000000..bfc3d7b00b
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini.rb
@@ -0,0 +1,111 @@
+# = XmlMini
+# This is a derivitive work of XmlSimple 1.0.11
+# Author:: Joseph Holsten <joseph@josephholsten.com>
+# Copyright:: Copyright (c) 2008 Joseph Holsten
+# Copyright:: Copyright (c) 2003-2006 Maik Schmidt <contact@maik-schmidt.de>
+# License:: Distributes under the same terms as Ruby.
+module XmlMini
+ extend self
+
+ CONTENT_KEY = '__content__'.freeze
+
+ # Parse an XML Document string into a simple hash
+ #
+ # Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
+ # and uses the defaults from ActiveSupport
+ #
+ # string::
+ # XML Document string to parse
+ def parse(string)
+ require 'rexml/document' unless defined?(REXML::Document)
+ doc = REXML::Document.new(string)
+ merge_element!({}, doc.root)
+ end
+
+ private
+ # Convert an XML element and merge into the hash
+ #
+ # hash::
+ # Hash to merge the converted element into.
+ # element::
+ # XML element to merge into hash
+ def merge_element!(hash, element)
+ merge!(hash, element.name, collapse(element))
+ end
+
+ # Actually converts an XML document element into a data structure.
+ #
+ # element::
+ # The document element to be collapsed.
+ def collapse(element)
+ hash = get_attributes(element)
+
+ if element.has_elements?
+ element.each_element {|child| merge_element!(hash, child) }
+ merge_texts!(hash, element) unless empty_content?(element)
+ hash
+ else
+ merge_texts!(hash, element)
+ end
+ end
+
+ # Merge all the texts of an element into the hash
+ #
+ # hash::
+ # Hash to add the converted emement to.
+ # element::
+ # XML element whose texts are to me merged into the hash
+ def merge_texts!(hash, element)
+ unless element.has_text?
+ hash
+ else
+ # must use value to prevent double-escaping
+ merge!(hash, CONTENT_KEY, element.texts.sum(&:value))
+ end
+ end
+
+ # Adds a new key/value pair to an existing Hash. If the key to be added
+ # already exists and the existing value associated with key is not
+ # an Array, it will be wrapped in an Array. Then the new value is
+ # appended to that Array.
+ #
+ # hash::
+ # Hash to add key/value pair to.
+ # key::
+ # Key to be added.
+ # value::
+ # Value to be associated with key.
+ def merge!(hash, key, value)
+ if hash.has_key?(key)
+ if hash[key].instance_of?(Array)
+ hash[key] << value
+ else
+ hash[key] = [hash[key], value]
+ end
+ elsif value.instance_of?(Array)
+ hash[key] = [value]
+ else
+ hash[key] = value
+ end
+ hash
+ end
+
+ # Converts the attributes array of an XML element into a hash.
+ # Returns an empty Hash if node has no attributes.
+ #
+ # element::
+ # XML element to extract attributes from.
+ def get_attributes(element)
+ attributes = {}
+ element.attributes.each { |n,v| attributes[n] = v }
+ attributes
+ end
+
+ # Determines if a document element has text content
+ #
+ # element::
+ # XML element to be checked.
+ def empty_content?(element)
+ element.texts.join.blank?
+ end
+end
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
index 9d8c252f86..ac362d14c8 100644
--- a/activesupport/test/abstract_unit.rb
+++ b/activesupport/test/abstract_unit.rb
@@ -1,44 +1,20 @@
-# encoding: utf-8
-
+require 'rubygems'
require 'test/unit'
+gem 'mocha', '>= 0.9.3'
+require 'mocha'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
-$:.unshift File.dirname(__FILE__)
require 'active_support'
+require 'active_support/test_case'
-if RUBY_VERSION < '1.9'
- $KCODE = 'UTF8'
-end
-
-def uses_gem(gem_name, test_name, version = '> 0')
- require 'rubygems'
- gem gem_name.to_s, version
- require gem_name.to_s
+def uses_memcached(test_name)
+ require 'memcache'
+ MemCache.new('localhost').stats
yield
-rescue LoadError
- $stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
-end
-
-# Wrap tests that use Mocha and skip if unavailable.
-unless defined? uses_mocha
- def uses_mocha(test_name, &block)
- uses_gem('mocha', test_name, '>= 0.5.5', &block)
- end
-end
-
-unless defined? uses_memcached
- def uses_memcached(test_name)
- require 'memcache'
- MemCache.new('localhost').stats
- yield
- rescue MemCache::MemCacheError
- $stderr.puts "Skipping #{test_name} tests. Start memcached and try again."
- end
+rescue MemCache::MemCacheError
+ $stderr.puts "Skipping #{test_name} tests. Start memcached and try again."
end
-# Show backtraces for deprecated behavior for quicker cleanup.
-ActiveSupport::Deprecation.debug = true
-
def with_kcode(code)
if RUBY_VERSION < '1.9'
begin
@@ -51,3 +27,10 @@ def with_kcode(code)
yield
end
end
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
+
+if RUBY_VERSION < '1.9'
+ $KCODE = 'UTF8'
+end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index cc371b3a7b..d8506de986 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -45,29 +45,27 @@ class CacheStoreSettingTest < Test::Unit::TestCase
end
end
-uses_mocha 'high-level cache store tests' do
- class CacheStoreTest < Test::Unit::TestCase
- def setup
- @cache = ActiveSupport::Cache.lookup_store(:memory_store)
- end
+class CacheStoreTest < Test::Unit::TestCase
+ def setup
+ @cache = ActiveSupport::Cache.lookup_store(:memory_store)
+ end
- def test_fetch_without_cache_miss
- @cache.stubs(:read).with('foo', {}).returns('bar')
- @cache.expects(:write).never
- assert_equal 'bar', @cache.fetch('foo') { 'baz' }
- end
+ def test_fetch_without_cache_miss
+ @cache.stubs(:read).with('foo', {}).returns('bar')
+ @cache.expects(:write).never
+ assert_equal 'bar', @cache.fetch('foo') { 'baz' }
+ end
- def test_fetch_with_cache_miss
- @cache.stubs(:read).with('foo', {}).returns(nil)
- @cache.expects(:write).with('foo', 'baz', {})
- assert_equal 'baz', @cache.fetch('foo') { 'baz' }
- end
+ def test_fetch_with_cache_miss
+ @cache.stubs(:read).with('foo', {}).returns(nil)
+ @cache.expects(:write).with('foo', 'baz', {})
+ assert_equal 'baz', @cache.fetch('foo') { 'baz' }
+ end
- def test_fetch_with_forced_cache_miss
- @cache.expects(:read).never
- @cache.expects(:write).with('foo', 'bar', :force => true)
- @cache.fetch('foo', :force => true) { 'bar' }
- end
+ def test_fetch_with_forced_cache_miss
+ @cache.expects(:read).never
+ @cache.expects(:write).with('foo', 'bar', :force => true)
+ @cache.fetch('foo', :force => true) { 'bar' }
end
end
@@ -160,6 +158,12 @@ uses_memcached 'memcached backed store' do
@cache.read('foo').gsub!(/.*/, 'baz')
assert_equal 'bar', @cache.read('foo')
end
+
+ def test_write_should_return_true_on_success
+ result = @cache.write('foo', 'bar')
+ assert_equal 'bar', @cache.read('foo') # make sure 'foo' was written
+ assert result
+ end
end
class CompressedMemCacheStore < Test::Unit::TestCase
diff --git a/activesupport/test/clean_backtrace_test.rb b/activesupport/test/clean_backtrace_test.rb
new file mode 100644
index 0000000000..ddbc258df1
--- /dev/null
+++ b/activesupport/test/clean_backtrace_test.rb
@@ -0,0 +1,47 @@
+require 'abstract_unit'
+
+class BacktraceCleanerFilterTest < ActiveSupport::TestCase
+ def setup
+ @bc = ActiveSupport::BacktraceCleaner.new
+ @bc.add_filter { |line| line.gsub("/my/prefix", '') }
+ end
+
+ test "backtrace should not contain prefix when it has been filtered out" do
+ assert_equal "/my/class.rb", @bc.clean([ "/my/prefix/my/class.rb" ]).first
+ end
+
+ test "backtrace should contain unaltered lines if they dont match a filter" do
+ assert_equal "/my/other_prefix/my/class.rb", @bc.clean([ "/my/other_prefix/my/class.rb" ]).first
+ end
+
+ test "backtrace should filter all lines in a backtrace" do
+ assert_equal \
+ ["/my/class.rb", "/my/module.rb"],
+ @bc.clean([ "/my/prefix/my/class.rb", "/my/prefix/my/module.rb" ])
+ end
+end
+
+class BacktraceCleanerSilencerTest < ActiveSupport::TestCase
+ def setup
+ @bc = ActiveSupport::BacktraceCleaner.new
+ @bc.add_silencer { |line| line =~ /mongrel/ }
+ end
+
+ test "backtrace should not contain lines that match the silencer" do
+ assert_equal \
+ [ "/other/class.rb" ],
+ @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb" ])
+ end
+end
+
+class BacktraceCleanerFilterAndSilencerTest < ActiveSupport::TestCase
+ def setup
+ @bc = ActiveSupport::BacktraceCleaner.new
+ @bc.add_filter { |line| line.gsub("/mongrel", "") }
+ @bc.add_silencer { |line| line =~ /mongrel/ }
+ end
+
+ test "backtrace should not silence lines that has first had their silence hook filtered out" do
+ assert_equal [ "/class.rb" ], @bc.clean([ "/mongrel/class.rb" ])
+ end
+end \ No newline at end of file
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
index 62a1f61d53..01b243cdb5 100644
--- a/activesupport/test/core_ext/array_ext_test.rb
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -15,17 +15,13 @@ class ArrayExtAccessTests < Test::Unit::TestCase
end
def test_second_through_tenth
- array = (1..10).to_a
+ array = (1..42).to_a
assert_equal array[1], array.second
assert_equal array[2], array.third
assert_equal array[3], array.fourth
assert_equal array[4], array.fifth
- assert_equal array[5], array.sixth
- assert_equal array[6], array.seventh
- assert_equal array[7], array.eighth
- assert_equal array[8], array.ninth
- assert_equal array[9], array.tenth
+ assert_equal array[41], array.forty_two
end
end
@@ -294,16 +290,14 @@ class ArrayExtractOptionsTests < Test::Unit::TestCase
end
end
-uses_mocha "ArrayExtRandomTests" do
- class ArrayExtRandomTests < Test::Unit::TestCase
- def test_random_element_from_array
- assert_nil [].rand
+class ArrayExtRandomTests < Test::Unit::TestCase
+ def test_random_element_from_array
+ assert_nil [].rand
- Kernel.expects(:rand).with(1).returns(0)
- assert_equal 'x', ['x'].rand
+ Kernel.expects(:rand).with(1).returns(0)
+ assert_equal 'x', ['x'].rand
- Kernel.expects(:rand).with(3).returns(1)
- assert_equal 2, [1, 2, 3].rand
- end
+ Kernel.expects(:rand).with(3).returns(1)
+ assert_equal 2, [1, 2, 3].rand
end
end
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index b53c754780..2cedf65153 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -210,50 +210,46 @@ class DateExtCalculationsTest < Test::Unit::TestCase
end
end
- uses_mocha 'past?, today? and future?' do
- def test_today
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, Date.new(1999, 12, 31).today?
- assert_equal true, Date.new(2000,1,1).today?
- assert_equal false, Date.new(2000,1,2).today?
- end
-
- def test_past
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal true, Date.new(1999, 12, 31).past?
- assert_equal false, Date.new(2000,1,1).past?
- assert_equal false, Date.new(2000,1,2).past?
- end
-
- def test_future
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, Date.new(1999, 12, 31).future?
- assert_equal false, Date.new(2000,1,1).future?
- assert_equal true, Date.new(2000,1,2).future?
+ def test_today
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, Date.new(1999, 12, 31).today?
+ assert_equal true, Date.new(2000,1,1).today?
+ assert_equal false, Date.new(2000,1,2).today?
+ end
+
+ def test_past
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal true, Date.new(1999, 12, 31).past?
+ assert_equal false, Date.new(2000,1,1).past?
+ assert_equal false, Date.new(2000,1,2).past?
+ end
+
+ def test_future
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, Date.new(1999, 12, 31).future?
+ assert_equal false, Date.new(2000,1,1).future?
+ assert_equal true, Date.new(2000,1,2).future?
+ end
+
+ def test_current_returns_date_today_when_zone_default_not_set
+ with_env_tz 'US/Central' do
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
+ assert_equal Date.new(1999, 12, 31), Date.today
+ assert_equal Date.new(1999, 12, 31), Date.current
end
end
- uses_mocha 'TestDateCurrent' do
- def test_current_returns_date_today_when_zone_default_not_set
+ def test_current_returns_time_zone_today_when_zone_default_set
+ silence_warnings do # silence warnings raised by tzinfo gem
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Central' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
assert_equal Date.new(1999, 12, 31), Date.today
- assert_equal Date.new(1999, 12, 31), Date.current
- end
- end
-
- def test_current_returns_time_zone_today_when_zone_default_set
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Central' do
- Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
- assert_equal Date.new(1999, 12, 31), Date.today
- assert_equal Date.new(2000, 1, 1), Date.current
- end
+ assert_equal Date.new(2000, 1, 1), Date.current
end
- ensure
- Time.zone_default = nil
end
+ ensure
+ Time.zone_default = nil
end
protected
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index be3cd8b5d6..45eb52c720 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -207,69 +207,65 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_match(/^2080-02-28T15:15:10-06:?00$/, DateTime.civil(2080, 2, 28, 15, 15, 10, -0.25).xmlschema)
end
- uses_mocha 'Test DateTime past?, today? and future?' do
- def test_today_with_offset
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, DateTime.civil(1999,12,31,23,59,59, Rational(-18000, 86400)).today?
- assert_equal true, DateTime.civil(2000,1,1,0,0,0, Rational(-18000, 86400)).today?
- assert_equal true, DateTime.civil(2000,1,1,23,59,59, Rational(-18000, 86400)).today?
- assert_equal false, DateTime.civil(2000,1,2,0,0,0, Rational(-18000, 86400)).today?
- end
-
- def test_today_without_offset
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, DateTime.civil(1999,12,31,23,59,59).today?
- assert_equal true, DateTime.civil(2000,1,1,0).today?
- assert_equal true, DateTime.civil(2000,1,1,23,59,59).today?
- assert_equal false, DateTime.civil(2000,1,2,0).today?
- end
-
- def test_past_with_offset
- DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
- assert_equal true, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).past?
- assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).past?
- assert_equal false, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).past?
- end
-
- def test_past_without_offset
- DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
- assert_equal true, DateTime.civil(2005,2,10,20,30,44).past?
- assert_equal false, DateTime.civil(2005,2,10,20,30,45).past?
- assert_equal false, DateTime.civil(2005,2,10,20,30,46).past?
- end
-
- def test_future_with_offset
- DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
- assert_equal false, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).future?
- assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).future?
- assert_equal true, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).future?
- end
-
- def test_future_without_offset
- DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
- assert_equal false, DateTime.civil(2005,2,10,20,30,44).future?
- assert_equal false, DateTime.civil(2005,2,10,20,30,45).future?
- assert_equal true, DateTime.civil(2005,2,10,20,30,46).future?
- end
+ def test_today_with_offset
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, DateTime.civil(1999,12,31,23,59,59, Rational(-18000, 86400)).today?
+ assert_equal true, DateTime.civil(2000,1,1,0,0,0, Rational(-18000, 86400)).today?
+ assert_equal true, DateTime.civil(2000,1,1,23,59,59, Rational(-18000, 86400)).today?
+ assert_equal false, DateTime.civil(2000,1,2,0,0,0, Rational(-18000, 86400)).today?
+ end
+
+ def test_today_without_offset
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, DateTime.civil(1999,12,31,23,59,59).today?
+ assert_equal true, DateTime.civil(2000,1,1,0).today?
+ assert_equal true, DateTime.civil(2000,1,1,23,59,59).today?
+ assert_equal false, DateTime.civil(2000,1,2,0).today?
+ end
+
+ def test_past_with_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal true, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).past?
+ assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).past?
+ assert_equal false, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).past?
end
- uses_mocha 'TestDateTimeCurrent' do
- def test_current_returns_date_today_when_zone_default_not_set
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
- assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
- end
+ def test_past_without_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal true, DateTime.civil(2005,2,10,20,30,44).past?
+ assert_equal false, DateTime.civil(2005,2,10,20,30,45).past?
+ assert_equal false, DateTime.civil(2005,2,10,20,30,46).past?
+ end
+
+ def test_future_with_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal false, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).future?
+ assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).future?
+ assert_equal true, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).future?
+ end
+
+ def test_future_without_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal false, DateTime.civil(2005,2,10,20,30,44).future?
+ assert_equal false, DateTime.civil(2005,2,10,20,30,45).future?
+ assert_equal true, DateTime.civil(2005,2,10,20,30,46).future?
+ end
+
+ def test_current_returns_date_today_when_zone_default_not_set
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
+ assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
+ end
- def test_current_returns_time_zone_today_when_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
- assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
- end
- ensure
- Time.zone_default = nil
+ def test_current_returns_time_zone_today_when_zone_default_set
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
+ assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
+ ensure
+ Time.zone_default = nil
end
def test_current_without_time_zone
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index 5cd52d8d79..3948006b42 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class DurationTest < Test::Unit::TestCase
+class DurationTest < ActiveSupport::TestCase
def test_inspect
assert_equal '1 month', 1.month.inspect
assert_equal '1 month and 1 day', (1.month + 1.day).inspect
@@ -40,78 +40,76 @@ class DurationTest < Test::Unit::TestCase
assert_equal 86400 * 1.7, 1.7.days
end
- uses_mocha 'TestDurationSinceAndAgoWithCurrentTime' do
- def test_since_and_ago_with_fractional_days
- Time.stubs(:now).returns Time.local(2000)
- # since
- assert_equal 36.hours.since, 1.5.days.since
- assert_equal((24 * 1.7).hours.since, 1.7.days.since)
- # ago
- assert_equal 36.hours.ago, 1.5.days.ago
- assert_equal((24 * 1.7).hours.ago, 1.7.days.ago)
- end
+ def test_since_and_ago_with_fractional_days
+ Time.stubs(:now).returns Time.local(2000)
+ # since
+ assert_equal 36.hours.since, 1.5.days.since
+ assert_equal((24 * 1.7).hours.since, 1.7.days.since)
+ # ago
+ assert_equal 36.hours.ago, 1.5.days.ago
+ assert_equal((24 * 1.7).hours.ago, 1.7.days.ago)
+ end
+
+ def test_since_and_ago_with_fractional_weeks
+ Time.stubs(:now).returns Time.local(2000)
+ # since
+ assert_equal((7 * 36).hours.since, 1.5.weeks.since)
+ assert_equal((7 * 24 * 1.7).hours.since, 1.7.weeks.since)
+ # ago
+ assert_equal((7 * 36).hours.ago, 1.5.weeks.ago)
+ assert_equal((7 * 24 * 1.7).hours.ago, 1.7.weeks.ago)
+ end
+
+ def test_deprecated_fractional_years
+ years_re = /Fractional years are not respected\. Convert value to integer before calling #years\./
+ assert_deprecated(years_re){1.0.years}
+ assert_deprecated(years_re){1.5.years}
+ assert_not_deprecated{1.years}
+ assert_deprecated(years_re){1.0.year}
+ assert_deprecated(years_re){1.5.year}
+ assert_not_deprecated{1.year}
+ end
- def test_since_and_ago_with_fractional_weeks
+ def test_deprecated_fractional_months
+ months_re = /Fractional months are not respected\. Convert value to integer before calling #months\./
+ assert_deprecated(months_re){1.5.months}
+ assert_deprecated(months_re){1.0.months}
+ assert_not_deprecated{1.months}
+ assert_deprecated(months_re){1.5.month}
+ assert_deprecated(months_re){1.0.month}
+ assert_not_deprecated{1.month}
+ end
+
+ def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
+ Time.zone_default = nil
+ with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
- assert_equal((7 * 36).hours.since, 1.5.weeks.since)
- assert_equal((7 * 24 * 1.7).hours.since, 1.7.weeks.since)
+ assert_equal false, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(2000,1,1,0,0,5), 5.seconds.since
# ago
- assert_equal((7 * 36).hours.ago, 1.5.weeks.ago)
- assert_equal((7 * 24 * 1.7).hours.ago, 1.7.weeks.ago)
- end
-
- def test_deprecated_fractional_years
- years_re = /Fractional years are not respected\. Convert value to integer before calling #years\./
- assert_deprecated(years_re){1.0.years}
- assert_deprecated(years_re){1.5.years}
- assert_not_deprecated{1.years}
- assert_deprecated(years_re){1.0.year}
- assert_deprecated(years_re){1.5.year}
- assert_not_deprecated{1.year}
- end
-
- def test_deprecated_fractional_months
- months_re = /Fractional months are not respected\. Convert value to integer before calling #months\./
- assert_deprecated(months_re){1.5.months}
- assert_deprecated(months_re){1.0.months}
- assert_not_deprecated{1.months}
- assert_deprecated(months_re){1.5.month}
- assert_deprecated(months_re){1.0.month}
- assert_not_deprecated{1.month}
+ assert_equal false, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(1999,12,31,23,59,55), 5.seconds.ago
end
+ end
- def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
- Time.zone_default = nil
+ def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
+ silence_warnings do # silence warnings raised by tzinfo gem
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
- assert_equal false, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
- assert_equal Time.local(2000,1,1,0,0,5), 5.seconds.since
+ assert_equal true, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time
+ assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name
# ago
- assert_equal false, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
- assert_equal Time.local(1999,12,31,23,59,55), 5.seconds.ago
+ assert_equal true, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time
+ assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
end
end
-
- def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns Time.local(2000)
- # since
- assert_equal true, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
- assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time
- assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name
- # ago
- assert_equal true, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
- assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time
- assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
- end
- end
- ensure
- Time.zone_default = nil
- end
+ ensure
+ Time.zone_default = nil
end
protected
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index deb9b7544d..92db977a77 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -79,4 +79,15 @@ class EnumerableTests < Test::Unit::TestCase
assert ![ 1, 2 ].many? {|x| x > 1 }
assert [ 1, 2, 2 ].many? {|x| x > 1 }
end
+
+ def test_none
+ assert [].none?
+ assert [nil, false].none?
+ assert ![1].none?
+
+ assert [].none? {|x| x > 1 }
+ assert ![ 2 ].none? {|x| x > 1 }
+ assert ![ 1, 2 ].none? {|x| x > 1 }
+ assert [ 1, 1 ].none? {|x| x > 1 }
+ end
end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 9537f486cb..30cbba26b0 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'builder'
class HashExtTest < Test::Unit::TestCase
def setup
@@ -358,12 +359,10 @@ class HashExtTest < Test::Unit::TestCase
assert_nothing_raised { original.except(:a) }
end
- uses_mocha 'except with expectation' do
- def test_except_with_mocha_expectation_on_original
- original = { :a => 'x', :b => 'y' }
- original.expects(:delete).never
- original.except(:a)
- end
+ def test_except_with_mocha_expectation_on_original
+ original = { :a => 'x', :b => 'y' }
+ original.expects(:delete).never
+ original.except(:a)
end
end
diff --git a/activesupport/test/core_ext/module/model_naming_test.rb b/activesupport/test/core_ext/module/model_naming_test.rb
index fc73fa5c36..d08349dd97 100644
--- a/activesupport/test/core_ext/module/model_naming_test.rb
+++ b/activesupport/test/core_ext/module/model_naming_test.rb
@@ -2,18 +2,18 @@ require 'abstract_unit'
class ModelNamingTest < Test::Unit::TestCase
def setup
- @name = ActiveSupport::ModelName.new('Post::TrackBack')
+ @model_name = ActiveSupport::ModelName.new('Post::TrackBack')
end
def test_singular
- assert_equal 'post_track_back', @name.singular
+ assert_equal 'post_track_back', @model_name.singular
end
def test_plural
- assert_equal 'post_track_backs', @name.plural
+ assert_equal 'post_track_backs', @model_name.plural
end
def test_partial_path
- assert_equal 'post/track_backs/track_back', @name.partial_path
+ assert_equal 'post/track_backs/track_back', @model_name.partial_path
end
end
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index 7fe5d0faee..886f692499 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -106,6 +106,17 @@ class ModuleTest < Test::Unit::TestCase
assert_equal invoice.customer_city, "Chicago"
end
+ def test_delegation_prefix_with_instance_variable
+ assert_raise ArgumentError do
+ Class.new do
+ def initialize(client)
+ @client = client
+ end
+ delegate :name, :address, :to => :@client, :prefix => true
+ end
+ end
+ end
+
def test_parent
assert_equal Yz::Zy, Yz::Zy::Cd.parent
assert_equal Yz, Yz::Zy.parent
diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb
index e88dcb52d5..2f79b6f67f 100644
--- a/activesupport/test/core_ext/object_and_class_ext_test.rb
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -247,3 +247,35 @@ class ObjectInstanceVariableTest < Test::Unit::TestCase
[arg] + instance_exec('bar') { |v| [reverse, v] } }
end
end
+
+class ObjectTryTest < Test::Unit::TestCase
+ def setup
+ @string = "Hello"
+ end
+
+ def test_nonexisting_method
+ method = :undefined_method
+ assert !@string.respond_to?(method)
+ assert_nil @string.try(method)
+ end
+
+ def test_valid_method
+ assert_equal 5, @string.try(:size)
+ end
+
+ def test_valid_private_method
+ class << @string
+ private :size
+ end
+
+ assert_equal 5, @string.try(:size)
+ end
+
+ def test_argument_forwarding
+ assert_equal 'Hey', @string.try(:sub, 'llo', 'y')
+ end
+
+ def test_block_forwarding
+ assert_equal 'Hey', @string.try(:sub, 'llo') { |match| 'y' }
+ end
+end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index b086c957fe..e232bf8384 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -207,7 +207,7 @@ class StringBehaviourTest < Test::Unit::TestCase
end
end
-class CoreExtStringMultibyteTest < Test::Unit::TestCase
+class CoreExtStringMultibyteTest < ActiveSupport::TestCase
UNICODE_STRING = 'こにちわ'
ASCII_STRING = 'ohayo'
BYTE_STRING = "\270\236\010\210\245"
@@ -253,4 +253,4 @@ class CoreExtStringMultibyteTest < Test::Unit::TestCase
assert UNICODE_STRING.mb_chars.kind_of?(String)
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index 11ec1c6cd6..52d6c18dce 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -123,7 +123,7 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
def test_end_of_year
assert_equal Time.local(2007,12,31,23,59,59), Time.local(2007,2,22,10,10,10).end_of_year
assert_equal Time.local(2007,12,31,23,59,59), Time.local(2007,12,31,10,10,10).end_of_year
- end
+ end
def test_beginning_of_year
assert_equal Time.local(2005,1,1,0,0,0), Time.local(2005,2,22,10,10,10).beginning_of_year
@@ -515,16 +515,14 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
assert_equal 31, Time.days_in_month(12, 2005)
end
- uses_mocha 'TestTimeDaysInMonthWithoutYearArg' do
- def test_days_in_month_feb_in_common_year_without_year_arg
- Time.stubs(:now).returns(Time.utc(2007))
- assert_equal 28, Time.days_in_month(2)
- end
+ def test_days_in_month_feb_in_common_year_without_year_arg
+ Time.stubs(:now).returns(Time.utc(2007))
+ assert_equal 28, Time.days_in_month(2)
+ end
- def test_days_in_month_feb_in_leap_year_without_year_arg
- Time.stubs(:now).returns(Time.utc(2008))
- assert_equal 29, Time.days_in_month(2)
- end
+ def test_days_in_month_feb_in_leap_year_without_year_arg
+ Time.stubs(:now).returns(Time.utc(2008))
+ assert_equal 29, Time.days_in_month(2)
end
def test_time_with_datetime_fallback
@@ -572,71 +570,69 @@ class TimeExtCalculationsTest < Test::Unit::TestCase
assert_nothing_raised { Time.now.xmlschema }
end
- uses_mocha 'Test Time past?, today? and future?' do
- def test_today_with_time_local
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, Time.local(1999,12,31,23,59,59).today?
- assert_equal true, Time.local(2000,1,1,0).today?
- assert_equal true, Time.local(2000,1,1,23,59,59).today?
- assert_equal false, Time.local(2000,1,2,0).today?
- end
-
- def test_today_with_time_utc
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, Time.utc(1999,12,31,23,59,59).today?
- assert_equal true, Time.utc(2000,1,1,0).today?
- assert_equal true, Time.utc(2000,1,1,23,59,59).today?
- assert_equal false, Time.utc(2000,1,2,0).today?
- end
-
- def test_past_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
- assert_equal true, Time.local(2005,2,10,15,30,44).past?
- assert_equal false, Time.local(2005,2,10,15,30,45).past?
- assert_equal false, Time.local(2005,2,10,15,30,46).past?
- assert_equal true, Time.utc(2005,2,10,20,30,44).past?
- assert_equal false, Time.utc(2005,2,10,20,30,45).past?
- assert_equal false, Time.utc(2005,2,10,20,30,46).past?
- end
- end
-
- def test_past_with_time_current_as_time_with_zone
- with_env_tz 'US/Eastern' do
- twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
- Time.stubs(:current).returns(twz)
- assert_equal true, Time.local(2005,2,10,10,30,44).past?
- assert_equal false, Time.local(2005,2,10,10,30,45).past?
- assert_equal false, Time.local(2005,2,10,10,30,46).past?
- assert_equal true, Time.utc(2005,2,10,15,30,44).past?
- assert_equal false, Time.utc(2005,2,10,15,30,45).past?
- assert_equal false, Time.utc(2005,2,10,15,30,46).past?
- end
- end
-
- def test_future_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
- assert_equal false, Time.local(2005,2,10,15,30,44).future?
- assert_equal false, Time.local(2005,2,10,15,30,45).future?
- assert_equal true, Time.local(2005,2,10,15,30,46).future?
- assert_equal false, Time.utc(2005,2,10,20,30,44).future?
- assert_equal false, Time.utc(2005,2,10,20,30,45).future?
- assert_equal true, Time.utc(2005,2,10,20,30,46).future?
- end
- end
-
- def test_future_with_time_current_as_time_with_zone
- with_env_tz 'US/Eastern' do
- twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
- Time.stubs(:current).returns(twz)
- assert_equal false, Time.local(2005,2,10,10,30,44).future?
- assert_equal false, Time.local(2005,2,10,10,30,45).future?
- assert_equal true, Time.local(2005,2,10,10,30,46).future?
- assert_equal false, Time.utc(2005,2,10,15,30,44).future?
- assert_equal false, Time.utc(2005,2,10,15,30,45).future?
- assert_equal true, Time.utc(2005,2,10,15,30,46).future?
- end
+ def test_today_with_time_local
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, Time.local(1999,12,31,23,59,59).today?
+ assert_equal true, Time.local(2000,1,1,0).today?
+ assert_equal true, Time.local(2000,1,1,23,59,59).today?
+ assert_equal false, Time.local(2000,1,2,0).today?
+ end
+
+ def test_today_with_time_utc
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, Time.utc(1999,12,31,23,59,59).today?
+ assert_equal true, Time.utc(2000,1,1,0).today?
+ assert_equal true, Time.utc(2000,1,1,23,59,59).today?
+ assert_equal false, Time.utc(2000,1,2,0).today?
+ end
+
+ def test_past_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
+ assert_equal true, Time.local(2005,2,10,15,30,44).past?
+ assert_equal false, Time.local(2005,2,10,15,30,45).past?
+ assert_equal false, Time.local(2005,2,10,15,30,46).past?
+ assert_equal true, Time.utc(2005,2,10,20,30,44).past?
+ assert_equal false, Time.utc(2005,2,10,20,30,45).past?
+ assert_equal false, Time.utc(2005,2,10,20,30,46).past?
+ end
+ end
+
+ def test_past_with_time_current_as_time_with_zone
+ with_env_tz 'US/Eastern' do
+ twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
+ Time.stubs(:current).returns(twz)
+ assert_equal true, Time.local(2005,2,10,10,30,44).past?
+ assert_equal false, Time.local(2005,2,10,10,30,45).past?
+ assert_equal false, Time.local(2005,2,10,10,30,46).past?
+ assert_equal true, Time.utc(2005,2,10,15,30,44).past?
+ assert_equal false, Time.utc(2005,2,10,15,30,45).past?
+ assert_equal false, Time.utc(2005,2,10,15,30,46).past?
+ end
+ end
+
+ def test_future_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
+ assert_equal false, Time.local(2005,2,10,15,30,44).future?
+ assert_equal false, Time.local(2005,2,10,15,30,45).future?
+ assert_equal true, Time.local(2005,2,10,15,30,46).future?
+ assert_equal false, Time.utc(2005,2,10,20,30,44).future?
+ assert_equal false, Time.utc(2005,2,10,20,30,45).future?
+ assert_equal true, Time.utc(2005,2,10,20,30,46).future?
+ end
+ end
+
+ def test_future_with_time_current_as_time_with_zone
+ with_env_tz 'US/Eastern' do
+ twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
+ Time.stubs(:current).returns(twz)
+ assert_equal false, Time.local(2005,2,10,10,30,44).future?
+ assert_equal false, Time.local(2005,2,10,10,30,45).future?
+ assert_equal true, Time.local(2005,2,10,10,30,46).future?
+ assert_equal false, Time.utc(2005,2,10,15,30,44).future?
+ assert_equal false, Time.utc(2005,2,10,15,30,45).future?
+ assert_equal true, Time.utc(2005,2,10,15,30,46).future?
end
end
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 774fd57ee6..dc36336239 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -152,50 +152,48 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal false, @twz.between?(Time.utc(2000,1,1,0,0,1), Time.utc(2000,1,1,0,0,2))
end
- uses_mocha 'TimeWithZone past?, today? and future?' do
- def test_today
- Date.stubs(:current).returns(Date.new(2000, 1, 1))
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(1999,12,31,23,59,59) ).today?
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,0) ).today?
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,23,59,59) ).today?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,2,0) ).today?
- end
-
- def test_past_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past?
- end
- end
-
- def test_past_with_time_current_as_time_with_zone
- twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
- Time.stubs(:current).returns(twz)
+ def test_today
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(1999,12,31,23,59,59) ).today?
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,0) ).today?
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,23,59,59) ).today?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,2,0) ).today?
+ end
+
+ def test_past_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past?
assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past?
assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past?
end
-
- def test_future_with_time_current_as_time_local
- with_env_tz 'US/Eastern' do
- Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future?
- assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future?
- assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future?
- end
- end
-
- def future_with_time_current_as_time_with_zone
- twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
- Time.stubs(:current).returns(twz)
+ end
+
+ def test_past_with_time_current_as_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
+ Time.stubs(:current).returns(twz)
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past?
+ end
+
+ def test_future_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future?
assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future?
assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future?
end
end
+ def future_with_time_current_as_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
+ Time.stubs(:current).returns(twz)
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future?
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future?
+ end
+
def test_eql?
assert @twz.eql?(Time.utc(2000))
assert @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
@@ -399,28 +397,26 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
end
- uses_mocha 'TestDatePartValueMethods' do
- def test_method_missing_with_non_time_return_value
- silence_warnings do # silence warnings raised by tzinfo gem
- @twz.time.expects(:foo).returns('bar')
- assert_equal 'bar', @twz.foo
- end
+ def test_method_missing_with_non_time_return_value
+ silence_warnings do # silence warnings raised by tzinfo gem
+ @twz.time.expects(:foo).returns('bar')
+ assert_equal 'bar', @twz.foo
end
+ end
- def test_date_part_value_methods
- silence_warnings do # silence warnings raised by tzinfo gem
- twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
- twz.expects(:method_missing).never
- assert_equal 1999, twz.year
- assert_equal 12, twz.month
- assert_equal 31, twz.day
- assert_equal 14, twz.hour
- assert_equal 18, twz.min
- assert_equal 17, twz.sec
- assert_equal 500, twz.usec
- assert_equal 5, twz.wday
- assert_equal 365, twz.yday
- end
+ def test_date_part_value_methods
+ silence_warnings do # silence warnings raised by tzinfo gem
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
+ twz.expects(:method_missing).never
+ assert_equal 1999, twz.year
+ assert_equal 12, twz.month
+ assert_equal 31, twz.day
+ assert_equal 14, twz.hour
+ assert_equal 18, twz.min
+ assert_equal 17, twz.sec
+ assert_equal 500, twz.usec
+ assert_equal 5, twz.wday
+ assert_equal 365, twz.yday
end
end
@@ -885,28 +881,26 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal nil, Time.zone
end
- uses_mocha 'TestTimeCurrent' do
- def test_current_returns_time_now_when_zone_default_not_set
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns Time.local(2000)
- assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone)
- assert_equal Time.local(2000), Time.current
- end
+ def test_current_returns_time_now_when_zone_default_not_set
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(2000), Time.current
end
+ end
- def test_current_returns_time_zone_now_when_zone_default_set
- silence_warnings do # silence warnings raised by tzinfo gem
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns Time.local(2000)
- assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
- assert_equal 'Eastern Time (US & Canada)', Time.current.time_zone.name
- assert_equal Time.utc(2000), Time.current.time
- end
+ def test_current_returns_time_zone_now_when_zone_default_set
+ silence_warnings do # silence warnings raised by tzinfo gem
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal 'Eastern Time (US & Canada)', Time.current.time_zone.name
+ assert_equal Time.utc(2000), Time.current.time
end
- ensure
- Time.zone_default = nil
end
+ ensure
+ Time.zone_default = nil
end
protected
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 6c3bd1a4fd..fe04b91f2b 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -694,17 +694,17 @@ class DependenciesTest < Test::Unit::TestCase
with_loading 'autoloading_fixtures' do
ActiveSupport::Dependencies.mechanism = :require
2.times do
- assert_raise(NameError) {"RaisesNameError".constantize}
+ assert_raise(NameError) { assert_equal 123, ::RaisesNameError::FooBarBaz }
end
end
end
def test_autoload_doesnt_shadow_name_error
with_loading 'autoloading_fixtures' do
- assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it hasn't been referenced yet!"
+ Object.send(:remove_const, :RaisesNameError) if defined?(::RaisesNameError)
2.times do
begin
- ::RaisesNameError.object_id
+ ::RaisesNameError::FooBarBaz.object_id
flunk 'should have raised NameError when autoloaded file referenced FooBarBaz'
rescue NameError => e
assert_equal 'uninitialized constant RaisesNameError::FooBarBaz', e.message
@@ -712,9 +712,9 @@ class DependenciesTest < Test::Unit::TestCase
assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!"
end
- assert !defined?(RaisesNameError)
+ assert !defined?(::RaisesNameError)
2.times do
- assert_raise(NameError) { RaisesNameError }
+ assert_raise(NameError) { ::RaisesNameError }
assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!"
end
end
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index 27e9573ce2..73a1f9959c 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -32,7 +32,7 @@ class Deprecatee
end
-class DeprecationTest < Test::Unit::TestCase
+class DeprecationTest < ActiveSupport::TestCase
def setup
# Track the last warning.
@old_behavior = ActiveSupport::Deprecation.behavior
@@ -143,19 +143,21 @@ class DeprecationTest < Test::Unit::TestCase
assert_deprecated(/you now need to do something extra for this one/) { @dtc.d }
end
- def test_assertion_failed_error_doesnt_spout_deprecation_warnings
- error_class = Class.new(StandardError) do
- def message
- ActiveSupport::Deprecation.warn 'warning in error message'
- super
+ unless defined?(::MiniTest)
+ def test_assertion_failed_error_doesnt_spout_deprecation_warnings
+ error_class = Class.new(StandardError) do
+ def message
+ ActiveSupport::Deprecation.warn 'warning in error message'
+ super
+ end
end
- end
- raise error_class.new('hmm')
+ raise error_class.new('hmm')
- rescue => e
- error = Test::Unit::Error.new('testing ur doodz', e)
- assert_not_deprecated { error.message }
- assert_nil @last_message
+ rescue => e
+ error = Test::Unit::Error.new('testing ur doodz', e)
+ assert_not_deprecated { error.message }
+ assert_nil @last_message
+ end
end
end
diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb
index db5bd5e088..cfb8c76d52 100644
--- a/activesupport/test/i18n_test.rb
+++ b/activesupport/test/i18n_test.rb
@@ -6,11 +6,9 @@ class I18nTest < Test::Unit::TestCase
@time = Time.utc(2008, 7, 2, 16, 47, 1)
end
- uses_mocha 'I18nTimeZoneTest' do
- def test_time_zone_localization_with_default_format
- Time.zone.stubs(:now).returns Time.local(2000)
- assert_equal Time.zone.now.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(Time.zone.now)
- end
+ def test_time_zone_localization_with_default_format
+ Time.zone.stubs(:now).returns Time.local(2000)
+ assert_equal Time.zone.now.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(Time.zone.now)
end
def test_date_localization_should_use_default_format
@@ -83,9 +81,9 @@ class I18nTest < Test::Unit::TestCase
def test_to_sentence
assert_equal 'a, b, and c', %w[a b c].to_sentence
- I18n.backend.store_translations 'en-US', :support => { :array => { :skip_last_comma => true } }
+ I18n.backend.store_translations 'en', :support => { :array => { :skip_last_comma => true } }
assert_equal 'a, b and c', %w[a b c].to_sentence
ensure
- I18n.backend.store_translations 'en-US', :support => { :array => { :skip_last_comma => false } }
+ I18n.backend.store_translations 'en', :support => { :array => { :skip_last_comma => false } }
end
end
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index d30852c013..d8c93dc9ae 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -104,6 +104,12 @@ class InflectorTest < Test::Unit::TestCase
end
end
+ def test_parameterize_and_normalize
+ StringToParameterizedAndNormalized.each do |some_string, parameterized_string|
+ assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string))
+ end
+ end
+
def test_parameterize_with_custom_separator
StringToParameterized.each do |some_string, parameterized_string|
assert_equal(parameterized_string.gsub('-', '_'), ActiveSupport::Inflector.parameterize(some_string, '_'))
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
index 3aa18ca781..481c3e835c 100644
--- a/activesupport/test/inflector_test_cases.rb
+++ b/activesupport/test/inflector_test_cases.rb
@@ -147,14 +147,25 @@ module InflectorTestCases
StringToParameterized = {
"Donald E. Knuth" => "donald-e-knuth",
"Random text with *(bad)* characters" => "random-text-with-bad-characters",
- "Malmö" => "malmo",
- "Garçons" => "garcons",
"Allow_Under_Scores" => "allow_under_scores",
"Trailing bad characters!@#" => "trailing-bad-characters",
"!@#Leading bad characters" => "leading-bad-characters",
"Squeeze separators" => "squeeze-separators"
}
+ # Ruby 1.9 doesn't do Unicode normalization yet.
+ if RUBY_VERSION >= '1.9'
+ StringToParameterizedAndNormalized = {
+ "Malmö" => "malm",
+ "Garçons" => "gar-ons"
+ }
+ else
+ StringToParameterizedAndNormalized = {
+ "Malmö" => "malmo",
+ "Garçons" => "garcons"
+ }
+ end
+
UnderscoreToHuman = {
"employee_salary" => "Employee salary",
"employee_id" => "Employee",
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index c070e0d9ed..8ed21cc9ad 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -126,15 +126,13 @@ class TestJSONEncoding < Test::Unit::TestCase
end
end
-uses_mocha 'JsonOptionsTests' do
- class JsonOptionsTests < Test::Unit::TestCase
- def test_enumerable_should_passthrough_options_to_elements
- json_options = { :include => :posts }
- ActiveSupport::JSON.expects(:encode).with(1, json_options)
- ActiveSupport::JSON.expects(:encode).with(2, json_options)
- ActiveSupport::JSON.expects(:encode).with('foo', json_options)
-
- [1, 2, 'foo'].to_json(json_options)
- end
+class JsonOptionsTests < Test::Unit::TestCase
+ def test_enumerable_should_passthrough_options_to_elements
+ json_options = { :include => :posts }
+ ActiveSupport::JSON.expects(:encode).with(1, json_options)
+ ActiveSupport::JSON.expects(:encode).with(2, json_options)
+ ActiveSupport::JSON.expects(:encode).with('foo', json_options)
+
+ [1, 2, 'foo'].to_json(json_options)
end
end
diff --git a/activesupport/test/memoizable_test.rb b/activesupport/test/memoizable_test.rb
index a78ebd9425..069ae27eb2 100644
--- a/activesupport/test/memoizable_test.rb
+++ b/activesupport/test/memoizable_test.rb
@@ -1,218 +1,226 @@
require 'abstract_unit'
-uses_mocha 'Memoizable' do
- class MemoizableTest < Test::Unit::TestCase
- class Person
- extend ActiveSupport::Memoizable
-
- attr_reader :name_calls, :age_calls
- def initialize
- @name_calls = 0
- @age_calls = 0
- end
+class MemoizableTest < Test::Unit::TestCase
+ class Person
+ extend ActiveSupport::Memoizable
- def name
- @name_calls += 1
- "Josh"
- end
+ attr_reader :name_calls, :age_calls
+ def initialize
+ @name_calls = 0
+ @age_calls = 0
+ end
- def name?
- true
- end
- memoize :name?
+ def name
+ @name_calls += 1
+ "Josh"
+ end
- def update(name)
- "Joshua"
- end
- memoize :update
+ def name?
+ true
+ end
+ memoize :name?
- def age
- @age_calls += 1
- nil
- end
+ def update(name)
+ "Joshua"
+ end
+ memoize :update
- memoize :name, :age
+ def age
+ @age_calls += 1
+ nil
end
- class Company
- attr_reader :name_calls
- def initialize
- @name_calls = 0
- end
+ memoize :name, :age
+ end
- def name
- @name_calls += 1
- "37signals"
- end
+ class Company
+ attr_reader :name_calls
+ def initialize
+ @name_calls = 0
end
- module Rates
- extend ActiveSupport::Memoizable
-
- attr_reader :sales_tax_calls
- def sales_tax(price)
- @sales_tax_calls ||= 0
- @sales_tax_calls += 1
- price * 0.1025
- end
- memoize :sales_tax
+ def name
+ @name_calls += 1
+ "37signals"
end
+ end
- class Calculator
- extend ActiveSupport::Memoizable
- include Rates
+ module Rates
+ extend ActiveSupport::Memoizable
- attr_reader :fib_calls
- def initialize
- @fib_calls = 0
- end
+ attr_reader :sales_tax_calls
+ def sales_tax(price)
+ @sales_tax_calls ||= 0
+ @sales_tax_calls += 1
+ price * 0.1025
+ end
+ memoize :sales_tax
+ end
- def fib(n)
- @fib_calls += 1
+ class Calculator
+ extend ActiveSupport::Memoizable
+ include Rates
- if n == 0 || n == 1
- n
- else
- fib(n - 1) + fib(n - 2)
- end
- end
- memoize :fib
+ attr_reader :fib_calls
+ def initialize
+ @fib_calls = 0
+ end
- def counter
- @count ||= 0
- @count += 1
+ def fib(n)
+ @fib_calls += 1
+
+ if n == 0 || n == 1
+ n
+ else
+ fib(n - 1) + fib(n - 2)
end
- memoize :counter
end
+ memoize :fib
- def setup
- @person = Person.new
- @calculator = Calculator.new
+ def counter
+ @count ||= 0
+ @count += 1
end
+ memoize :counter
+ end
- def test_memoization
- assert_equal "Josh", @person.name
- assert_equal 1, @person.name_calls
-
- 3.times { assert_equal "Josh", @person.name }
- assert_equal 1, @person.name_calls
- end
+ def setup
+ @person = Person.new
+ @calculator = Calculator.new
+ end
- def test_memoization_with_punctuation
- assert_equal true, @person.name?
+ def test_memoization
+ assert_equal "Josh", @person.name
+ assert_equal 1, @person.name_calls
- assert_nothing_raised(NameError) do
- @person.memoize_all
- @person.unmemoize_all
- end
- end
+ 3.times { assert_equal "Josh", @person.name }
+ assert_equal 1, @person.name_calls
+ end
- def test_memoization_with_nil_value
- assert_equal nil, @person.age
- assert_equal 1, @person.age_calls
+ def test_memoization_with_punctuation
+ assert_equal true, @person.name?
- 3.times { assert_equal nil, @person.age }
- assert_equal 1, @person.age_calls
+ assert_nothing_raised(NameError) do
+ @person.memoize_all
+ @person.unmemoize_all
end
+ end
- def test_memorized_results_are_immutable
- assert_equal "Josh", @person.name
- assert_raise(ActiveSupport::FrozenObjectError) { @person.name.gsub!("Josh", "Gosh") }
- end
+ def test_memoization_with_nil_value
+ assert_equal nil, @person.age
+ assert_equal 1, @person.age_calls
- def test_reloadable
- counter = @calculator.counter
- assert_equal 1, @calculator.counter
- assert_equal 2, @calculator.counter(:reload)
- assert_equal 2, @calculator.counter
- assert_equal 3, @calculator.counter(true)
- assert_equal 3, @calculator.counter
- end
-
- def test_unmemoize_all
- assert_equal 1, @calculator.counter
+ 3.times { assert_equal nil, @person.age }
+ assert_equal 1, @person.age_calls
+ end
- assert @calculator.instance_variable_get(:@_memoized_counter).any?
- @calculator.unmemoize_all
- assert @calculator.instance_variable_get(:@_memoized_counter).empty?
+ def test_memorized_results_are_immutable
+ assert_equal "Josh", @person.name
+ assert_raise(ActiveSupport::FrozenObjectError) { @person.name.gsub!("Josh", "Gosh") }
+ end
- assert_equal 2, @calculator.counter
- end
+ def test_reloadable
+ counter = @calculator.counter
+ assert_equal 1, @calculator.counter
+ assert_equal 2, @calculator.counter(:reload)
+ assert_equal 2, @calculator.counter
+ assert_equal 3, @calculator.counter(true)
+ assert_equal 3, @calculator.counter
+ end
- def test_memoize_all
- @calculator.memoize_all
- assert @calculator.instance_variable_defined?(:@_memoized_counter)
- end
+ def test_flush_cache
+ assert_equal 1, @calculator.counter
- def test_memoization_cache_is_different_for_each_instance
- assert_equal 1, @calculator.counter
- assert_equal 2, @calculator.counter(:reload)
- assert_equal 1, Calculator.new.counter
- end
+ assert @calculator.instance_variable_get(:@_memoized_counter).any?
+ @calculator.flush_cache(:counter)
+ assert @calculator.instance_variable_get(:@_memoized_counter).empty?
- def test_memoized_is_not_affected_by_freeze
- @person.freeze
- assert_equal "Josh", @person.name
- assert_equal "Joshua", @person.update("Joshua")
- end
+ assert_equal 2, @calculator.counter
+ end
- def test_memoization_with_args
- assert_equal 55, @calculator.fib(10)
- assert_equal 11, @calculator.fib_calls
- end
+ def test_unmemoize_all
+ assert_equal 1, @calculator.counter
- def test_reloadable_with_args
- assert_equal 55, @calculator.fib(10)
- assert_equal 11, @calculator.fib_calls
- assert_equal 55, @calculator.fib(10, :reload)
- assert_equal 12, @calculator.fib_calls
- assert_equal 55, @calculator.fib(10, true)
- assert_equal 13, @calculator.fib_calls
- end
+ assert @calculator.instance_variable_get(:@_memoized_counter).any?
+ @calculator.unmemoize_all
+ assert @calculator.instance_variable_get(:@_memoized_counter).empty?
- def test_object_memoization
- [Company.new, Company.new, Company.new].each do |company|
- company.extend ActiveSupport::Memoizable
- company.memoize :name
+ assert_equal 2, @calculator.counter
+ end
- assert_equal "37signals", company.name
- assert_equal 1, company.name_calls
- assert_equal "37signals", company.name
- assert_equal 1, company.name_calls
- end
- end
+ def test_memoize_all
+ @calculator.memoize_all
+ assert @calculator.instance_variable_defined?(:@_memoized_counter)
+ end
- def test_memoized_module_methods
- assert_equal 1.025, @calculator.sales_tax(10)
- assert_equal 1, @calculator.sales_tax_calls
- assert_equal 1.025, @calculator.sales_tax(10)
- assert_equal 1, @calculator.sales_tax_calls
- assert_equal 2.5625, @calculator.sales_tax(25)
- assert_equal 2, @calculator.sales_tax_calls
- end
+ def test_memoization_cache_is_different_for_each_instance
+ assert_equal 1, @calculator.counter
+ assert_equal 2, @calculator.counter(:reload)
+ assert_equal 1, Calculator.new.counter
+ end
- def test_object_memoized_module_methods
- company = Company.new
- company.extend(Rates)
+ def test_memoized_is_not_affected_by_freeze
+ @person.freeze
+ assert_equal "Josh", @person.name
+ assert_equal "Joshua", @person.update("Joshua")
+ end
- assert_equal 1.025, company.sales_tax(10)
- assert_equal 1, company.sales_tax_calls
- assert_equal 1.025, company.sales_tax(10)
- assert_equal 1, company.sales_tax_calls
- assert_equal 2.5625, company.sales_tax(25)
- assert_equal 2, company.sales_tax_calls
- end
+ def test_memoization_with_args
+ assert_equal 55, @calculator.fib(10)
+ assert_equal 11, @calculator.fib_calls
+ end
- def test_double_memoization
- assert_raise(RuntimeError) { Person.memoize :name }
- person = Person.new
- person.extend ActiveSupport::Memoizable
- assert_raise(RuntimeError) { person.memoize :name }
+ def test_reloadable_with_args
+ assert_equal 55, @calculator.fib(10)
+ assert_equal 11, @calculator.fib_calls
+ assert_equal 55, @calculator.fib(10, :reload)
+ assert_equal 12, @calculator.fib_calls
+ assert_equal 55, @calculator.fib(10, true)
+ assert_equal 13, @calculator.fib_calls
+ end
- company = Company.new
+ def test_object_memoization
+ [Company.new, Company.new, Company.new].each do |company|
company.extend ActiveSupport::Memoizable
company.memoize :name
- assert_raise(RuntimeError) { company.memoize :name }
+
+ assert_equal "37signals", company.name
+ assert_equal 1, company.name_calls
+ assert_equal "37signals", company.name
+ assert_equal 1, company.name_calls
end
end
+
+ def test_memoized_module_methods
+ assert_equal 1.025, @calculator.sales_tax(10)
+ assert_equal 1, @calculator.sales_tax_calls
+ assert_equal 1.025, @calculator.sales_tax(10)
+ assert_equal 1, @calculator.sales_tax_calls
+ assert_equal 2.5625, @calculator.sales_tax(25)
+ assert_equal 2, @calculator.sales_tax_calls
+ end
+
+ def test_object_memoized_module_methods
+ company = Company.new
+ company.extend(Rates)
+
+ assert_equal 1.025, company.sales_tax(10)
+ assert_equal 1, company.sales_tax_calls
+ assert_equal 1.025, company.sales_tax(10)
+ assert_equal 1, company.sales_tax_calls
+ assert_equal 2.5625, company.sales_tax(25)
+ assert_equal 2, company.sales_tax_calls
+ end
+
+ def test_double_memoization
+ assert_raise(RuntimeError) { Person.memoize :name }
+ person = Person.new
+ person.extend ActiveSupport::Memoizable
+ assert_raise(RuntimeError) { person.memoize :name }
+
+ company = Company.new
+ company.extend ActiveSupport::Memoizable
+ company.memoize :name
+ assert_raise(RuntimeError) { company.memoize :name }
+ end
end
diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb
new file mode 100644
index 0000000000..c0b4a4658c
--- /dev/null
+++ b/activesupport/test/message_encryptor_test.rb
@@ -0,0 +1,46 @@
+require 'abstract_unit'
+
+class MessageEncryptorTest < Test::Unit::TestCase
+ def setup
+ @encryptor = ActiveSupport::MessageEncryptor.new(ActiveSupport::SecureRandom.hex(64))
+ @data = {:some=>"data", :now=>Time.now}
+ end
+
+ def test_simple_round_tripping
+ message = @encryptor.encrypt(@data)
+ assert_equal @data, @encryptor.decrypt(message)
+ end
+
+ def test_encrypting_twice_yields_differing_cipher_text
+ first_messqage = @encryptor.encrypt(@data)
+ second_message = @encryptor.encrypt(@data)
+ assert_not_equal first_messqage, second_message
+ end
+
+ def test_messing_with_either_value_causes_failure
+ text, iv = @encryptor.encrypt(@data).split("--")
+ assert_not_decrypted([iv, text] * "--")
+ assert_not_decrypted([text, munge(iv)] * "--")
+ assert_not_decrypted([munge(text), iv] * "--")
+ assert_not_decrypted([munge(text), munge(iv)] * "--")
+ end
+
+ def test_signed_round_tripping
+ message = @encryptor.encrypt_and_sign(@data)
+ assert_equal @data, @encryptor.decrypt_and_verify(message)
+ end
+
+
+ private
+ def assert_not_decrypted(value)
+ assert_raises(ActiveSupport::MessageEncryptor::InvalidMessage) do
+ @encryptor.decrypt(value)
+ end
+ end
+
+ def munge(base64_string)
+ bits = ActiveSupport::Base64.decode64(base64_string)
+ bits.reverse!
+ ActiveSupport::Base64.encode64s(bits)
+ end
+end
diff --git a/activesupport/test/message_verifier_test.rb b/activesupport/test/message_verifier_test.rb
new file mode 100644
index 0000000000..2190308856
--- /dev/null
+++ b/activesupport/test/message_verifier_test.rb
@@ -0,0 +1,25 @@
+require 'abstract_unit'
+
+class MessageVerifierTest < Test::Unit::TestCase
+ def setup
+ @verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!")
+ @data = {:some=>"data", :now=>Time.now}
+ end
+
+ def test_simple_round_tripping
+ message = @verifier.generate(@data)
+ assert_equal @data, @verifier.verify(message)
+ end
+
+ def test_tampered_data_raises
+ data, hash = @verifier.generate(@data).split("--")
+ assert_not_verified("#{data.reverse}--#{hash}")
+ assert_not_verified("#{data}--#{hash.reverse}")
+ end
+
+ def assert_not_verified(message)
+ assert_raises(ActiveSupport::MessageVerifier::InvalidSignature) do
+ @verifier.verify(message)
+ end
+ end
+end
diff --git a/activesupport/test/multibyte_unicode_database_test.rb b/activesupport/test/multibyte_unicode_database_test.rb
index fb415e08d3..405c7c2108 100644
--- a/activesupport/test/multibyte_unicode_database_test.rb
+++ b/activesupport/test/multibyte_unicode_database_test.rb
@@ -1,11 +1,7 @@
# encoding: utf-8
-
require 'abstract_unit'
-uses_mocha "MultibyteUnicodeDatabaseTest" do
-
class MultibyteUnicodeDatabaseTest < Test::Unit::TestCase
-
def setup
@ucd = ActiveSupport::Multibyte::UnicodeDatabase.new
end
@@ -24,5 +20,3 @@ class MultibyteUnicodeDatabaseTest < Test::Unit::TestCase
end
end
end
-
-end \ No newline at end of file
diff --git a/activesupport/test/option_merger_test.rb b/activesupport/test/option_merger_test.rb
index 0d72314880..f26d61617d 100644
--- a/activesupport/test/option_merger_test.rb
+++ b/activesupport/test/option_merger_test.rb
@@ -64,6 +64,14 @@ class OptionMergerTest < Test::Unit::TestCase
end
end
end
+
+ def test_nested_method_with_options_using_lamdba
+ local_lamdba = lambda { { :lambda => true } }
+ with_options(@options) do |o|
+ assert_equal @options.merge(local_lamdba.call),
+ o.method_with_options(local_lamdba).call
+ end
+ end
# Needed when counting objects with the ObjectSpace
def test_option_merger_class_method
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index 98a6ad6b26..17dffbd624 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -61,4 +61,16 @@ class OrderedHashTest < Test::Unit::TestCase
assert_equal false, @ordered_hash.has_value?('ABCABC')
assert_equal false, @ordered_hash.value?('ABCABC')
end
+
+ def test_each_key
+ keys = []
+ @ordered_hash.each_key { |k| keys << k }
+ assert_equal @keys, keys
+ end
+
+ def test_each_value
+ values = []
+ @ordered_hash.each_value { |v| values << v }
+ assert_equal @values, values
+ end
end
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
index 4e253848f6..298037e27c 100644
--- a/activesupport/test/test_test.rb
+++ b/activesupport/test/test_test.rb
@@ -1,7 +1,6 @@
require 'abstract_unit'
-require 'active_support/test_case'
-class AssertDifferenceTest < Test::Unit::TestCase
+class AssertDifferenceTest < ActiveSupport::TestCase
def setup
@object = Class.new do
attr_accessor :num
@@ -66,8 +65,8 @@ class AssertDifferenceTest < Test::Unit::TestCase
@object.increment
end
fail 'should not get to here'
- rescue Test::Unit::AssertionFailedError => e
- assert_equal "<1 + 1> was the expression that failed.\n<3> expected but was\n<2>.", e.message
+ rescue Exception => e
+ assert_equal "<3> expected but was\n<2>.", e.message
end
def test_array_of_expressions_identify_failure_when_message_provided
@@ -75,8 +74,8 @@ class AssertDifferenceTest < Test::Unit::TestCase
@object.increment
end
fail 'should not get to here'
- rescue Test::Unit::AssertionFailedError => e
- assert_equal "something went wrong.\n<1 + 1> was the expression that failed.\n<3> expected but was\n<2>.", e.message
+ rescue Exception => e
+ assert_equal "something went wrong.\n<3> expected but was\n<2>.", e.message
end
else
def default_test; end
@@ -84,15 +83,17 @@ class AssertDifferenceTest < Test::Unit::TestCase
end
# These should always pass
-class NotTestingThingsTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Default
+if ActiveSupport::Testing.const_defined?(:Default)
+ class NotTestingThingsTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Default
+ end
end
class AlsoDoingNothingTest < ActiveSupport::TestCase
end
# Setup and teardown callbacks.
-class SetupAndTeardownTest < Test::Unit::TestCase
+class SetupAndTeardownTest < ActiveSupport::TestCase
setup :reset_callback_record, :foo
teardown :foo, :sentinel, :foo
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index 515ffcf0bf..f80575cfd4 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -51,52 +51,50 @@ class TimeZoneTest < Test::Unit::TestCase
define_method("test_utc_offset_for_#{name}") do
silence_warnings do # silence warnings raised by tzinfo gem
- period = zone.tzinfo.period_for_utc(Time.utc(2006,1,1,0,0,0))
+ period = zone.tzinfo.current_period
assert_equal period.utc_offset, zone.utc_offset
end
end
end
- uses_mocha 'TestTimeZoneNowAndToday' do
- def test_now
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns(Time.local(2000))
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_instance_of ActiveSupport::TimeWithZone, zone.now
- assert_equal Time.utc(2000,1,1,5), zone.now.utc
- assert_equal Time.utc(2000), zone.now.time
- assert_equal zone, zone.now.time_zone
- end
+ def test_now
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns(Time.local(2000))
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_instance_of ActiveSupport::TimeWithZone, zone.now
+ assert_equal Time.utc(2000,1,1,5), zone.now.utc
+ assert_equal Time.utc(2000), zone.now.time
+ assert_equal zone, zone.now.time_zone
end
+ end
- def test_now_enforces_spring_dst_rules
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns(Time.local(2006,4,2,2)) # 2AM springs forward to 3AM
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_equal Time.utc(2006,4,2,3), zone.now.time
- assert_equal true, zone.now.dst?
- end
+ def test_now_enforces_spring_dst_rules
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns(Time.local(2006,4,2,2)) # 2AM springs forward to 3AM
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.utc(2006,4,2,3), zone.now.time
+ assert_equal true, zone.now.dst?
end
+ end
- def test_now_enforces_fall_dst_rules
- with_env_tz 'US/Eastern' do
- Time.stubs(:now).returns(Time.at(1162098000)) # equivalent to 1AM DST
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- assert_equal Time.utc(2006,10,29,1), zone.now.time
- assert_equal true, zone.now.dst?
- end
+ def test_now_enforces_fall_dst_rules
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns(Time.at(1162098000)) # equivalent to 1AM DST
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.utc(2006,10,29,1), zone.now.time
+ assert_equal true, zone.now.dst?
end
+ end
- def test_today
- Time.stubs(:now).returns(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
- assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
- Time.stubs(:now).returns(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
- Time.stubs(:now).returns(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
- Time.stubs(:now).returns(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST
- assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
- end
+ def test_today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
end
def test_local
@@ -206,13 +204,11 @@ class TimeZoneTest < Test::Unit::TestCase
end
end
- uses_mocha 'TestParseWithIncompleteDate' do
- def test_parse_with_incomplete_date
- zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
- zone.stubs(:now).returns zone.local(1999,12,31)
- twz = zone.parse('19:00:00')
- assert_equal Time.utc(1999,12,31,19), twz.time
- end
+ def test_parse_with_incomplete_date
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone.stubs(:now).returns zone.local(1999,12,31)
+ twz = zone.parse('19:00:00')
+ assert_equal Time.utc(1999,12,31,19), twz.time
end
def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
diff --git a/ci/cruise_config.rb b/ci/cruise_config.rb
index ec1c82a8bf..46325f5ebd 100644
--- a/ci/cruise_config.rb
+++ b/ci/cruise_config.rb
@@ -1,5 +1,5 @@
Project.configure do |project|
project.build_command = 'ruby ci/ci_build.rb'
- project.email_notifier.emails = ['thewoolleyman@gmail.com','michael@koziarski.com']
+ project.email_notifier.emails = ['thewoolleyman@gmail.com','michael@koziarski.com', 'david@loudthinking.com', 'jeremy@bitsweat.net', 'josh@joshpeek.com', 'pratiknaik@gmail.com']
project.email_notifier.from = 'thewoolleyman+railsci@gmail.com'
end
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index 058afddbde..ca49c5d1c7 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,4 +1,76 @@
-*2.2.1 [RC2 or 2.2 final]*
+*2.3.0 [Edge]*
+
+* Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally]
+
+ This has been extracted from rg - http://github.com/jeremymcanally/rg
+
+ Example:
+
+ # template.rb
+
+ # Install plugins from git or svn
+ plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git"
+ plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/"
+
+ # Add gems to environment.rb
+ gem "jeremymcanally-context"
+ gem "bluecloth"
+
+ # Vendor file. Data in a string or...
+ vendor("borrowed.rb", <<CODE
+ def helpful_method
+ do_something_helpful_here
+ end
+ CODE
+
+ # ...file data from block return value.
+ # #initializer creates a new initializer file
+ initializer("crypto.rb") do
+ salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}"
+
+ "SPECIAL_SALT = '#{salt}'"
+ end
+
+ Usage:
+
+ To use a template, provide a file path or URL:
+
+ 1. Using a local file :
+
+ rails <application name> -m /path/to/my/template.rb
+
+ 2. Or directly from a URL :
+
+ rails <application name> --template=http://gist.github.com/31208.txt
+
+* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [DHH]
+
+* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 [Damian Janowski/?]
+
+* Added view path support for engines [DHH]
+
+* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [DHH]
+
+* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [DHH]
+
+* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! [Jeremy Kemper]
+
+* Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik]
+
+* "rails <app>" will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. [Yaroslav Markin, Pratik Naik]
+
+* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner]
+
+* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [DHH]
+
+* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. [Jeremy Kemper]
+
+* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH]
+
+* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [DHH]
+
+
+*2.2.1 [RC2] (November 14th, 2008)*
* Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 [Mathias Meyer]
diff --git a/railties/README b/railties/README
index 2af0fb1133..37ec8ea211 100644
--- a/railties/README
+++ b/railties/README
@@ -36,32 +36,19 @@ link:files/vendor/rails/actionpack/README.html.
== Web Servers
-By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise
-Rails will use WEBrick, the webserver that ships with Ruby. When you run script/server,
-Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures
-that you can always get up and running quickly.
+By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
+with a variety of other web servers.
Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
More info at: http://mongrel.rubyforge.org
-If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than
-Mongrel and WEBrick and also suited for production use, but requires additional
-installation and currently only works well on OS X/Unix (Windows users are encouraged
-to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from
-http://www.lighttpd.net.
+Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
+Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
+FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
-And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby
-web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not
-for production.
-
-But of course its also possible to run Rails on any platform that supports FCGI.
-Apache, LiteSpeed, IIS are just a few. For more information on FCGI,
-please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI
-
-
-== Apache .htaccess example
+== Apache .htaccess example for FCGI/CGI
# General Apache options
AddHandler fastcgi-script .fcgi
diff --git a/railties/Rakefile b/railties/Rakefile
index 872ea83ec2..f812b42f1d 100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -44,7 +44,7 @@ BASE_DIRS = %w(
app
config/environments
config/initializers
- components
+ config/locales
db
doc
log
@@ -53,7 +53,6 @@ BASE_DIRS = %w(
public
script
script/performance
- script/process
test
vendor
vendor/plugins
@@ -71,7 +70,7 @@ LOG_FILES = %w( server.log development.log test.log production.log )
HTML_FILES = %w( 422.html 404.html 500.html index.html robots.txt favicon.ico images/rails.png
javascripts/prototype.js javascripts/application.js
javascripts/effects.js javascripts/dragdrop.js javascripts/controls.js )
-BIN_FILES = %w( about console destroy generate performance/benchmarker performance/profiler process/reaper process/spawner process/inspector runner server plugin )
+BIN_FILES = %w( about console destroy generate performance/benchmarker performance/profiler runner server plugin )
VENDOR_LIBS = %w( actionpack activerecord actionmailer activesupport activeresource railties )
@@ -174,9 +173,6 @@ task :copy_dispatches do
copy_with_rewritten_ruby_path("dispatches/dispatch.fcgi", "#{PKG_DESTINATION}/public/dispatch.fcgi")
chmod 0755, "#{PKG_DESTINATION}/public/dispatch.fcgi"
-
- # copy_with_rewritten_ruby_path("dispatches/gateway.cgi", "#{PKG_DESTINATION}/public/gateway.cgi")
- # chmod 0755, "#{PKG_DESTINATION}/public/gateway.cgi"
end
task :copy_html_files do
@@ -184,7 +180,7 @@ task :copy_html_files do
end
task :copy_application do
- cp "helpers/application.rb", "#{PKG_DESTINATION}/app/controllers/application.rb"
+ cp "helpers/application_controller.rb", "#{PKG_DESTINATION}/app/controllers/application_controller.rb"
cp "helpers/application_helper.rb", "#{PKG_DESTINATION}/app/helpers/application_helper.rb"
end
@@ -196,8 +192,12 @@ task :copy_configs do
cp "configs/routes.rb", "#{PKG_DESTINATION}/config/routes.rb"
- cp "configs/initializers/inflections.rb", "#{PKG_DESTINATION}/config/initializers/inflections.rb"
- cp "configs/initializers/mime_types.rb", "#{PKG_DESTINATION}/config/initializers/mime_types.rb"
+ cp "configs/initializers/backtrace_silencers.rb", "#{PKG_DESTINATION}/config/initializers/backtrace_silencers.rb"
+ cp "configs/initializers/inflections.rb", "#{PKG_DESTINATION}/config/initializers/inflections.rb"
+ cp "configs/initializers/mime_types.rb", "#{PKG_DESTINATION}/config/initializers/mime_types.rb"
+ cp "configs/initializers/new_rails_defaults.rb", "#{PKG_DESTINATION}/config/initializers/new_rails_defaults.rb"
+
+ cp "configs/locales/en.yml", "#{PKG_DESTINATION}/config/locales/en.yml"
cp "environments/boot.rb", "#{PKG_DESTINATION}/config/boot.rb"
cp "environments/environment.rb", "#{PKG_DESTINATION}/config/environment.rb"
@@ -283,26 +283,35 @@ task :guides do
template = File.expand_path("doc/guides/source/templates/guides.html.erb")
- ignore = ['icons', 'images', 'templates', 'stylesheets']
+ ignore = ['..', 'icons', 'images', 'templates', 'stylesheets']
ignore << 'active_record_basics.txt'
indexless = ['index.txt', 'authors.txt']
- Dir.entries(source)[2..-1].each do |entry|
+ # Traverse all entries in doc/guides/source/
+ Dir.entries(source).each do |entry|
next if ignore.include?(entry)
if File.directory?(File.join(source, entry))
- input = File.join(source, entry, 'index.txt')
- output = File.join(html, entry)
+ # If the current entry is a directory, then we will want to compile
+ # the 'index.txt' file inside this directory.
+ if entry == '.'
+ input = File.join(source, 'index.txt')
+ output = File.join(html, "index.html")
+ else
+ input = File.join(source, entry, 'index.txt')
+ output = File.join(html, "#{entry}.html")
+ end
else
+ # If the current entry is a file, then we will want to compile this file.
input = File.join(source, entry)
- output = File.join(html, entry).sub(/\.txt$/, '')
+ output = File.join(html, entry).sub(/\.txt$/, '.html')
end
begin
puts "GENERATING => #{output}"
ENV['MANUALSONRAILS_TOC'] = 'no' if indexless.include?(entry)
- Mizuho::Generator.new(input, output, template).start
+ Mizuho::Generator.new(input, :output => output, :template => template).start
rescue Mizuho::GenerationError
STDERR.puts "*** ERROR"
exit 2
@@ -349,11 +358,11 @@ spec = Gem::Specification.new do |s|
EOF
s.add_dependency('rake', '>= 0.8.3')
- s.add_dependency('activesupport', '= 2.2.0' + PKG_BUILD)
- s.add_dependency('activerecord', '= 2.2.0' + PKG_BUILD)
- s.add_dependency('actionpack', '= 2.2.0' + PKG_BUILD)
- s.add_dependency('actionmailer', '= 2.2.0' + PKG_BUILD)
- s.add_dependency('activeresource', '= 2.2.0' + PKG_BUILD)
+ s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
+ s.add_dependency('activerecord', '= 2.3.0' + PKG_BUILD)
+ s.add_dependency('actionpack', '= 2.3.0' + PKG_BUILD)
+ s.add_dependency('actionmailer', '= 2.3.0' + PKG_BUILD)
+ s.add_dependency('activeresource', '= 2.3.0' + PKG_BUILD)
s.rdoc_options << '--exclude' << '.'
s.has_rdoc = false
diff --git a/railties/bin/process/inspector b/railties/bin/process/inspector
deleted file mode 100755
index bf25ad86d1..0000000000
--- a/railties/bin/process/inspector
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/usr/bin/env ruby
-require File.dirname(__FILE__) + '/../../config/boot'
-require 'commands/process/inspector'
diff --git a/railties/bin/process/reaper b/railties/bin/process/reaper
deleted file mode 100755
index c77f04535f..0000000000
--- a/railties/bin/process/reaper
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/usr/bin/env ruby
-require File.dirname(__FILE__) + '/../../config/boot'
-require 'commands/process/reaper'
diff --git a/railties/bin/process/spawner b/railties/bin/process/spawner
deleted file mode 100755
index 7118f3983c..0000000000
--- a/railties/bin/process/spawner
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/usr/bin/env ruby
-require File.dirname(__FILE__) + '/../../config/boot'
-require 'commands/process/spawner'
diff --git a/railties/bin/rails b/railties/bin/rails
index ae0cc8adca..6a0c675206 100755
--- a/railties/bin/rails
+++ b/railties/bin/rails
@@ -8,6 +8,7 @@ if %w(--version -v).include? ARGV.first
end
freeze = ARGV.any? { |option| %w(--freeze -f).include?(option) }
+
app_path = ARGV.first
require File.dirname(__FILE__) + '/../lib/rails_generator'
diff --git a/railties/builtin/rails_info/rails/info.rb b/railties/builtin/rails_info/rails/info.rb
index 4cbd2cca4a..7b6f09ac69 100644
--- a/railties/builtin/rails_info/rails/info.rb
+++ b/railties/builtin/rails_info/rails/info.rb
@@ -20,13 +20,13 @@ module Rails
rescue Exception
end
- def components
+ def frameworks
%w( active_record action_pack active_resource action_mailer active_support )
end
- def component_version(component)
- require "#{component}/version"
- "#{component.classify}::VERSION::STRING".constantize
+ def framework_version(framework)
+ require "#{framework}/version"
+ "#{framework.classify}::VERSION::STRING".constantize
end
def edge_rails_revision(info = git_info)
@@ -90,11 +90,11 @@ module Rails
Rails::VERSION::STRING
end
- # Versions of each Rails component (Active Record, Action Pack,
+ # Versions of each Rails framework (Active Record, Action Pack,
# Active Resource, Action Mailer, and Active Support).
- components.each do |component|
- property "#{component.titlecase} version" do
- component_version(component)
+ frameworks.each do |framework|
+ property "#{framework.titlecase} version" do
+ framework_version(framework)
end
end
diff --git a/railties/config.ru b/railties/config.ru
deleted file mode 100644
index 43492a2dcc..0000000000
--- a/railties/config.ru
+++ /dev/null
@@ -1,17 +0,0 @@
-# Rackup Configuration
-#
-# Start Rails mongrel server with rackup
-# $ rackup -p 3000 config.ru
-#
-# Start server with webrick (or any compatible Rack server) instead
-# $ rackup -p 3000 -s webrick config.ru
-
-# Require your environment file to bootstrap Rails
-require File.dirname(__FILE__) + '/config/environment'
-
-# Static server middleware
-# You can remove this extra check if you use an asset server
-use Rails::Rack::Static
-
-# Dispatch the request
-run ActionController::Dispatcher.new
diff --git a/railties/configs/apache.conf b/railties/configs/apache.conf
deleted file mode 100644
index d9d211c058..0000000000
--- a/railties/configs/apache.conf
+++ /dev/null
@@ -1,40 +0,0 @@
-# General Apache options
-AddHandler fastcgi-script .fcgi
-AddHandler cgi-script .cgi
-Options +FollowSymLinks +ExecCGI
-
-# If you don't want Rails to look in certain directories,
-# use the following rewrite rules so that Apache won't rewrite certain requests
-#
-# Example:
-# RewriteCond %{REQUEST_URI} ^/notrails.*
-# RewriteRule .* - [L]
-
-# Redirect all requests not available on the filesystem to Rails
-# By default the cgi dispatcher is used which is very slow
-#
-# For better performance replace the dispatcher with the fastcgi one
-#
-# Example:
-# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
-RewriteEngine On
-
-# If your Rails application is accessed via an Alias directive,
-# then you MUST also set the RewriteBase in this htaccess file.
-#
-# Example:
-# Alias /myrailsapp /path/to/myrailsapp/public
-# RewriteBase /myrailsapp
-
-RewriteRule ^$ index.html [QSA]
-RewriteRule ^([^.]+)$ $1.html [QSA]
-RewriteCond %{REQUEST_FILENAME} !-f
-RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
-
-# In case Rails experiences terminal errors
-# Instead of displaying this message you can supply a file here which will be rendered instead
-#
-# Example:
-# ErrorDocument 500 /500.html
-
-ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
diff --git a/railties/configs/initializers/backtrace_silencers.rb b/railties/configs/initializers/backtrace_silencers.rb
new file mode 100644
index 0000000000..c2169ed01c
--- /dev/null
+++ b/railties/configs/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying do debug a problem that might steem from framework code.
+# Rails.backtrace_cleaner.remove_silencers! \ No newline at end of file
diff --git a/railties/configs/initializers/new_rails_defaults.rb b/railties/configs/initializers/new_rails_defaults.rb
index 78e0117cc4..8ec3186c84 100644
--- a/railties/configs/initializers/new_rails_defaults.rb
+++ b/railties/configs/initializers/new_rails_defaults.rb
@@ -1,3 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
diff --git a/railties/configs/initializers/session_store.rb b/railties/configs/initializers/session_store.rb
new file mode 100644
index 0000000000..40179e0aa3
--- /dev/null
+++ b/railties/configs/initializers/session_store.rb
@@ -0,0 +1,15 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying cookie session data integrity.
+# If you change this key, all old sessions 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.session = {
+ :session_key => '_<%= app_name %>_session',
+ :secret => '<%= app_secret %>'
+}
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rake db:sessions:create")
+# ActionController::Base.session_store = :active_record_store
diff --git a/railties/configs/lighttpd.conf b/railties/configs/lighttpd.conf
deleted file mode 100644
index ed68d714bb..0000000000
--- a/railties/configs/lighttpd.conf
+++ /dev/null
@@ -1,54 +0,0 @@
-# Default configuration file for the lighttpd web server
-# Start using ./script/server lighttpd
-
-server.bind = "0.0.0.0"
-server.port = 3000
-
-server.modules = ( "mod_rewrite", "mod_accesslog", "mod_fastcgi", "mod_compress", "mod_expire" )
-
-server.error-handler-404 = "/dispatch.fcgi"
-server.pid-file = CWD + "/tmp/pids/lighttpd.pid"
-server.document-root = CWD + "/public/"
-
-server.errorlog = CWD + "/log/lighttpd.error.log"
-accesslog.filename = CWD + "/log/lighttpd.access.log"
-
-url.rewrite = ( "^/$" => "index.html", "^([^.]+)$" => "$1.html" )
-
-compress.filetype = ( "text/plain", "text/html", "text/css", "text/javascript" )
-compress.cache-dir = CWD + "/tmp/cache"
-
-expire.url = ( "/favicon.ico" => "access 3 days",
- "/images/" => "access 3 days",
- "/stylesheets/" => "access 3 days",
- "/javascripts/" => "access 3 days" )
-
-
-# Change *-procs to 2 if you need to use Upload Progress or other tasks that
-# *need* to execute a second request while the first is still pending.
-fastcgi.server = ( ".fcgi" => ( "localhost" => (
- "min-procs" => 1,
- "max-procs" => 1,
- "socket" => CWD + "/tmp/sockets/fcgi.socket",
- "bin-path" => CWD + "/public/dispatch.fcgi",
- "bin-environment" => ( "RAILS_ENV" => "development" )
-) ) )
-
-mimetype.assign = (
- ".css" => "text/css",
- ".gif" => "image/gif",
- ".htm" => "text/html",
- ".html" => "text/html",
- ".jpeg" => "image/jpeg",
- ".jpg" => "image/jpeg",
- ".js" => "text/javascript",
- ".png" => "image/png",
- ".swf" => "application/x-shockwave-flash",
- ".txt" => "text/plain"
-)
-
-# Making sure file uploads above 64k always work when using IE or Safari
-# For more information, see http://trac.lighttpd.net/trac/ticket/360
-$HTTP["useragent"] =~ "^(.*MSIE.*)|(.*AppleWebKit.*)$" {
- server.max-keep-alive-requests = 0
-}
diff --git a/railties/configs/locales/en.yml b/railties/configs/locales/en.yml
new file mode 100644
index 0000000000..f265c068d8
--- /dev/null
+++ b/railties/configs/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world" \ No newline at end of file
diff --git a/railties/dispatches/config.ru b/railties/dispatches/config.ru
new file mode 100644
index 0000000000..acbfe4e9ae
--- /dev/null
+++ b/railties/dispatches/config.ru
@@ -0,0 +1,7 @@
+# Rack Dispatcher
+
+# Require your environment file to bootstrap Rails
+require File.dirname(__FILE__) + '/config/environment'
+
+# Dispatch the request
+run ActionController::Dispatcher.new
diff --git a/railties/doc/README_FOR_APP b/railties/doc/README_FOR_APP
index fe41f5cc24..e33b85817b 100644
--- a/railties/doc/README_FOR_APP
+++ b/railties/doc/README_FOR_APP
@@ -1,2 +1,5 @@
-Use this README file to introduce your application and point to useful places in the API for learning more.
-Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
+To build the guides:
+
+* Install source-highlighter (http://www.gnu.org/software/src-highlite/source-highlight.html)
+* Install the mizuho gem (http://github.com/FooBarWidget/mizuho/tree/master)
+* Run `rake guides` from the railties directory \ No newline at end of file
diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html
index c68f10ad5a..68b8188f7c 100644
--- a/railties/doc/guides/html/2_2_release_notes.html
+++ b/railties/doc/guides/html/2_2_release_notes.html
@@ -243,6 +243,8 @@ ul#navMain {
<li><a href="#_method_arrays_for_member_or_collection_routes">Method Arrays for Member or Collection Routes</a></li>
+ <li><a href="#_resources_with_specific_actions">Resources With Specific Actions</a></li>
+
<li><a href="#_other_action_controller_changes">Other Action Controller Changes</a></li>
</ul>
@@ -407,7 +409,7 @@ More information :
</li>
</ul></div>
<div class="para"><p>All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.</p></div>
-<div class="para"><p>If you want to these generate guides locally, inside your application:</p></div>
+<div class="para"><p>If you want to generate these guides locally, inside your application:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -525,7 +527,7 @@ More information :
<div class="sectionbody">
<div class="para"><p>There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.</p></div>
<h3 id="_transactional_migrations">5.1. Transactional Migrations</h3>
-<div class="para"><p>Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by <tt>rake db:migrate:redo</tt> after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported <strong>on PostgreSQL only</strong>. The code is extensible to other database types in the future.</p></div>
+<div class="para"><p>Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by <tt>rake db:migrate:redo</tt> after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -542,6 +544,11 @@ More information:
<a href="http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/">DDL Transactions</a>
</p>
</li>
+<li>
+<p>
+<a href="http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/">A major milestone for DB2 on Rails</a>
+</p>
+</li>
</ul></div>
</li>
</ul></div>
@@ -693,9 +700,9 @@ Counter cache columns (for associations declared with <tt>:counter_cache &#8658;
</div>
<h2 id="_action_controller">6. Action Controller</h2>
<div class="sectionbody">
-<div class="para"><p>On the controller side, there are a couple of changes that will help tidy up your routes.</p></div>
+<div class="para"><p>On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.</p></div>
<h3 id="_shallow_route_nesting">6.1. Shallow Route Nesting</h3>
-<div class="para"><p>Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you <em>can</em> supply more information.</p></div>
+<div class="para"><p>Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -756,8 +763,24 @@ Lead Contributor: <a href="http://brennandunn.com/">Brennan Dunn</a>
</p>
</li>
</ul></div>
-<div class="para"><p>Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions.</p></div>
-<h3 id="_other_action_controller_changes">6.3. Other Action Controller Changes</h3>
+<h3 id="_resources_with_specific_actions">6.3. Resources With Specific Actions</h3>
+<div class="para"><p>By default, when you use <tt>map.resources</tt> to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the <tt>:only</tt> and <tt>:except</tt> options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special <tt>:all</tt> or <tt>:none</tt> options. These options are inherited by nested resources.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>index<span style="color: #990000">,</span> <span style="color: #990000">:</span>show<span style="color: #990000">]</span>
+map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>except <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>destroy
+</tt></pre></div></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Lead Contributor: <a href="http://experthuman.com/">Tom Stuart</a>
+</p>
+</li>
+</ul></div>
+<h3 id="_other_action_controller_changes">6.4. Other Action Controller Changes</h3>
<div class="ilist"><ul>
<li>
<p>
@@ -789,6 +812,16 @@ Rails now supports HTTP-only cookies (and uses them for sessions), which help mi
<tt>render</tt> now supports a <tt>:js</tt> option to render plain vanilla javascript with the right mime type.
</p>
</li>
+<li>
+<p>
+Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
+</p>
+</li>
+<li>
+<p>
+Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling <tt>polymorphic_path([@project, @date, @area])</tt> with a nil date will give you <tt>project_area_path</tt>.
+</p>
+</li>
</ul></div>
</div>
<h2 id="_action_view">7. Action View</h2>
@@ -833,6 +866,7 @@ More information:
</ul></div>
</li>
</ul></div>
+<div class="para"><p>Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.</p></div>
</div>
<h2 id="_active_support">9. Active Support</h2>
<div class="sectionbody">
@@ -1071,7 +1105,7 @@ Wrapped <tt>Rails.env</tt> in <tt>StringInquirer</tt> so you can do <tt>Rails.en
</li>
<li>
<p>
-<tt>script/generate</tt> works without deprecation warnings when RubyGems 1.3.0 is present
+To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.
</p>
</li>
</ul></div>
diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html
index 32ddbe1f60..66563bf1a3 100644
--- a/railties/doc/guides/html/actioncontroller_basics.html
+++ b/railties/doc/guides/html/actioncontroller_basics.html
@@ -199,18 +199,20 @@ ul#navMain {
<h2>Chapters</h2>
<ol>
<li>
- <a href="#_what_does_a_controller_do">What does a controller do?</a>
+ <a href="#_what_does_a_controller_do">What Does a Controller do?</a>
</li>
<li>
- <a href="#_methods_and_actions">Methods and actions</a>
+ <a href="#_methods_and_actions">Methods and Actions</a>
</li>
<li>
<a href="#_parameters">Parameters</a>
<ul>
- <li><a href="#_hash_and_array_parameters">Hash and array parameters</a></li>
+ <li><a href="#_hash_and_array_parameters">Hash and Array Parameters</a></li>
- <li><a href="#_routing_parameters">Routing parameters</a></li>
+ <li><a href="#_routing_parameters">Routing Parameters</a></li>
+
+ <li><a href="#_tt_default_url_options_tt"><tt>default_url_options</tt></a></li>
</ul>
</li>
@@ -218,9 +220,9 @@ ul#navMain {
<a href="#_session">Session</a>
<ul>
- <li><a href="#_disabling_the_session">Disabling the session</a></li>
+ <li><a href="#_disabling_the_session">Disabling the Session</a></li>
- <li><a href="#_accessing_the_session">Accessing the session</a></li>
+ <li><a href="#_accessing_the_session">Accessing the Session</a></li>
<li><a href="#_the_flash">The flash</a></li>
@@ -233,9 +235,9 @@ ul#navMain {
<a href="#_filters">Filters</a>
<ul>
- <li><a href="#_after_filters_and_around_filters">After filters and around filters</a></li>
+ <li><a href="#_after_filters_and_around_filters">After Filters and Around Filters</a></li>
- <li><a href="#_other_ways_to_use_filters">Other ways to use filters</a></li>
+ <li><a href="#_other_ways_to_use_filters">Other Ways to Use Filters</a></li>
</ul>
</li>
@@ -243,12 +245,15 @@ ul#navMain {
<a href="#_verification">Verification</a>
</li>
<li>
- <a href="#_the_request_and_response_objects">The request and response objects</a>
+ <a href="#_request_forgery_protection">Request Forgery Protection</a>
+ </li>
+ <li>
+ <a href="#_the_tt_request_tt_and_tt_response_tt_objects">The <tt>request</tt> and <tt>response</tt> Objects</a>
<ul>
- <li><a href="#_the_request">The request</a></li>
+ <li><a href="#_the_tt_request_tt_object">The <tt>request</tt> Object</a></li>
- <li><a href="#_the_response">The response</a></li>
+ <li><a href="#_the_tt_response_tt_object">The <tt>response</tt> Object</a></li>
</ul>
</li>
@@ -256,28 +261,31 @@ ul#navMain {
<a href="#_http_basic_authentication">HTTP Basic Authentication</a>
</li>
<li>
- <a href="#_streaming_and_file_downloads">Streaming and file downloads</a>
+ <a href="#_streaming_and_file_downloads">Streaming and File Downloads</a>
<ul>
- <li><a href="#_sending_files">Sending files</a></li>
+ <li><a href="#_sending_files">Sending Files</a></li>
- <li><a href="#_restful_downloads">RESTful downloads</a></li>
+ <li><a href="#_restful_downloads">RESTful Downloads</a></li>
</ul>
</li>
<li>
- <a href="#_parameter_filtering">Parameter filtering</a>
+ <a href="#_parameter_filtering">Parameter Filtering</a>
</li>
<li>
<a href="#_rescue">Rescue</a>
<ul>
- <li><a href="#_the_default_500_and_404_templates">The default 500 and 404 templates</a></li>
+ <li><a href="#_the_default_500_and_404_templates">The Default 500 and 404 Templates</a></li>
<li><a href="#_tt_rescue_from_tt"><tt>rescue_from</tt></a></li>
</ul>
</li>
+ <li>
+ <a href="#_changelog">Changelog</a>
+ </li>
</ol>
</div>
@@ -285,30 +293,75 @@ ul#navMain {
<h1>Action Controller basics</h1>
<div id="preamble">
<div class="sectionbody">
-<div class="para"><p>In this guide you will learn how controllers work and how they fit into the request cycle in your application. You will learn how to make use of the many tools provided by Action Controller to work with the session, cookies and filters and how to use the built-in HTTP authentication and data streaming facilities. In the end, we will take a look at some tools that will be useful once your controllers are ready and working, like how to filter sensitive parameters from the log and how to rescue and deal with exceptions that may be raised during the request.</p></div>
+<div class="para"><p>In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Follow the flow of a request through a controller
+</p>
+</li>
+<li>
+<p>
+Understand why and how to store data in the session or cookies
+</p>
+</li>
+<li>
+<p>
+Work with filters to execute code during request processing
+</p>
+</li>
+<li>
+<p>
+Use Action Controller's built-in HTTP authentication
+</p>
+</li>
+<li>
+<p>
+Stream data directly to the user's browser
+</p>
+</li>
+<li>
+<p>
+Filter sensitive parameters so they do not appear in the application's log
+</p>
+</li>
+<li>
+<p>
+Deal with exceptions that may be raised during request processing
+</p>
+</li>
+</ul></div>
</div>
</div>
-<h2 id="_what_does_a_controller_do">1. What does a controller do?</h2>
+<h2 id="_what_does_a_controller_do">1. What Does a Controller do?</h2>
<div class="sectionbody">
<div class="para"><p>Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.</p></div>
<div class="para"><p>For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.</p></div>
-<div class="para"><p>A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model.</p></div>
+<div class="para"><p>A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">For more details on the routing process, see <a href="../routing_outside_in.html">Rails Routing from the Outside In</a>.</td>
+</tr></table>
+</div>
</div>
-<h2 id="_methods_and_actions">2. Methods and actions</h2>
+<h2 id="_methods_and_actions">2. Methods and Actions</h2>
<div class="sectionbody">
-<div class="para"><p>A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) gets run.</p></div>
+<div class="para"><p>A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ApplicationController
<span style="font-style: italic"><span style="color: #9A1900"># Actions are public methods</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> new
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># These methods are responsible for producing output</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># Action methods are responsible for producing output</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> edit
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -320,8 +373,8 @@ private
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Private methods in a controller are also used as filters, which will be covered later in this guide.</p></div>
-<div class="para"><p>As an example, if the user goes to <tt>/clients/new</tt> in your application to add a new client, a ClientsController instance will be created and the <tt>new</tt> method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the <tt>new.html.erb</tt> view unless the action says otherwise. The <tt>new</tt> method could make available to the view a <tt>@client</tt> instance variable by creating a new Client:</p></div>
+<div class="para"><p>There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.</p></div>
+<div class="para"><p>As an example, if a user goes to <tt>/clients/new</tt> in your application to add a new client, Rails will create an instance of ClientsController and run the <tt>new</tt> method. Note that the empty method from the example above could work just fine because Rails will by default render the <tt>new.html.erb</tt> view unless the action says otherwise. The <tt>new</tt> method could make available to the view a <tt>@client</tt> instance variable by creating a new Client:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -332,10 +385,11 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <a href="../layouts_and_rendering.html">Layouts &amp; rendering guide</a> explains this in more detail.</p></div>
+<div class="para"><p>ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.</p></div>
</div>
<h2 id="_parameters">3. Parameters</h2>
<div class="sectionbody">
-<div class="para"><p>You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the <tt>params</tt> hash in your controller:</p></div>
+<div class="para"><p>You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the <tt>params</tt> hash in your controller:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -343,9 +397,10 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
- <span style="font-style: italic"><span style="color: #9A1900"># This action uses query string parameters because it gets run by a HTTP GET request,</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># but this does not make any difference to the way in which the parameters are accessed.</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># The URL for this action would look like this in order to list activated clients: /clients?status=activated</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># This action uses query string parameters because it gets run by a HTTP</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># GET request, but this does not make any difference to the way in which</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># the parameters are accessed. The URL for this action would look like this</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># in order to list activated clients: /clients?status=activated</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> params<span style="color: #990000">[:</span>status<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"activated"</span>
<span style="color: #009900">@clients</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>activated
@@ -370,12 +425,20 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h3 id="_hash_and_array_parameters">3.1. Hash and array parameters</h3>
+<h3 id="_hash_and_array_parameters">3.1. Hash and Array Parameters</h3>
<div class="para"><p>The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>GET /clients?ids[]=1&amp;ids[2]&amp;ids[]=3</tt></pre>
+<pre><tt>GET /clients?ids[]=1&amp;ids[]=2&amp;ids[]=3</tt></pre>
</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&amp;ids%5b%5d=2&amp;ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.</td>
+</tr></table>
+</div>
<div class="para"><p>The value of <tt>params[:ids]</tt> will now be <tt>["1", "2", "3"]</tt>. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.</p></div>
<div class="para"><p>To send a hash you include the key name inside the brackets:</p></div>
<div class="listingblock">
@@ -387,13 +450,38 @@ http://www.gnu.org/software/src-highlite -->
&lt;input type="text" name="client[address][city]" value="Carrot City" /&gt;
&lt;/form&gt;</tt></pre>
</div></div>
-<div class="para"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{:name &#8658; "Acme", :phone &#8658; "12345", :address &#8658; {:postcode &#8658; "12345", :city &#8658; "Carrot City"}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p></div>
-<h3 id="_routing_parameters">3.2. Routing parameters</h3>
-<div class="para"><p>The <tt>params</tt> hash will always contain the <tt>:controller</tt> and <tt>:action</tt> keys, but you should use the methods <tt>controller_name</tt> and <tt>action_name</tt> instead to access these values. Any other parameters defined by the routing, such as <tt>:id</tt> will also be available.</p></div>
+<div class="para"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{"name" &#8658; "Acme", "phone" &#8658; "12345", "address" &#8658; {"postcode" &#8658; "12345", "city" &#8658; "Carrot City"}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p></div>
+<div class="para"><p>Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.</p></div>
+<h3 id="_routing_parameters">3.2. Routing Parameters</h3>
+<div class="para"><p>The <tt>params</tt> hash will always contain the <tt>:controller</tt> and <tt>:action</tt> keys, but you should use the methods <tt>controller_name</tt> and <tt>action_name</tt> instead to access these values. Any other parameters defined by the routing, such as <tt>:id</tt> will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the <tt>:status</tt> parameter in a "pretty" URL:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
+map<span style="color: #990000">.</span>connect <span style="color: #FF0000">"/clients/:status"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"clients"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"index"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foo <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"bar"</span>
+<span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
+</tt></pre></div></div>
+<div class="para"><p>In this case, when a user opens the URL <tt>/clients/active</tt>, <tt>params[:status]</tt> will be set to "active". When this route is used, <tt>params[:foo]</tt> will also be set to "bar" just like it was passed in the query string in the same way <tt>params[:action]</tt> will contain "index".</p></div>
+<h3 id="_tt_default_url_options_tt">3.3. <tt>default_url_options</tt></h3>
+<div class="para"><p>You can set global default parameters that will be used when generating URLs with <tt>default_url_options</tt>. To do this, define a method with that name in your controller:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>class ApplicationController &lt; ActionController::Base
+
+ #The options parameter is the hash passed in to +url_for+
+ def default_url_options(options)
+ {:locale =&gt; I18n.locale}
+ end
+
+end</tt></pre>
+</div></div>
+<div class="para"><p>These options will be used as a starting-point when generating, so it's possible they'll be overridden by <tt>url_for</tt>. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.</p></div>
</div>
<h2 id="_session">4. Session</h2>
<div class="sectionbody">
-<div class="para"><p>Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and can use one of a number of different storage mechanisms:</p></div>
+<div class="para"><p>Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -402,12 +490,12 @@ CookieStore - Stores everything on the client.
</li>
<li>
<p>
-DRBStore - Stores the data on a DRb client.
+DRbStore - Stores the data on a DRb server.
</p>
</li>
<li>
<p>
-MemCacheStore - Stores the data in MemCache.
+MemCacheStore - Stores the data in a memcache.
</p>
</li>
<li>
@@ -416,8 +504,9 @@ ActiveRecordStore - Stores the data in a database using Active Record.
</p>
</li>
</ul></div>
-<div class="para"><p>All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server.</p></div>
-<div class="para"><p>The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.</p></div>
+<div class="para"><p>All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).</p></div>
+<div class="para"><p>Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.</p></div>
+<div class="para"><p>Read more about session storage in the <a href="../security.html">Security Guide</a>.</p></div>
<div class="para"><p>If you need a different session storage mechanism, you can change it in the <tt>config/environment.rb</tt> file:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -427,8 +516,8 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]</span></span>
config<span style="color: #990000">.</span>action_controller<span style="color: #990000">.</span>session_store <span style="color: #990000">=</span> <span style="color: #990000">:</span>active_record_store
</tt></pre></div></div>
-<h3 id="_disabling_the_session">4.1. Disabling the session</h3>
-<div class="para"><p>Sometimes you don't need a session, and you can turn it off to avoid the unnecessary overhead. To do this, use the <a href="http://api.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html#M000649">session</a> class method in your controller:</p></div>
+<h3 id="_disabling_the_session">4.1. Disabling the Session</h3>
+<div class="para"><p>Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the <tt>session</tt> class method in your controller:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -450,7 +539,7 @@ http://www.gnu.org/software/src-highlite -->
session <span style="color: #990000">:</span>on
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Or even a single action:</p></div>
+<div class="para"><p>Or even for specified actions:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -460,14 +549,14 @@ http://www.gnu.org/software/src-highlite -->
session <span style="color: #990000">:</span>on<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>create<span style="color: #990000">,</span> <span style="color: #990000">:</span>update<span style="color: #990000">]</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h3 id="_accessing_the_session">4.2. Accessing the session</h3>
+<h3 id="_accessing_the_session">4.2. Accessing the Session</h3>
<div class="para"><p>In your controller you can access the session through the <tt>session</tt> instance method.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
-<td class="content">There are two <tt>session</tt> methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. The class method is used outside of method definitions while the instance methods is used inside methods, in actions or filters.</td>
+<td class="content">There are two <tt>session</tt> methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values.</td>
</tr></table>
</div>
<div class="para"><p>Session values are stored using key/value pairs like a hash:</p></div>
@@ -481,7 +570,7 @@ http://www.gnu.org/software/src-highlite -->
private
<span style="font-style: italic"><span style="color: #9A1900"># Finds the User with the ID stored in the session with the key :current_user_id</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># This is a common way to do user login in a Rails application; logging in sets the</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># This is a common way to handle user login in a Rails application; logging in sets the</span></span>
<span style="font-style: italic"><span style="color: #9A1900"># session value and logging out removes it.</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> current_user
<span style="color: #009900">@_current_user</span> <span style="color: #990000">||=</span> session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">]</span> <span style="color: #990000">&amp;&amp;</span> User<span style="color: #990000">.</span>find<span style="color: #990000">(</span>session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">])</span>
@@ -525,9 +614,9 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>To reset the entire session, use <a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000855">reset_session</a>.</p></div>
+<div class="para"><p>To reset the entire session, use <tt>reset_session</tt>.</p></div>
<h3 id="_the_flash">4.3. The flash</h3>
-<div class="para"><p>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request:</p></div>
+<div class="para"><p>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -543,7 +632,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The <tt>destroy</tt> action redirects to the application's <tt>root_url</tt>, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout:</p></div>
+<div class="para"><p>The <tt>destroy</tt> action redirects to the application's <tt>root_url</tt>, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;html&gt;
@@ -578,7 +667,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h4 id="_flash_now">4.3.1. flash.now</h4>
+<h4 id="_tt_flash_now_tt">4.3.1. <tt>flash.now</tt></h4>
<div class="para"><p>By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the <tt>create</tt> action fails to save a resource and you render the <tt>new</tt> template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use <tt>flash.now</tt> in the same way you use the normal <tt>flash</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -634,11 +723,11 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Note that while for session values, you set the key to <tt>nil</tt>, to delete a cookie value, you use <tt>cookies.delete(:key)</tt>.</p></div>
+<div class="para"><p>Note that while for session values, you set the key to <tt>nil</tt>, to delete a cookie value, you should use <tt>cookies.delete(:key)</tt>.</p></div>
</div>
<h2 id="_filters">6. Filters</h2>
<div class="sectionbody">
-<div class="para"><p>Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first:</p></div>
+<div class="para"><p>Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -666,7 +755,7 @@ private
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the <a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704">before_filter</a> method:</p></div>
+<div class="para"><p>The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the <tt>before_filter</tt> method:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -678,7 +767,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use <a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711">skip_before_filter</a> :</p></div>
+<div class="para"><p>In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with <tt>skip_before_filter</tt> :</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -690,8 +779,8 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The <tt>:only</tt> option is used to only skip this filter for these actions, and there is also an <tt>:except</tt> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p></div>
-<h3 id="_after_filters_and_around_filters">6.1. After filters and around filters</h3>
+<div class="para"><p>Now, the <tt>LoginsController</tt>'s "new" and "create" actions will work as before without requiring the user to be logged in. The <tt>:only</tt> option is used to only skip this filter for these actions, and there is also an <tt>:except</tt> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p></div>
+<h3 id="_after_filters_and_around_filters">6.1. After Filters and Around Filters</h3>
<div class="para"><p>In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -715,9 +804,9 @@ private
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h3 id="_other_ways_to_use_filters">6.2. Other ways to use filters</h3>
+<h3 id="_other_ways_to_use_filters">6.2. Other Ways to Use Filters</h3>
<div class="para"><p>While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.</p></div>
-<div class="para"><p>The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the <tt>require_login</tt> filter from above could be rewritte to use a block:</p></div>
+<div class="para"><p>The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the <tt>require_login</tt> filter from above could be rewritten to use a block:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -730,7 +819,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Note that the filter in this case uses <tt>send</tt> because the <tt>logged_in?</tt> method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.</p></div>
-<div class="para"><p>The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class:</p></div>
+<div class="para"><p>The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -753,13 +842,13 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method <tt>filter</tt> which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same <tt>filter</tt> method, which will get run in the same way. The method must <tt>yield</tt> to execute the action. Alternatively, it can have both a <tt>before</tt> and an <tt>after</tt> method that are run before and after the action.</p></div>
+<div class="para"><p>Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method <tt>filter</tt> which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same <tt>filter</tt> method, which will get run in the same way. The method must <tt>yield</tt> to execute the action. Alternatively, it can have both a <tt>before</tt> and an <tt>after</tt> method that are run before and after the action.</p></div>
<div class="para"><p>The Rails API documentation has <a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html">more information on using filters</a>.</p></div>
</div>
<h2 id="_verification">7. Verification</h2>
<div class="sectionbody">
-<div class="para"><p>Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the <tt>params</tt>, <tt>session</tt> or <tt>flash</tt> hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the <a href="http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html">API codumentation</a> as "essentially a special kind of before_filter".</p></div>
-<div class="para"><p>Let's see how we can use verification to make sure the user supplies a username and a password in order to log in:</p></div>
+<div class="para"><p>Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the <tt>params</tt>, <tt>session</tt> or <tt>flash</tt> hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the <a href="http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html">API documentation</a> as "essentially a special kind of before_filter".</p></div>
+<div class="para"><p>Here's an example of using verification to make sure the user supplies a username and a password in order to log in:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -794,16 +883,49 @@ http://www.gnu.org/software/src-highlite -->
verify <span style="color: #990000">:</span>params <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>username<span style="color: #990000">,</span> <span style="color: #990000">:</span>password<span style="color: #990000">],</span>
<span style="color: #990000">:</span>render <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"new"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span>
<span style="color: #990000">:</span>add_flash <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>error <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Username and password required to log in"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span>
- <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900">#Only run this verification for the "create" action</span></span>
+ <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># Only run this verification for the "create" action</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_the_request_and_response_objects">8. The request and response objects</h2>
+<h2 id="_request_forgery_protection">8. Request Forgery Protection</h2>
+<div class="sectionbody">
+<div class="para"><p>Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.</p></div>
+<div class="para"><p>If you generate a form like this:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="color: #FF0000">&lt;% form_for @user do |f| -%&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.text_field :username %&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.text_field :password -%&gt;</span>
+<span style="color: #FF0000">&lt;% end -%&gt;</span>
+</tt></pre></div></div>
+<div class="para"><p>You will see how the token gets added as a hidden field:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">&lt;form</span></span> <span style="color: #009900">action</span><span style="color: #990000">=</span><span style="color: #FF0000">"/users/1"</span> <span style="color: #009900">method</span><span style="color: #990000">=</span><span style="color: #FF0000">"post"</span><span style="font-weight: bold"><span style="color: #0000FF">&gt;</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">&lt;div&gt;</span></span><span style="font-style: italic"><span style="color: #9A1900">&lt;!-- ... --&gt;</span></span><span style="font-weight: bold"><span style="color: #0000FF">&lt;input</span></span> <span style="color: #009900">type</span><span style="color: #990000">=</span><span style="color: #FF0000">"hidden"</span> <span style="color: #009900">value</span><span style="color: #990000">=</span><span style="color: #FF0000">"67250ab105eb5ad10851c00a5621854a23af5489"</span> <span style="color: #009900">name</span><span style="color: #990000">=</span><span style="color: #FF0000">"authenticity_token"</span><span style="font-weight: bold"><span style="color: #0000FF">/&gt;&lt;/div&gt;</span></span>
+<span style="font-style: italic"><span style="color: #9A1900">&lt;!-- Fields --&gt;</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">&lt;/form&gt;</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Rails adds this token to every form that's generated using the <a href="../form_helpers.html">form helpers</a>, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method <tt>form_authenticity_token</tt>:</p></div>
+<div class="listingblock">
+<div class="title">Example: Add a JavaScript variable containing the token for use with Ajax</div>
+<div class="content">
+<pre><tt>&lt;%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %&gt;</tt></pre>
+</div></div>
+<div class="para"><p>The <a href="../security.html">Security Guide</a> has more about this and a lot of other security-related issues that you should be aware of when developing a web application.</p></div>
+</div>
+<h2 id="_the_tt_request_tt_and_tt_response_tt_objects">9. The <tt>request</tt> and <tt>response</tt> Objects</h2>
<div class="sectionbody">
-<div class="para"><p>In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The <tt>request</tt> method contains an instance of <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">AbstractRequest</a> and the <tt>response</tt> method contains the <a href="http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb">response object</a> representing what is going to be sent back to the client.</p></div>
-<h3 id="_the_request">8.1. The request</h3>
-<div class="para"><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>.</p></div>
+<div class="para"><p>In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The <tt>request</tt> method contains an instance of AbstractRequest and the <tt>response</tt> method returns a <tt>response</tt> object representing what is going to be sent back to the client.</p></div>
+<h3 id="_the_tt_request_tt_object">9.1. The <tt>request</tt> Object</h3>
+<div class="para"><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>. Among the properties that you can access on this object are:</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -812,7 +934,7 @@ host - The hostname used for this request.
</li>
<li>
<p>
-domain - The hostname without the first part (usually "www").
+domain - The hostname without the first segment (usually "www").
</p>
</li>
<li>
@@ -861,11 +983,10 @@ url - The entire URL used for the request.
</p>
</li>
</ul></div>
-<h4 id="_path_parameters_query_parameters_and_request_parameters">8.1.1. path_parameters, query_parameters and request_parameters</h4>
-<div class="para"><p>TODO: Does this belong here?</p></div>
-<div class="para"><p>Rails collects all of the parameters sent along with the request in the <tt>params</tt> hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The <tt>query_parameters</tt> hash contains parameters that were sent as part of the query string while the <tt>request_parameters</tt> hash contains parameters sent as part of the post body. The <tt>path_parameters</tt> hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action.</p></div>
-<h3 id="_the_response">8.2. The response</h3>
-<div class="para"><p>The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.</p></div>
+<h4 id="_tt_path_parameters_tt_tt_query_parameters_tt_and_tt_request_parameters_tt">9.1.1. <tt>path_parameters</tt>, <tt>query_parameters</tt> and <tt>request_parameters</tt></h4>
+<div class="para"><p>Rails collects all of the parameters sent along with the request in the <tt>params</tt> hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The <tt>query_parameters</tt> hash contains parameters that were sent as part of the query string while the <tt>request_parameters</tt> hash contains parameters sent as part of the post body. The <tt>path_parameters</tt> hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.</p></div>
+<h3 id="_the_tt_response_tt_object">9.2. The <tt>response</tt> Object</h3>
+<div class="para"><p>The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -892,11 +1013,25 @@ content_type - The content type of the response.
charset - The character set being used for the response. Default is "utf8".
</p>
</li>
+<li>
+<p>
+headers - Headers used for the response.
+</p>
+</li>
</ul></div>
+<h4 id="_setting_custom_headers">9.2.1. Setting Custom Headers</h4>
+<div class="para"><p>If you want to set custom headers for a response then <tt>response.headers</tt> is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to <tt>headers</tt> with the name and value:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>response<span style="color: #990000">.</span>headers<span style="color: #990000">[</span><span style="color: #FF0000">"Content-Type"</span><span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"application/pdf"</span>
+</tt></pre></div></div>
</div>
-<h2 id="_http_basic_authentication">9. HTTP Basic Authentication</h2>
+<h2 id="_http_basic_authentication">10. HTTP Basic Authentication</h2>
<div class="sectionbody">
-<div class="para"><p>Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, <a href="http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610">authenticate_or_request_with_http_basic</a>.</p></div>
+<div class="para"><p>Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, <tt>authenticate_or_request_with_http_basic</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -904,7 +1039,7 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AdminController <span style="color: #990000">&lt;</span> ApplicationController
- USERNAME<span style="color: #990000">,</span> PASSWORD <span style="color: #990000">=</span> <span style="color: #FF0000">"humbaba"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"f59a4805511bf4bb61978445a5380c6c"</span>
+ USERNAME<span style="color: #990000">,</span> PASSWORD <span style="color: #990000">=</span> <span style="color: #FF0000">"humbaba"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"</span>
before_filter <span style="color: #990000">:</span>authenticate
@@ -912,7 +1047,7 @@ private
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> authenticate
authenticate_or_request_with_http_basic <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>username<span style="color: #990000">,</span> password<span style="color: #990000">|</span>
- username <span style="color: #990000">==</span> USERNAME <span style="color: #990000">&amp;&amp;</span> Digest<span style="color: #990000">::</span>MD5<span style="color: #990000">.</span>hexdigest<span style="color: #990000">(</span>password<span style="color: #990000">)</span> <span style="color: #990000">==</span> PASSWORD
+ username <span style="color: #990000">==</span> USERNAME <span style="color: #990000">&amp;&amp;</span> Digest<span style="color: #990000">::</span>SHA1<span style="color: #990000">.</span>hexdigest<span style="color: #990000">(</span>password<span style="color: #990000">)</span> <span style="color: #990000">==</span> PASSWORD
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -920,9 +1055,9 @@ private
</tt></pre></div></div>
<div class="para"><p>With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.</p></div>
</div>
-<h2 id="_streaming_and_file_downloads">10. Streaming and file downloads</h2>
+<h2 id="_streaming_and_file_downloads">11. Streaming and File Downloads</h2>
<div class="sectionbody">
-<div class="para"><p>Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the <a href="http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624">send_data</a> and the <a href="http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623">send_file</a> methods, that will both stream data to the client. <tt>send_file</tt> is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.</p></div>
+<div class="para"><p>Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the <tt>send_data</tt> and the <tt>send_file</tt> methods, that will both stream data to the client. <tt>send_file</tt> is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.</p></div>
<div class="para"><p>To stream data to the client, use <tt>send_data</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -952,7 +1087,7 @@ private
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The <tt>download_pdf</tt> action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the <tt>:disposition</tt> option to "inline". The opposite and default value for this option is "attachment".</p></div>
-<h3 id="_sending_files">10.1. Sending files</h3>
+<h3 id="_sending_files">11.1. Sending Files</h3>
<div class="para"><p>If you want to send a file that already exists on disk, use the <tt>send_file</tt> method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -969,13 +1104,13 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the <tt>stream</tt> option or adjust the block size with the <tt>buffer_size</tt> option.</p></div>
+<div class="para"><p>This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the <tt>:stream</tt> option or adjust the block size with the <tt>:buffer_size</tt> option.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
-<td class="content">Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.</td>
+<td class="content">Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.</td>
</tr></table>
</div>
<div class="admonitionblock">
@@ -986,8 +1121,8 @@ http://www.gnu.org/software/src-highlite -->
<td class="content">It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.</td>
</tr></table>
</div>
-<h3 id="_restful_downloads">10.2. RESTful downloads</h3>
-<div class="para"><p>While <tt>send_data</tt> works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the <tt>show</tt> action:</p></div>
+<h3 id="_restful_downloads">11.2. RESTful Downloads</h3>
+<div class="para"><p>While <tt>send_data</tt> works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the <tt>show</tt> action, without any streaming:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1007,7 +1142,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file <tt>config/initializers/mime_types.rb</tt>:</p></div>
+<div class="para"><p>In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file <tt>config/initializers/mime_types.rb</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1029,9 +1164,9 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>GET /clients/1.pdf</tt></pre>
</div></div>
</div>
-<h2 id="_parameter_filtering">11. Parameter filtering</h2>
+<h2 id="_parameter_filtering">12. Parameter Filtering</h2>
<div class="sectionbody">
-<div class="para"><p>Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The <a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000837">filter_parameter_logging</a> method can be used to filter out sensitive information from the log. It works by replacing certain keys in the <tt>params</tt> hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":</p></div>
+<div class="para"><p>Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The <tt>filter_parameter_logging</tt> method can be used to filter out sensitive information from the log. It works by replacing certain values in the <tt>params</tt> hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1045,14 +1180,14 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.</p></div>
</div>
-<h2 id="_rescue">12. Rescue</h2>
+<h2 id="_rescue">13. Rescue</h2>
<div class="sectionbody">
<div class="para"><p>Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:</p></div>
-<h3 id="_the_default_500_and_404_templates">12.1. The default 500 and 404 templates</h3>
+<h3 id="_the_default_500_and_404_templates">13.1. The Default 500 and 404 Templates</h3>
<div class="para"><p>By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the <tt>public</tt> folder, in <tt>404.html</tt> and <tt>500.html</tt> respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.</p></div>
-<h3 id="_tt_rescue_from_tt">12.2. <tt>rescue_from</tt></h3>
-<div class="para"><p>If you want to do something a bit more elaborate when catching errors, you can use <a href=":http://api.rubyonrails.org/classes/ActionController/Rescue/ClassMethods.html#M000620">rescue_from</a>, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the <tt>:with</tt> option. You can also use a block directly instead of an explicit Proc object.</p></div>
-<div class="para"><p>Let's see how we can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.</p></div>
+<h3 id="_tt_rescue_from_tt">13.2. <tt>rescue_from</tt></h3>
+<div class="para"><p>If you want to do something a bit more elaborate when catching errors, you can use <tt>rescue_from</tt>, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a <tt>rescue_from</tt> directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the <tt>:with</tt> option. You can also use a block directly instead of an explicit Proc object.</p></div>
+<div class="para"><p>Here's how you can use <tt>rescue_from</tt> to intercept all ActiveRecord::RecordNotFound errors and do something with them.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1070,7 +1205,7 @@ private
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Of course, this example is anything but elaborate and doesn't improve the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:</p></div>
+<div class="para"><p>Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1117,6 +1252,17 @@ private
</tr></table>
</div>
</div>
+<h2 id="_changelog">14. Changelog</h2>
+<div class="sectionbody">
+<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17">Lighthouse ticket</a></p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+November 4, 2008: First release version by Tore Darrell
+</p>
+</li>
+</ul></div>
+</div>
</div>
</div>
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
new file mode 100644
index 0000000000..0aa507a9b9
--- /dev/null
+++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
@@ -0,0 +1,749 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <title>Active Record Validations and Callbacks</title>
+ <!--[if lt IE 8]>
+ <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
+ <![endif]-->
+ <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
+ <style type="text/css">
+ div#container {
+ max-width: 900px;
+ padding-bottom: 3em;
+}
+
+div#content {
+ margin-left: 200px;
+}
+
+div#container.notoc {
+ max-width: 600px;
+}
+
+.notoc div#content {
+ margin-left: 0;
+}
+
+pre {
+ line-height: 1.4em;
+}
+
+#content p tt {
+ background: #eeeeee;
+ border: solid 1px #cccccc;
+ padding: 3px;
+}
+
+dt {
+ font-weight: bold;
+}
+
+#content dt tt {
+ font-size: 10pt;
+}
+
+dd {
+ margin-left: 3em;
+}
+
+#content dt tt, #content pre tt {
+ background: none;
+ padding: 0;
+ border: 0;
+}
+
+#content .olist ol {
+ margin-left: 2em;
+}
+
+#header {
+ position: relative;
+ max-width: 840px;
+ margin-left: auto;
+ margin-right: auto;
+}
+
+#header.notoc {
+ max-width: 580px;
+}
+
+#logo {
+ position: absolute;
+ left: 10px;
+ top: 10px;
+ width: 110px;
+ height: 140px;
+}
+
+div#header h1#site_title {
+ background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
+ position: absolute;
+ width: 392px;
+ height: 55px;
+ left: 145px;
+ top: 20px;
+ margin: 0;
+ padding: 0;
+}
+
+#site_title span {
+ display: none;
+}
+
+#site_title_tagline {
+ display: none;
+}
+
+ul#navMain {
+ position: absolute;
+ margin: 0;
+ padding: 0;
+ top: 97px;
+ left: 145px;
+}
+
+.left-floaty, .right-floaty {
+ padding: 15px;
+}
+
+.admonitionblock,
+.tableblock {
+ margin-left: 1em;
+ margin-right: 1em;
+ margin-top: 0.25em;
+ margin-bottom: 1em;
+}
+
+.admonitionblock .icon {
+ padding-right: 8px;
+}
+
+.admonitionblock .content {
+ border: solid 1px #ffda78;
+ background: #fffebd;
+ padding: 10px;
+ padding-top: 8px;
+ padding-bottom: 8px;
+}
+
+.admonitionblock .title {
+ font-size: 140%;
+ margin-bottom: 0.5em;
+}
+
+.tableblock table {
+ border: solid 1px #aaaaff;
+ background: #f0f0ff;
+}
+
+.tableblock th {
+ background: #e0e0e0;
+}
+
+.tableblock th,
+.tableblock td {
+ padding: 3px;
+ padding-left: 5px;
+ padding-right: 5px;
+}
+
+.sidebarblock {
+ margin-top: 0.25em;
+ margin: 1em;
+ border: solid 1px #ccccbb;
+ padding: 8px;
+ background: #ffffe0;
+}
+
+.sidebarblock .sidebar-title {
+ font-size: 140%;
+ font-weight: 600;
+ margin-bottom: 0.3em;
+}
+
+.sidebarblock .sidebar-content > .para:last-child > p {
+ margin-bottom: 0;
+}
+
+.sidebarblock .sidebar-title a {
+ text-decoration: none;
+}
+
+.sidebarblock .sidebar-title a:hover {
+ text-decoration: underline;
+}
+
+ </style>
+</head>
+<body>
+ <div id="header" >
+ <div id="logo">
+ <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
+ </div>
+
+ <h1 id="site_title"><span>Ruby on Rails</span></h1>
+ <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
+
+ <ul id="navMain">
+ <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
+ <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
+ </ul>
+ </div>
+
+ <div id="container">
+
+ <div id="sidebar">
+ <h2>Chapters</h2>
+ <ol>
+ <li>
+ <a href="#_motivations_to_validate_your_active_record_objects">Motivations to validate your Active Record objects</a>
+ </li>
+ <li>
+ <a href="#_how_it_works">How it works</a>
+ <ul>
+
+ <li><a href="#_when_does_validation_happens">When does validation happens?</a></li>
+
+ <li><a href="#_the_meaning_of_em_valid_em">The meaning of <em>valid</em></a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_the_declarative_validation_helpers">The declarative validation helpers</a>
+ <ul>
+
+ <li><a href="#_the_tt_validates_acceptance_of_tt_helper">The <tt>validates_acceptance_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_associated_tt_helper">The <tt>validates_associated</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_confirmation_of_tt_helper">The <tt>validates_confirmation_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_each_tt_helper">The <tt>validates_each</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_exclusion_of_tt_helper">The <tt>validates_exclusion_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_format_of_tt_helper">The <tt>validates_format_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_inclusion_of_tt_helper">The <tt>validates_inclusion_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_length_of_tt_helper">The <tt>validates_length_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_numericallity_of_tt_helper">The <tt>validates_numericallity_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_presence_of_tt_helper">The <tt>validates_presence_of</tt> helper</a></li>
+
+ <li><a href="#_the_tt_validates_uniqueness_of_tt_helper">The <tt>validates_uniqueness_of</tt> helper</a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_common_validation_options">Common validation options</a>
+ <ul>
+
+ <li><a href="#_the_tt_allow_nil_tt_option">The <tt>:allow_nil</tt> option</a></li>
+
+ <li><a href="#_the_tt_message_tt_option">The <tt>:message</tt> option</a></li>
+
+ <li><a href="#_the_tt_on_tt_option">The <tt>:on</tt> option</a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_conditional_validation">Conditional validation</a>
+ <ul>
+
+ <li><a href="#_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options">Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</a></li>
+
+ <li><a href="#_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options">Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</a></li>
+
+ <li><a href="#_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options">Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_writing_your_own_validation_methods">Writing your own validation methods</a>
+ </li>
+ <li>
+ <a href="#_changelog">Changelog</a>
+ </li>
+ </ol>
+ </div>
+
+ <div id="content">
+ <h1>Active Record Validations and Callbacks</h1>
+ <div id="preamble">
+<div class="sectionbody">
+<div class="para"><p>This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.</p></div>
+<div class="para"><p>After reading this guide and trying out the presented concepts, we hope that you'll be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Correctly use all the built-in Active Record validation helpers
+</p>
+</li>
+<li>
+<p>
+Create your own custom validation methods
+</p>
+</li>
+<li>
+<p>
+Work with the error messages generated by the validation proccess
+</p>
+</li>
+<li>
+<p>
+Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
+</p>
+</li>
+<li>
+<p>
+Create special classes that encapsulate common behaviour for your callbacks
+</p>
+</li>
+<li>
+<p>
+Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
+</p>
+</li>
+</ul></div>
+</div>
+</div>
+<h2 id="_motivations_to_validate_your_active_record_objects">1. Motivations to validate your Active Record objects</h2>
+<div class="sectionbody">
+<div class="para"><p>The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.</p></div>
+<div class="para"><p>There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
+</p>
+</li>
+<li>
+<p>
+Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
+</p>
+</li>
+<li>
+<p>
+Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
+</p>
+</li>
+</ul></div>
+</div>
+<h2 id="_how_it_works">2. How it works</h2>
+<div class="sectionbody">
+<h3 id="_when_does_validation_happens">2.1. When does validation happens?</h3>
+<div class="para"><p>There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the <tt>new</tt> method, that object does not belong to the database yet. Once you call <tt>save</tt> upon that object it'll be recorded to it's table. Active Record uses the <tt>new_record?</tt> instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>We can see how it works by looking at the following script/console output:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>&gt;&gt; p = Person.new(:name =&gt; "John Doe", :birthdate =&gt; Date.parse("09/03/1979"))
+=&gt; #&lt;Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil&gt;
+&gt;&gt; p.new_record?
+=&gt; true
+&gt;&gt; p.save
+=&gt; true
+&gt;&gt; p.new_record?
+=&gt; false</tt></pre>
+</div></div>
+<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt>, <tt>update_attribute</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
+<h3 id="_the_meaning_of_em_valid_em">2.2. The meaning of <em>valid</em></h3>
+<div class="para"><p>For verifying if an object is valid, Active Record uses the <tt>valid?</tt> method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the <tt>errors</tt> instance method. The proccess is really simple: If the <tt>errors</tt> method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the <tt>errors</tt> collection.</p></div>
+</div>
+<h2 id="_the_declarative_validation_helpers">3. The declarative validation helpers</h2>
+<div class="sectionbody">
+<div class="para"><p>Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's <tt>errors</tt> collection, this message being associated with the field being validated.</p></div>
+<div class="para"><p>Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.</p></div>
+<div class="para"><p>All these helpers accept the <tt>:on</tt> and <tt>:message</tt> options, which define when the validation should be applied and what message should be added to the <tt>errors</tt> collection when it fails, respectively. The <tt>:on</tt> option takes one the values <tt>:save</tt> (it's the default), <tt>:create</tt> or <tt>:update</tt>. There is a default error message for each one of the validation helpers. These messages are used when the <tt>:message</tt> option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.</p></div>
+<h3 id="_the_tt_validates_acceptance_of_tt_helper">3.1. The <tt>validates_acceptance_of</tt> helper</h3>
+<div class="para"><p>Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this <em>acceptance</em> does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_acceptance_of <span style="color: #990000">:</span>terms_of_service
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_acceptance_of</tt> is "<em>must be accepted</em>"</p></div>
+<div class="para"><p><tt>validates_acceptance_of</tt> can receive an <tt>:accept</tt> option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_acceptance_of <span style="color: #990000">:</span>terms_of_service<span style="color: #990000">,</span> <span style="color: #990000">:</span>accept <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'yes'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_the_tt_validates_associated_tt_helper">3.2. The <tt>validates_associated</tt> helper</h3>
+<div class="para"><p>You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, <tt>valid?</tt> will be called upon each one of the associated objects.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Library <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ has_many <span style="color: #990000">:</span>books
+ validates_associated <span style="color: #990000">:</span>books
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>This validation will work with all the association types.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/caution.png" alt="Caution" />
+</td>
+<td class="content">Pay attention not to use <tt>validates_associated</tt> on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.</td>
+</tr></table>
+</div>
+<div class="para"><p>The default error message for <tt>validates_associated</tt> is "<em>is invalid</em>". Note that the errors for each failed validation in the associated objects will be set there and not in this model.</p></div>
+<h3 id="_the_tt_validates_confirmation_of_tt_helper">3.3. The <tt>validates_confirmation_of</tt> helper</h3>
+<div class="para"><p>You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with <em>_confirmation</em> appended.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_confirmation_of <span style="color: #990000">:</span>email
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>In your view template you could use something like</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>&lt;%= text_field :person, :email %&gt;
+&lt;%= text_field :person, :email_confirmation %&gt;</tt></pre>
+</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">This check is performed only if <tt>email_confirmation</tt> is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at <tt>validates_presence_of</tt> later on this guide):</td>
+</tr></table>
+</div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_confirmation_of <span style="color: #990000">:</span>email
+ validates_presence_of <span style="color: #990000">:</span>email_confirmation
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_confirmation_of</tt> is "<em>doesn't match confirmation</em>"</p></div>
+<h3 id="_the_tt_validates_each_tt_helper">3.4. The <tt>validates_each</tt> helper</h3>
+<div class="para"><p>This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to <tt>validates_each</tt> will be tested against it. In the following example, we don't want names and surnames to begin with lower case.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_each <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>surname <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>model<span style="color: #990000">,</span> attr<span style="color: #990000">,</span> value<span style="color: #990000">|</span>
+ model<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>add<span style="color: #990000">(</span>attr<span style="color: #990000">,</span> <span style="color: #FF0000">'Must start with upper case'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> value <span style="color: #990000">=~</span> <span style="color: #FF6600">/^[a-z]/</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.</p></div>
+<h3 id="_the_tt_validates_exclusion_of_tt_helper">3.5. The <tt>validates_exclusion_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> MovieFile <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_exclusion_of <span style="color: #990000">:</span>format<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>mov avi<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Extension %s is not allowed"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The <tt>validates_exclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will not be accepted for the validated attributes. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
+<div class="para"><p>The default error message for <tt>validates_exclusion_of</tt> is "<em>is not included in the list</em>".</p></div>
+<h3 id="_the_tt_validates_format_of_tt_helper">3.6. The <tt>validates_format_of</tt> helper</h3>
+<div class="para"><p>This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the <tt>:with</tt> option.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_format_of <span style="color: #990000">:</span>description<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #FF6600">/^[a-zA-Z]+$/</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Only letters allowed"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_format_of</tt> is "<em>is invalid</em>".</p></div>
+<h3 id="_the_tt_validates_inclusion_of_tt_helper">3.7. The <tt>validates_inclusion_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The <tt>validates_inclusion_of</tt> helper has an option <tt>:in</tt> that receives the set of values that will be accepted. The <tt>:in</tt> option has an alias called <tt>:within</tt> that you can use for the same purpose, if you'd like to. In the previous example we used the <tt>:message</tt> option to show how we can personalize it with the current attribute's value, through the <tt>%s</tt> format mask.</p></div>
+<div class="para"><p>The default error message for <tt>validates_inclusion_of</tt> is "<em>is not included in the list</em>".</p></div>
+<h3 id="_the_tt_validates_length_of_tt_helper">3.8. The <tt>validates_length_of</tt> helper</h3>
+<div class="para"><p>This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=&gt;</span> <span style="color: #993399">2</span>
+ validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>maximum <span style="color: #990000">=&gt;</span> <span style="color: #993399">500</span>
+ validates_length_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #993399">6</span><span style="color: #990000">..</span><span style="color: #993399">20</span>
+ validates_length_of <span style="color: #990000">:</span>registration_number<span style="color: #990000">,</span> <span style="color: #990000">:</span>is <span style="color: #990000">=&gt;</span> <span style="color: #993399">6</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The possible length constraint options are:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>:minimum</tt> - The attribute cannot have less than the specified length.
+</p>
+</li>
+<li>
+<p>
+<tt>:maximum</tt> - The attribute cannot have more than the specified length.
+</p>
+</li>
+<li>
+<p>
+<tt>:in</tt> (or <tt>:within</tt>) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
+</p>
+</li>
+<li>
+<p>
+<tt>:is</tt> - The attribute length must be equal to a given value.
+</p>
+</li>
+</ul></div>
+<div class="para"><p>The default error messages depend on the type of length validation being performed. You can personalize these messages, using the <tt>:wrong_length</tt>, <tt>:too_long</tt> and <tt>:too_short</tt> options and the <tt>%d</tt> format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the <tt>:message</tt> option to specify an error message.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_length_of <span style="color: #990000">:</span>bio<span style="color: #990000">,</span> <span style="color: #990000">:</span>too_long <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"you're writing too much. %d characters is the maximum allowed."</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>This helper has an alias called <tt>validates_size_of</tt>, it's the same helper with a different name. You can use it if you'd like to.</p></div>
+<h3 id="_the_tt_validates_numericallity_of_tt_helper">3.9. The <tt>validates_numericallity_of</tt> helper</h3>
+<div class="para"><p>This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the <tt>:integer_only</tt> option set to true, you can specify that only integral numbers are allowed.</p></div>
+<div class="para"><p>If you use <tt>:integer_only</tt> set to <tt>true</tt>, then it will use the <tt><span>/\A[+\-]?\d+\Z/</span></tt> regular expression to validate the attribute's value. Otherwise, it will try to convert the value using <tt>Kernel.Float</tt>.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Player <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_numericallity_of <span style="color: #990000">:</span>points
+ validates_numericallity_of <span style="color: #990000">:</span>games_played<span style="color: #990000">,</span> <span style="color: #990000">:</span>integer_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_numericallity_of</tt> is "<em>is not a number</em>".</p></div>
+<h3 id="_the_tt_validates_presence_of_tt_helper">3.10. The <tt>validates_presence_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attributes are not empty. It uses the <tt>blank?</tt> method to check if the value is either <tt>nil</tt> or an empty string (if the string has only spaces, it will still be considered empty).</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.</td>
+</tr></table>
+</div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ belongs_to <span style="color: #990000">:</span>order
+ validates_presence_of <span style="color: #990000">:</span>order_id
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in &#8658; [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # &#8658; true</td>
+</tr></table>
+</div>
+<div class="para"><p>The default error message for <tt>validates_presence_of</tt> is "<em>can't be empty</em>".</p></div>
+<h3 id="_the_tt_validates_uniqueness_of_tt_helper">3.11. The <tt>validates_uniqueness_of</tt> helper</h3>
+<div class="para"><p>This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>email
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.</p></div>
+<div class="para"><p>There is a <tt>:scope</tt> option that you can use to specify other attributes that must be used to define uniqueness:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Holiday <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>year<span style="color: #990000">,</span> <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Should happen once per year"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>There is also a <tt>:case_sensitive</tt> option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>case_sensitive <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The default error message for <tt>validates_uniqueness_of</tt> is "<em>has already been taken</em>".</p></div>
+</div>
+<h2 id="_common_validation_options">4. Common validation options</h2>
+<div class="sectionbody">
+<div class="para"><p>There are some common options that all the validation helpers can use. Here they are, except for the <tt>:if</tt> and <tt>:unless</tt> options, which we'll cover right at the next topic.</p></div>
+<h3 id="_the_tt_allow_nil_tt_option">4.1. The <tt>:allow_nil</tt> option</h3>
+<div class="para"><p>You may use the <tt>:allow_nil</tt> option everytime you just want to trigger a validation if the value being validated is not <tt>nil</tt>. You may be asking yourself if it makes any sense to use <tt>:allow_nil</tt> and <tt>validates_presence_of</tt> together. Well, it does. Remember, validation will be skipped only for <tt>nil</tt> attributes, but empty strings are not considered <tt>nil</tt>.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Coffee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_inclusion_of <span style="color: #990000">:</span>size<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">%</span>w<span style="color: #990000">(</span>small medium large<span style="color: #990000">),</span>
+ <span style="color: #990000">:</span>message <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"%s is not a valid size"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>allow_nil <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_the_tt_message_tt_option">4.2. The <tt>:message</tt> option</h3>
+<div class="para"><p>As stated before, the <tt>:message</tt> option lets you specify the message that will be added to the <tt>errors</tt> collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.</p></div>
+<h3 id="_the_tt_on_tt_option">4.3. The <tt>:on</tt> option</h3>
+<div class="para"><p>As stated before, the <tt>:on</tt> option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use <tt>:on =<span>&gt;</span> :create</tt> to run the validation only when a new record is created or <tt>:on =<span>&gt;</span> :update</tt> to run the validation only when a record is updated.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_uniqueness_of <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to update email with a duplicated value</span></span>
+ validates_numericallity_of <span style="color: #990000">:</span>age<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>update <span style="font-style: italic"><span style="color: #9A1900"># =&gt; it will be possible to create the record with a 'non-numerical age'</span></span>
+ validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>on <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>save <span style="font-style: italic"><span style="color: #9A1900"># =&gt; that's the default</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_conditional_validation">5. Conditional validation</h2>
+<div class="sectionbody">
+<div class="para"><p>Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the <tt>:if</tt> and <tt>:unless</tt> options, which can take a symbol, a string or a Ruby Proc. You may use the <tt>:if</tt> option when you want to specify when the validation <strong>should</strong> happen. If you want to specify when the validation <strong>should not</strong> happen, then you may use the <tt>:unless</tt> option.</p></div>
+<h3 id="_using_a_symbol_with_the_tt_if_tt_and_tt_unless_tt_options">5.1. Using a symbol with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
+<div class="para"><p>You can associated the <tt>:if</tt> and <tt>:unless</tt> options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>card_number<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>paid_with_card?
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> paid_with_card?
+ payment_type <span style="color: #990000">==</span> <span style="color: #FF0000">"card"</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_using_a_string_with_the_tt_if_tt_and_tt_unless_tt_options">5.2. Using a string with the <tt>:if</tt> and <tt>:unless</tt> options</h3>
+<div class="para"><p>You can also use a string that will be evaluated using <tt>:eval</tt> and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Person <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>surname<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"name.nil?"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_using_a_proc_object_with_the_tt_if_tt_and_tt_unless_tt_options">5.3. Using a Proc object with the <tt>:if</tt> and :<tt>unless</tt> options</h3>
+<div class="para"><p>Finally, it's possible to associate <tt>:if</tt> and <tt>:unless</tt> with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_confirmation_of <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> <span style="color: #990000">=&gt;</span> Proc<span style="color: #990000">.</span>new <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>a<span style="color: #990000">|</span> a<span style="color: #990000">.</span>password<span style="color: #990000">.</span>blank? <span style="color: #FF0000">}</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_writing_your_own_validation_methods">6. Writing your own validation methods</h2>
+<div class="sectionbody">
+<div class="para"><p>When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's <tt>errors</tt> collection.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> validate_on_create
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods, passing it the symbols for the methods' names.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span> <span style="color: #990000">:</span>discount_cannot_be_more_than_total_value
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> expiration_date_cannot_be_in_the_past
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> discount_cannot_be_greater_than_total_value
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> discount <span style="color: #990000">&lt;=</span> total_value
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_changelog">7. Changelog</h2>
+<div class="sectionbody">
+<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks">http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks</a></p></div>
+</div>
+
+ </div>
+ </div>
+</body>
+</html>
diff --git a/railties/doc/guides/html/authors.html b/railties/doc/guides/html/authors.html
index 973cf7cd2e..a54135b14d 100644
--- a/railties/doc/guides/html/authors.html
+++ b/railties/doc/guides/html/authors.html
@@ -218,6 +218,19 @@ work with Rails. His near-daily links and other blogging can be found at <a href
Cofounder of <a href="http://www.eventioz.com">Eventioz</a>. He has been using Rails since 2006 and contributing since early 2008.
Can be found at gmail, twitter, freenode, everywhere as miloops.</p></div>
</div></div>
+<div class="sidebarblock" id="hawe">
+<div class="sidebar-content">
+<div class="sidebar-title">Heiko Webers</div>
+<div class="para"><p>Heiko Webers is the founder of <a href="http://www.bauland42.de">bauland42</a>, a German web application security consulting and development
+company focused on Ruby on Rails. He blogs at <a href="http://www.rorsecurity.info">http://www.rorsecurity.info</a>. After 10 years of desktop application development,
+Heiko has rarely looked back.</p></div>
+</div></div>
+<div class="sidebarblock" id="toretore">
+<div class="sidebar-content">
+<div class="sidebar-title">Tore Darell</div>
+<div class="para"><p>Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
+and unobtrusive JavaScript. His home on the internet is his blog <a href="http://tore.darell.no/">Sneaky Abstractions</a>.</p></div>
+</div></div>
</div>
</div>
diff --git a/railties/doc/guides/html/caching_with_rails.html b/railties/doc/guides/html/caching_with_rails.html
index df30c46c35..7aa5999e1a 100644
--- a/railties/doc/guides/html/caching_with_rails.html
+++ b/railties/doc/guides/html/caching_with_rails.html
@@ -235,48 +235,54 @@ need to return to those hungry web clients in the shortest time possible.</p></d
<div class="sectionbody">
<div class="para"><p>This is an introduction to the three types of caching techniques that Rails
provides by default without the use of any third party plugins.</p></div>
-<div class="para"><p>To get started make sure Base.perform_caching is set to true for your
-environment.</p></div>
+<div class="para"><p>To get started make sure config.action_controller.perform_caching is set
+to true for your environment. This flag is normally set in the
+corresponding config/environments/*.rb and caching is disabled by default
+there for development and test, and enabled for production.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>Base<span style="color: #990000">.</span>perform_caching <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+<pre><tt>config<span style="color: #990000">.</span>action_controller<span style="color: #990000">.</span>perform_caching <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
</tt></pre></div></div>
<h3 id="_page_caching">1.1. Page Caching</h3>
<div class="para"><p>Page caching is a Rails mechanism which allows the request for a generated
page to be fulfilled by the webserver, without ever having to go through the
-Rails stack at all. Obviously, this is super fast. Unfortunately, it can't be
+Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
applied to every situation (such as pages that need authentication) and since
the webserver is literally just serving a file from the filesystem, cache
expiration is an issue that needs to be dealt with.</p></div>
<div class="para"><p>So, how do you enable this super-fast cache behavior? Simple, let's say you
-have a controller called ProductController and a <em>list</em> action that lists all
+have a controller called ProductsController and a <em>list</em> action that lists all
the products</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>index
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The first time anyone requestsion products/list, Rails will generate a file
-called list.html and the webserver will then look for that file before it
-passes the next request for products/list to your Rails application.</p></div>
+<div class="para"><p>The first time anyone requests products/index, Rails will generate a file
+called index.html and the webserver will then look for that file before it
+passes the next request for products/index to your Rails application.</p></div>
<div class="para"><p>By default, the page cache directory is set to Rails.public_path (which is
-usually set to RAILS_ROOT + "/public") and this can be configured by changing
-the configuration setting Base.cache_public_directory</p></div>
-<div class="para"><p>The page caching mechanism will automatically add a .html exxtension to
+usually set to RAILS_ROOT + "/public") and this can be configured by
+changing the configuration setting ActionController::Base.page_cache_directory. Changing the
+default from /public helps avoid naming conflicts, since you may want to
+put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the
+cached files from.</p></div>
+<div class="para"><p>The Page Caching mechanism will automatically add a .html exxtension to
requests for pages that do not have an extension to make it easy for the
webserver to find those pages and this can be configured by changing the
-configuration setting Base.page_cache_extension</p></div>
+configuration setting ActionController::Base.page_cache_extension.</p></div>
<div class="para"><p>In order to expire this page when a new product is added we could extend our
example controler like this:</p></div>
<div class="listingblock">
@@ -284,9 +290,9 @@ example controler like this:</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -299,11 +305,11 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>If you want a more complicated expiration scheme, you can use cache sweepers
to expire cached objects when things change. This is covered in the section on Sweepers.</p></div>
<h3 id="_action_caching">1.2. Action Caching</h3>
-<div class="para"><p>One of the issues with page caching is that you cannot use it for pages that
+<div class="para"><p>One of the issues with Page Caching is that you cannot use it for pages that
require to restrict access somehow. This is where Action Caching comes in.
Action Caching works like Page Caching except for the fact that the incoming
web request does go from the webserver to the Rails stack and Action Pack so
-that before_filters can be run on it before the cache is served, so that
+that before filters can be run on it before the cache is served, so that
authentication and other restrictions can be used while still serving the
result of the output from a cached copy.</p></div>
<div class="para"><p>Clearing the cache works in the exact same way as with Page Caching.</p></div>
@@ -314,10 +320,10 @@ object, but still cache those pages:</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -336,7 +342,7 @@ action should be cached. Also, you can use :layout &#8658; false to cache withou
layout so that dynamic information in the layout such as logged in user info
or the number of items in the cart can be left uncached. This feature is
available as of Rails 2.2.</p></div>
-<div class="para"><p>[More: more examples? Walk-through of action caching from request to response?
+<div class="para"><p>[More: more examples? Walk-through of Action Caching from request to response?
Description of Rake tasks to clear cached files? Show example of
subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
to expire_action?]</p></div>
@@ -346,13 +352,13 @@ a page or action and serving it out to the world. Unfortunately, dynamic web
applications usually build pages with a variety of components not all of which
have the same caching characteristics. In order to address such a dynamically
created page where different parts of the page need to be cached and expired
-differently Rails provides a mechanism called Fragment caching.</p></div>
-<div class="para"><p>Fragment caching allows a fragment of view logic to be wrapped in a cache
+differently Rails provides a mechanism called Fragment Caching.</p></div>
+<div class="para"><p>Fragment Caching allows a fragment of view logic to be wrapped in a cache
block and served out of the cache store when the next request comes in.</p></div>
-<div class="para"><p>As an example, if you wanted to show all the orders placed on your website in
-real time and didn't want to cache that part of the page, but did want to
-cache the part of the page which lists all products available, you could use
-this piece of code:</p></div>
+<div class="para"><p>As an example, if you wanted to show all the orders placed on your website
+in real time and didn't want to cache that part of the page, but did want
+to cache the part of the page which lists all products available, you
+could use this piece of code:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -371,7 +377,7 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>The cache block in our example will bind to the action that called it and is
written out to the same place as the Action Cache, which means that if you
-want to cache multiple fragments per action, you should provide an action_path to the cache call:</p></div>
+want to cache multiple fragments per action, you should provide an action_suffix to the cache call:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -439,10 +445,10 @@ following:</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
cache_sweeper <span style="color: #990000">:</span>store_sweeper<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
@@ -468,10 +474,10 @@ database again.</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
cache_sweeper <span style="color: #990000">:</span>store_sweeper<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
diff --git a/railties/doc/guides/html/command_line.html b/railties/doc/guides/html/command_line.html
new file mode 100644
index 0000000000..2add20446e
--- /dev/null
+++ b/railties/doc/guides/html/command_line.html
@@ -0,0 +1,434 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <title>A Guide to The Rails Command Line</title>
+ <!--[if lt IE 8]>
+ <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
+ <![endif]-->
+ <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
+ <style type="text/css">
+ div#container {
+ max-width: 900px;
+ padding-bottom: 3em;
+}
+
+div#content {
+ margin-left: 200px;
+}
+
+div#container.notoc {
+ max-width: 600px;
+}
+
+.notoc div#content {
+ margin-left: 0;
+}
+
+pre {
+ line-height: 1.4em;
+}
+
+#content p tt {
+ background: #eeeeee;
+ border: solid 1px #cccccc;
+ padding: 3px;
+}
+
+dt {
+ font-weight: bold;
+}
+
+#content dt tt {
+ font-size: 10pt;
+}
+
+dd {
+ margin-left: 3em;
+}
+
+#content dt tt, #content pre tt {
+ background: none;
+ padding: 0;
+ border: 0;
+}
+
+#content .olist ol {
+ margin-left: 2em;
+}
+
+#header {
+ position: relative;
+ max-width: 840px;
+ margin-left: auto;
+ margin-right: auto;
+}
+
+#header.notoc {
+ max-width: 580px;
+}
+
+#logo {
+ position: absolute;
+ left: 10px;
+ top: 10px;
+ width: 110px;
+ height: 140px;
+}
+
+div#header h1#site_title {
+ background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
+ position: absolute;
+ width: 392px;
+ height: 55px;
+ left: 145px;
+ top: 20px;
+ margin: 0;
+ padding: 0;
+}
+
+#site_title span {
+ display: none;
+}
+
+#site_title_tagline {
+ display: none;
+}
+
+ul#navMain {
+ position: absolute;
+ margin: 0;
+ padding: 0;
+ top: 97px;
+ left: 145px;
+}
+
+.left-floaty, .right-floaty {
+ padding: 15px;
+}
+
+.admonitionblock,
+.tableblock {
+ margin-left: 1em;
+ margin-right: 1em;
+ margin-top: 0.25em;
+ margin-bottom: 1em;
+}
+
+.admonitionblock .icon {
+ padding-right: 8px;
+}
+
+.admonitionblock .content {
+ border: solid 1px #ffda78;
+ background: #fffebd;
+ padding: 10px;
+ padding-top: 8px;
+ padding-bottom: 8px;
+}
+
+.admonitionblock .title {
+ font-size: 140%;
+ margin-bottom: 0.5em;
+}
+
+.tableblock table {
+ border: solid 1px #aaaaff;
+ background: #f0f0ff;
+}
+
+.tableblock th {
+ background: #e0e0e0;
+}
+
+.tableblock th,
+.tableblock td {
+ padding: 3px;
+ padding-left: 5px;
+ padding-right: 5px;
+}
+
+.sidebarblock {
+ margin-top: 0.25em;
+ margin: 1em;
+ border: solid 1px #ccccbb;
+ padding: 8px;
+ background: #ffffe0;
+}
+
+.sidebarblock .sidebar-title {
+ font-size: 140%;
+ font-weight: 600;
+ margin-bottom: 0.3em;
+}
+
+.sidebarblock .sidebar-content > .para:last-child > p {
+ margin-bottom: 0;
+}
+
+.sidebarblock .sidebar-title a {
+ text-decoration: none;
+}
+
+.sidebarblock .sidebar-title a:hover {
+ text-decoration: underline;
+}
+
+ </style>
+</head>
+<body>
+ <div id="header" >
+ <div id="logo">
+ <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
+ </div>
+
+ <h1 id="site_title"><span>Ruby on Rails</span></h1>
+ <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
+
+ <ul id="navMain">
+ <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
+ <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
+ </ul>
+ </div>
+
+ <div id="container">
+
+ <div id="sidebar">
+ <h2>Chapters</h2>
+ <ol>
+ <li>
+ <a href="#_command_line_basics">Command Line Basics</a>
+ <ul>
+
+ <li><a href="#_rails">rails</a></li>
+
+ <li><a href="#_server">server</a></li>
+
+ <li><a href="#_generate">generate</a></li>
+
+ </ul>
+ </li>
+ </ol>
+ </div>
+
+ <div id="content">
+ <h1>A Guide to The Rails Command Line</h1>
+ <div id="preamble">
+<div class="sectionbody">
+<div class="para"><p>Rails comes with every command line tool you'll need to</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Create a Rails application
+</p>
+</li>
+<li>
+<p>
+Generate models, controllers, database migrations, and unit tests
+</p>
+</li>
+<li>
+<p>
+Start a development server
+</p>
+</li>
+<li>
+<p>
+Mess with objects through an interactive shell
+</p>
+</li>
+<li>
+<p>
+Profile and benchmark your new creation
+</p>
+</li>
+</ul></div>
+<div class="para"><p>&#8230; and much, much more! (Buy now!)</p></div>
+<div class="para"><p>This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.</p></div>
+</div>
+</div>
+<h2 id="_command_line_basics">1. Command Line Basics</h2>
+<div class="sectionbody">
+<div class="para"><p>There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+console
+</p>
+</li>
+<li>
+<p>
+server
+</p>
+</li>
+<li>
+<p>
+rake
+</p>
+</li>
+<li>
+<p>
+generate
+</p>
+</li>
+<li>
+<p>
+rails
+</p>
+</li>
+</ul></div>
+<div class="para"><p>Let's create a simple Rails application to step through each of these commands in context.</p></div>
+<h3 id="_rails">1.1. rails</h3>
+<div class="para"><p>The first thing we'll want to do is create a new Rails application by running the <tt>rails</tt> command after installing Rails.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">You know you need the rails gem installed by typing <tt>gem install rails</tt> first, right? Okay, okay, just making sure.</td>
+</tr></table>
+</div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>$ rails commandsapp
+
+ create
+ create app/controllers
+ create app/helpers
+ create app/models
+ <span style="color: #990000">...</span>
+ <span style="color: #990000">...</span>
+ create log/production<span style="color: #990000">.</span>log
+ create log/development<span style="color: #990000">.</span>log
+ create log/test<span style="color: #990000">.</span>log
+</tt></pre></div></div>
+<div class="para"><p>Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">This output will seem very familiar when we get to the <tt>generate</tt> command. Creepy foreshadowing!</td>
+</tr></table>
+</div>
+<h3 id="_server">1.2. server</h3>
+<div class="para"><p>Let's try it! The <tt>server</tt> command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]</td>
+</tr></table>
+</div>
+<div class="para"><p>Here we'll flex our <tt>server</tt> command, which without any prodding of any kind will run our new shiny Rails app:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>$ cd commandsapp
+$ <span style="color: #990000">.</span>/script/server
+<span style="color: #990000">=&gt;</span> Booting WEBrick<span style="color: #990000">...</span>
+<span style="color: #990000">=&gt;</span> Rails <span style="color: #993399">2.2</span><span style="color: #990000">.</span><span style="color: #993399">0</span> application started on http<span style="color: #990000">://</span><span style="color: #993399">0.0</span><span style="color: #990000">.</span><span style="color: #993399">0.0</span><span style="color: #990000">:</span><span style="color: #993399">3000</span>
+<span style="color: #990000">=&gt;</span> Ctrl-C to shutdown server<span style="color: #990000">;</span> call with --help <span style="font-weight: bold"><span style="color: #0000FF">for</span></span> options
+<span style="color: #990000">[</span><span style="color: #993399">2008</span>-<span style="color: #993399">11</span>-<span style="color: #993399">04</span> <span style="color: #993399">10</span><span style="color: #990000">:</span><span style="color: #993399">11</span><span style="color: #990000">:</span><span style="color: #993399">38</span><span style="color: #990000">]</span> INFO WEBrick <span style="color: #993399">1.3</span><span style="color: #990000">.</span><span style="color: #993399">1</span>
+<span style="color: #990000">[</span><span style="color: #993399">2008</span>-<span style="color: #993399">11</span>-<span style="color: #993399">04</span> <span style="color: #993399">10</span><span style="color: #990000">:</span><span style="color: #993399">11</span><span style="color: #990000">:</span><span style="color: #993399">38</span><span style="color: #990000">]</span> INFO ruby <span style="color: #993399">1.8</span><span style="color: #990000">.</span><span style="color: #993399">5</span> <span style="color: #990000">(</span><span style="color: #993399">2006</span>-<span style="color: #993399">12</span>-<span style="color: #993399">04</span><span style="color: #990000">)</span> <span style="color: #990000">[</span>i486-linux<span style="color: #990000">]</span>
+<span style="color: #990000">[</span><span style="color: #993399">2008</span>-<span style="color: #993399">11</span>-<span style="color: #993399">04</span> <span style="color: #993399">10</span><span style="color: #990000">:</span><span style="color: #993399">11</span><span style="color: #990000">:</span><span style="color: #993399">38</span><span style="color: #990000">]</span> INFO WEBrick<span style="color: #990000">::</span>HTTPServer<span style="font-style: italic"><span style="color: #9A1900">#start: pid=18994 port=3000</span></span>
+</tt></pre></div></div>
+<div class="para"><p>WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to <a href="http://localhost:3000">http://localhost:3000</a>. I'll wait.</p></div>
+<div class="para"><p>See? Cool! It doesn't do much yet, but we'll change that.</p></div>
+<h3 id="_generate">1.3. generate</h3>
+<div class="para"><p>The <tt>generate</tt> command uses templates to create a whole lot of things. You can always find out what's available by running <tt>generate</tt> by itself. Let's do that:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>$ <span style="color: #990000">.</span>/script/generate
+Usage<span style="color: #990000">:</span> <span style="color: #990000">.</span>/script/generate generator <span style="color: #990000">[</span>options<span style="color: #990000">]</span> <span style="color: #990000">[</span>args<span style="color: #990000">]</span>
+
+<span style="color: #990000">...</span>
+<span style="color: #990000">...</span>
+
+Installed Generators
+ Builtin<span style="color: #990000">:</span> controller<span style="color: #990000">,</span> integration_test<span style="color: #990000">,</span> mailer<span style="color: #990000">,</span> migration<span style="color: #990000">,</span> model<span style="color: #990000">,</span> observer<span style="color: #990000">,</span> performance_test<span style="color: #990000">,</span> plugin<span style="color: #990000">,</span> resource<span style="color: #990000">,</span> scaffold<span style="color: #990000">,</span> session_migration
+
+<span style="color: #990000">...</span>
+<span style="color: #990000">...</span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!</td>
+</tr></table>
+</div>
+<div class="para"><p>Using generators will save you a large amount of time by writing <strong>boilerplate code</strong> for you &#8212; necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?</p></div>
+<div class="para"><p>Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like <tt>rails</tt> or <tt>./script/generate</tt>). For others, you can try adding <tt>&#8212;help</tt> or <tt>-h</tt> to the end, as in <tt>./script/server &#8212;help</tt>.</td>
+</tr></table>
+</div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>$ <span style="color: #990000">.</span>/script/generate controller
+Usage<span style="color: #990000">:</span> <span style="color: #990000">.</span>/script/generate controller ControllerName <span style="color: #990000">[</span>options<span style="color: #990000">]</span>
+
+<span style="color: #990000">...</span>
+<span style="color: #990000">...</span>
+
+Example<span style="color: #990000">:</span>
+ `<span style="color: #990000">.</span>/script/generate controller CreditCard open debit credit close`
+
+ Credit card controller with URLs like /credit_card/debit<span style="color: #990000">.</span>
+ Controller<span style="color: #990000">:</span> app/controllers/credit_card_controller<span style="color: #990000">.</span>rb
+ Views<span style="color: #990000">:</span> app/views/credit_card/debit<span style="color: #990000">.</span>html<span style="color: #990000">.</span>erb <span style="color: #990000">[...]</span>
+ Helper<span style="color: #990000">:</span> app/helpers/credit_card_helper<span style="color: #990000">.</span>rb
+ Test<span style="color: #990000">:</span> test/functional/credit_card_controller_test<span style="color: #990000">.</span>rb
+
+Modules Example<span style="color: #990000">:</span>
+ `<span style="color: #990000">.</span>/script/generate controller <span style="color: #FF0000">'admin/credit_card'</span> <span style="font-weight: bold"><span style="color: #0000FF">suspend</span></span> late_fee`
+
+ Credit card admin controller with URLs /admin/credit_card/suspend<span style="color: #990000">.</span>
+ Controller<span style="color: #990000">:</span> app/controllers/admin/credit_card_controller<span style="color: #990000">.</span>rb
+ Views<span style="color: #990000">:</span> app/views/admin/credit_card/debit<span style="color: #990000">.</span>html<span style="color: #990000">.</span>erb <span style="color: #990000">[...]</span>
+ Helper<span style="color: #990000">:</span> app/helpers/admin/credit_card_helper<span style="color: #990000">.</span>rb
+ Test<span style="color: #990000">:</span> test/functional/admin/credit_card_controller_test<span style="color: #990000">.</span>rb
+</tt></pre></div></div>
+<div class="para"><p>Ah, the controller generator is expecting parameters in the form of <tt>generate controller ControllerName action1 action2</tt>. Let's make a <tt>Greetings</tt> controller with an action of <strong>hello</strong>, which will say something nice to us.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>$ <span style="color: #990000">.</span>/script/generate controller Greeting hello
+ exists app/controllers<span style="color: #990000">/</span>
+ exists app/helpers<span style="color: #990000">/</span>
+ create app/views/greeting
+ exists test/functional<span style="color: #990000">/</span>
+ create app/controllers/greetings_controller<span style="color: #990000">.</span>rb
+ create test/functional/greetings_controller_test<span style="color: #990000">.</span>rb
+ create app/helpers/greetings_helper<span style="color: #990000">.</span>rb
+ create app/views/greetings/hello<span style="color: #990000">.</span>html<span style="color: #990000">.</span>erb
+</tt></pre></div></div>
+<div class="para"><p>Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!</p></div>
+</div>
+
+ </div>
+ </div>
+</body>
+</html>
diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html
new file mode 100644
index 0000000000..4aa3a0f545
--- /dev/null
+++ b/railties/doc/guides/html/configuring.html
@@ -0,0 +1,438 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <title>Configuring Rails Applications</title>
+ <!--[if lt IE 8]>
+ <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
+ <![endif]-->
+ <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
+ <style type="text/css">
+ div#container {
+ max-width: 900px;
+ padding-bottom: 3em;
+}
+
+div#content {
+ margin-left: 200px;
+}
+
+div#container.notoc {
+ max-width: 600px;
+}
+
+.notoc div#content {
+ margin-left: 0;
+}
+
+pre {
+ line-height: 1.4em;
+}
+
+#content p tt {
+ background: #eeeeee;
+ border: solid 1px #cccccc;
+ padding: 3px;
+}
+
+dt {
+ font-weight: bold;
+}
+
+#content dt tt {
+ font-size: 10pt;
+}
+
+dd {
+ margin-left: 3em;
+}
+
+#content dt tt, #content pre tt {
+ background: none;
+ padding: 0;
+ border: 0;
+}
+
+#content .olist ol {
+ margin-left: 2em;
+}
+
+#header {
+ position: relative;
+ max-width: 840px;
+ margin-left: auto;
+ margin-right: auto;
+}
+
+#header.notoc {
+ max-width: 580px;
+}
+
+#logo {
+ position: absolute;
+ left: 10px;
+ top: 10px;
+ width: 110px;
+ height: 140px;
+}
+
+div#header h1#site_title {
+ background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
+ position: absolute;
+ width: 392px;
+ height: 55px;
+ left: 145px;
+ top: 20px;
+ margin: 0;
+ padding: 0;
+}
+
+#site_title span {
+ display: none;
+}
+
+#site_title_tagline {
+ display: none;
+}
+
+ul#navMain {
+ position: absolute;
+ margin: 0;
+ padding: 0;
+ top: 97px;
+ left: 145px;
+}
+
+.left-floaty, .right-floaty {
+ padding: 15px;
+}
+
+.admonitionblock,
+.tableblock {
+ margin-left: 1em;
+ margin-right: 1em;
+ margin-top: 0.25em;
+ margin-bottom: 1em;
+}
+
+.admonitionblock .icon {
+ padding-right: 8px;
+}
+
+.admonitionblock .content {
+ border: solid 1px #ffda78;
+ background: #fffebd;
+ padding: 10px;
+ padding-top: 8px;
+ padding-bottom: 8px;
+}
+
+.admonitionblock .title {
+ font-size: 140%;
+ margin-bottom: 0.5em;
+}
+
+.tableblock table {
+ border: solid 1px #aaaaff;
+ background: #f0f0ff;
+}
+
+.tableblock th {
+ background: #e0e0e0;
+}
+
+.tableblock th,
+.tableblock td {
+ padding: 3px;
+ padding-left: 5px;
+ padding-right: 5px;
+}
+
+.sidebarblock {
+ margin-top: 0.25em;
+ margin: 1em;
+ border: solid 1px #ccccbb;
+ padding: 8px;
+ background: #ffffe0;
+}
+
+.sidebarblock .sidebar-title {
+ font-size: 140%;
+ font-weight: 600;
+ margin-bottom: 0.3em;
+}
+
+.sidebarblock .sidebar-content > .para:last-child > p {
+ margin-bottom: 0;
+}
+
+.sidebarblock .sidebar-title a {
+ text-decoration: none;
+}
+
+.sidebarblock .sidebar-title a:hover {
+ text-decoration: underline;
+}
+
+ </style>
+</head>
+<body>
+ <div id="header" >
+ <div id="logo">
+ <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
+ </div>
+
+ <h1 id="site_title"><span>Ruby on Rails</span></h1>
+ <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
+
+ <ul id="navMain">
+ <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
+ <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
+ </ul>
+ </div>
+
+ <div id="container">
+
+ <div id="sidebar">
+ <h2>Chapters</h2>
+ <ol>
+ <li>
+ <a href="#_locations_for_initialization_code">Locations for Initialization Code</a>
+ </li>
+ <li>
+ <a href="#_using_a_preinitializer">Using a Preinitializer</a>
+ </li>
+ <li>
+ <a href="#_configuring_rails_components">Configuring Rails Components</a>
+ <ul>
+
+ <li><a href="#_configuring_active_record">Configuring Active Record</a></li>
+
+ <li><a href="#_configuring_action_controller">Configuring Action Controller</a></li>
+
+ <li><a href="#_configuring_action_view">Configuring Action View</a></li>
+
+ <li><a href="#_configuring_action_mailer">Configuring Action Mailer</a></li>
+
+ <li><a href="#_configuring_active_resource">Configuring Active Resource</a></li>
+
+ <li><a href="#_configuring_active_support">Configuring Active Support</a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_using_initializers">Using Initializers</a>
+ </li>
+ <li>
+ <a href="#_using_an_after_initializer">Using an After-Initializer</a>
+ </li>
+ <li>
+ <a href="#_changelog">Changelog</a>
+ </li>
+ </ol>
+ </div>
+
+ <div id="content">
+ <h1>Configuring Rails Applications</h1>
+ <div id="preamble">
+<div class="sectionbody">
+<div class="para"><p>This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Adjust the behavior of your Rails applications
+</p>
+</li>
+<li>
+<p>
+Add additional code to be run at application start time
+</p>
+</li>
+</ul></div>
+</div>
+</div>
+<h2 id="_locations_for_initialization_code">1. Locations for Initialization Code</h2>
+<div class="sectionbody">
+<div class="para"><p>preinitializers
+environment.rb first
+env-specific files
+initializers (load_application_initializers)
+after-initializer</p></div>
+</div>
+<h2 id="_using_a_preinitializer">2. Using a Preinitializer</h2>
+<div class="sectionbody">
+</div>
+<h2 id="_configuring_rails_components">3. Configuring Rails Components</h2>
+<div class="sectionbody">
+<h3 id="_configuring_active_record">3.1. Configuring Active Record</h3>
+<h3 id="_configuring_action_controller">3.2. Configuring Action Controller</h3>
+<h3 id="_configuring_action_view">3.3. Configuring Action View</h3>
+<h3 id="_configuring_action_mailer">3.4. Configuring Action Mailer</h3>
+<h3 id="_configuring_active_resource">3.5. Configuring Active Resource</h3>
+<h3 id="_configuring_active_support">3.6. Configuring Active Support</h3>
+</div>
+<h2 id="_using_initializers">4. Using Initializers</h2>
+<div class="sectionbody">
+<div class="literalblock">
+<div class="content">
+<pre><tt>organization, controlling load order</tt></pre>
+</div></div>
+</div>
+<h2 id="_using_an_after_initializer">5. Using an After-Initializer</h2>
+<div class="sectionbody">
+</div>
+<h2 id="_changelog">6. Changelog</h2>
+<div class="sectionbody">
+<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28">Lighthouse ticket</a></p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+November 5, 2008: Rough outline by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
+</p>
+</li>
+</ul></div>
+<div class="para"><p>actionmailer/lib/action_mailer/base.rb
+257: cattr_accessor :logger
+267: cattr_accessor :smtp_settings
+273: cattr_accessor :sendmail_settings
+276: cattr_accessor :raise_delivery_errors
+282: cattr_accessor :perform_deliveries
+285: cattr_accessor :deliveries
+288: cattr_accessor :default_charset
+291: cattr_accessor :default_content_type
+294: cattr_accessor :default_mime_version
+297: cattr_accessor :default_implicit_parts_order
+299: cattr_reader :protected_instance_variables</p></div>
+<div class="para"><p>actionmailer/Rakefile
+36: rdoc.options &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>actionpack/lib/action_controller/base.rb
+263: cattr_reader :protected_instance_variables
+273: cattr_accessor :asset_host
+279: cattr_accessor :consider_all_requests_local
+285: cattr_accessor :allow_concurrency
+317: cattr_accessor :param_parsers
+321: cattr_accessor :default_charset
+325: cattr_accessor :logger
+329: cattr_accessor :resource_action_separator
+333: cattr_accessor :resources_path_names
+337: cattr_accessor :request_forgery_protection_token
+341: cattr_accessor :optimise_named_routes
+351: cattr_accessor :use_accept_header
+361: cattr_accessor :relative_url_root</p></div>
+<div class="para"><p>actionpack/lib/action_controller/caching/pages.rb
+55: cattr_accessor :page_cache_directory
+58: cattr_accessor :page_cache_extension</p></div>
+<div class="para"><p>actionpack/lib/action_controller/caching.rb
+37: cattr_reader :cache_store
+48: cattr_accessor :perform_caching</p></div>
+<div class="para"><p>actionpack/lib/action_controller/dispatcher.rb
+98: cattr_accessor :error_file_path</p></div>
+<div class="para"><p>actionpack/lib/action_controller/mime_type.rb
+24: cattr_reader :html_types, :unverifiable_types</p></div>
+<div class="para"><p>actionpack/lib/action_controller/rescue.rb
+36: base.cattr_accessor :rescue_responses
+40: base.cattr_accessor :rescue_templates</p></div>
+<div class="para"><p>actionpack/lib/action_controller/session/active_record_store.rb
+60: cattr_accessor :data_column_name
+170: cattr_accessor :connection
+173: cattr_accessor :table_name
+177: cattr_accessor :session_id_column
+181: cattr_accessor :data_column
+282: cattr_accessor :session_class</p></div>
+<div class="para"><p>actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+44: cattr_accessor :included_tags, :instance_writer &#8658; false</p></div>
+<div class="para"><p>actionpack/lib/action_view/base.rb
+189: cattr_accessor :debug_rjs
+193: cattr_accessor :warn_cache_misses</p></div>
+<div class="para"><p>actionpack/lib/action_view/helpers/active_record_helper.rb
+7: cattr_accessor :field_error_proc</p></div>
+<div class="para"><p>actionpack/lib/action_view/helpers/form_helper.rb
+805: cattr_accessor :default_form_builder</p></div>
+<div class="para"><p>actionpack/lib/action_view/template_handlers/erb.rb
+47: cattr_accessor :erb_trim_mode</p></div>
+<div class="para"><p>actionpack/test/active_record_unit.rb
+5: cattr_accessor :able_to_connect
+6: cattr_accessor :connected</p></div>
+<div class="para"><p>actionpack/test/controller/filters_test.rb
+286: cattr_accessor :execution_log</p></div>
+<div class="para"><p>actionpack/test/template/form_options_helper_test.rb
+3:TZInfo::Timezone.cattr_reader :loaded_zones</p></div>
+<div class="para"><p>activemodel/lib/active_model/errors.rb
+28: cattr_accessor :default_error_messages</p></div>
+<div class="para"><p>activemodel/Rakefile
+19: rdoc.options &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>activerecord/lib/active_record/attribute_methods.rb
+9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer &#8658; false
+11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer &#8658; false</p></div>
+<div class="para"><p>activerecord/lib/active_record/base.rb
+394: cattr_accessor :logger, :instance_writer &#8658; false
+443: cattr_accessor :configurations, :instance_writer &#8658; false
+450: cattr_accessor :primary_key_prefix_type, :instance_writer &#8658; false
+456: cattr_accessor :table_name_prefix, :instance_writer &#8658; false
+461: cattr_accessor :table_name_suffix, :instance_writer &#8658; false
+467: cattr_accessor :pluralize_table_names, :instance_writer &#8658; false
+473: cattr_accessor :colorize_logging, :instance_writer &#8658; false
+478: cattr_accessor :default_timezone, :instance_writer &#8658; false
+487: cattr_accessor :schema_format , :instance_writer &#8658; false
+491: cattr_accessor :timestamped_migrations , :instance_writer &#8658; false</p></div>
+<div class="para"><p>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
+11: cattr_accessor :connection_handler, :instance_writer &#8658; false</p></div>
+<div class="para"><p>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+166: cattr_accessor :emulate_booleans</p></div>
+<div class="para"><p>activerecord/lib/active_record/fixtures.rb
+498: cattr_accessor :all_loaded_fixtures</p></div>
+<div class="para"><p>activerecord/lib/active_record/locking/optimistic.rb
+38: base.cattr_accessor :lock_optimistically, :instance_writer &#8658; false</p></div>
+<div class="para"><p>activerecord/lib/active_record/migration.rb
+259: cattr_accessor :verbose</p></div>
+<div class="para"><p>activerecord/lib/active_record/schema_dumper.rb
+13: cattr_accessor :ignore_tables</p></div>
+<div class="para"><p>activerecord/lib/active_record/serializers/json_serializer.rb
+4: base.cattr_accessor :include_root_in_json, :instance_writer &#8658; false</p></div>
+<div class="para"><p>activerecord/Rakefile
+142: rdoc.options &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>activerecord/test/cases/lifecycle_test.rb
+61: cattr_reader :last_inherited</p></div>
+<div class="para"><p>activerecord/test/cases/mixin_test.rb
+9: cattr_accessor :forced_now_time</p></div>
+<div class="para"><p>activeresource/lib/active_resource/base.rb
+206: cattr_accessor :logger</p></div>
+<div class="para"><p>activeresource/Rakefile
+43: rdoc.options &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <em>-A cattr_accessor=object</em></p></div>
+<div class="para"><p>activesupport/lib/active_support/buffered_logger.rb
+17: cattr_accessor :silencer</p></div>
+<div class="para"><p>activesupport/lib/active_support/cache.rb
+81: cattr_accessor :logger</p></div>
+<div class="para"><p>activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
+5:# cattr_accessor :hair_colors
+10: def cattr_reader(*syms)
+29: def cattr_writer(*syms)
+50: def cattr_accessor(*syms)
+51: cattr_reader(*syms)
+52: cattr_writer(*syms)</p></div>
+<div class="para"><p>activesupport/lib/active_support/core_ext/logger.rb
+34: cattr_accessor :silencer</p></div>
+<div class="para"><p>activesupport/test/core_ext/class/attribute_accessor_test.rb
+6: cattr_accessor :foo
+7: cattr_accessor :bar, :instance_writer &#8658; false</p></div>
+<div class="para"><p>activesupport/test/core_ext/module/synchronization_test.rb
+6: @target.cattr_accessor :mutex, :instance_writer &#8658; false</p></div>
+<div class="para"><p>railties/doc/guides/html/creating_plugins.html
+786: cattr_accessor &lt;span style="color: #990000"&gt;:&lt;/span&gt;yaffle_text_field&lt;span style="color: #990000"&gt;,&lt;/span&gt; &lt;span style="color: #990000"&gt;:&lt;/span&gt;yaffle_date_field
+860: cattr_accessor &lt;span style="color: #990000"&gt;:&lt;/span&gt;yaffle_text_field&lt;span style="color: #990000"&gt;,&lt;/span&gt; &lt;span style="color: #990000"&gt;:&lt;/span&gt;yaffle_date_field</p></div>
+<div class="para"><p>railties/lib/rails_generator/base.rb
+93: cattr_accessor :logger</p></div>
+<div class="para"><p>railties/Rakefile
+265: rdoc.options &lt;&lt; <em>&#8212;line-numbers</em> &lt;&lt; <em>&#8212;inline-source</em> &lt;&lt; <em>&#8212;accessor</em> &lt;&lt; <em>cattr_accessor=object</em></p></div>
+<div class="para"><p>railties/test/rails_info_controller_test.rb
+12: cattr_accessor :local_request</p></div>
+<div class="para"><p>Rakefile
+32: rdoc.options &lt;&lt; <em>-A cattr_accessor=object</em></p></div>
+</div>
+
+ </div>
+ </div>
+</body>
+</html>
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 48d5f03687..375d216b4a 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -204,26 +204,61 @@ ul#navMain {
<li><a href="#_create_the_basic_app">Create the basic app</a></li>
- <li><a href="#_create_the_plugin">Create the plugin</a></li>
+ <li><a href="#_generate_the_plugin_skeleton">Generate the plugin skeleton</a></li>
<li><a href="#_setup_the_plugin_for_testing">Setup the plugin for testing</a></li>
+ <li><a href="#_run_the_plugin_tests">Run the plugin tests</a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_extending_core_classes">Extending core classes</a>
+ <ul>
+
+ <li><a href="#_creating_the_test">Creating the test</a></li>
+
+ <li><a href="#_organize_your_files">Organize your files</a></li>
+
+ <li><a href="#_working_with_init_rb">Working with init.rb</a></li>
+
</ul>
</li>
<li>
- <a href="#_add_a_tt_to_squawk_tt_method_to_string">Add a <tt>to_squawk</tt> method to String</a>
+ <a href="#_add_an_tt_acts_as_yaffle_tt_method_to_active_record">Add an <tt>acts_as_yaffle</tt> method to Active Record</a>
+ <ul>
+
+ <li><a href="#_add_a_class_method">Add a class method</a></li>
+
+ <li><a href="#_add_an_instance_method">Add an instance method</a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_create_a_generator">Create a generator</a>
+ <ul>
+
+ <li><a href="#_testing_generators">Testing generators</a></li>
+
+ <li><a href="#_adding_to_the_manifest">Adding to the manifest</a></li>
+
+ <li><a href="#_manually_test_the_generator">Manually test the generator</a></li>
+
+ <li><a href="#_the_usage_file">The USAGE file</a></li>
+
+ </ul>
</li>
<li>
- <a href="#_add_an_tt_acts_as_yaffle_tt_method_to_activerecord">Add an <tt>acts_as_yaffle</tt> method to ActiveRecord</a>
+ <a href="#_add_a_custom_generator_command">Add a custom generator command</a>
</li>
<li>
- <a href="#_create_a_tt_squawk_info_for_tt_view_helper">Create a <tt>squawk_info_for</tt> view helper</a>
+ <a href="#_add_a_model">Add a model</a>
</li>
<li>
- <a href="#_create_a_migration_generator">Create a migration generator</a>
+ <a href="#_add_a_controller">Add a controller</a>
</li>
<li>
- <a href="#_add_a_custom_generator_command">Add a custom generator command</a>
+ <a href="#_add_a_helper">Add a helper</a>
</li>
<li>
<a href="#_add_a_custom_route">Add a Custom Route</a>
@@ -232,12 +267,8 @@ ul#navMain {
<a href="#_odds_and_ends">Odds and ends</a>
<ul>
- <li><a href="#_work_with_init_rb">Work with init.rb</a></li>
-
<li><a href="#_generate_rdoc_documentation">Generate RDoc Documentation</a></li>
- <li><a href="#_store_models_views_helpers_and_controllers_in_your_plugins">Store models, views, helpers, and controllers in your plugins</a></li>
-
<li><a href="#_write_custom_rake_tasks_in_your_plugin">Write custom Rake tasks in your plugin</a></li>
<li><a href="#_store_plugins_in_alternate_locations">Store plugins in alternate locations</a></li>
@@ -265,123 +296,107 @@ ul#navMain {
<h1>The Basics of Creating Rails Plugins</h1>
<div id="preamble">
<div class="sectionbody">
-<div class="para"><p>Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness.</p></div>
-<div class="para"><p>In this tutorial you will learn how to create a plugin that includes:</p></div>
+<div class="para"><p>A Rails plugin is either an extension or a modification of the core framework. Plugins provide:</p></div>
<div class="ilist"><ul>
<li>
<p>
-Core Extensions - extending String with a <tt>to_squawk</tt> method:
+a way for developers to share bleeding-edge ideas without hurting the stable code base
</p>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Anywhere</span></span>
-<span style="color: #FF0000">"hello!"</span><span style="color: #990000">.</span>to_squawk <span style="font-style: italic"><span style="color: #9A1900"># =&gt; "squawk! hello!"</span></span>
-</tt></pre></div></div>
</li>
<li>
<p>
-An <tt>acts_as_yaffle</tt> method for ActiveRecord models that adds a <tt>squawk</tt> method:
+a segmented architecture so that units of code can be fixed or updated on their own release schedule
</p>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>last_sang_at
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
-Hickwall<span style="color: #990000">.</span>new<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
-</tt></pre></div></div>
</li>
<li>
<p>
-A view helper that will print out squawking info:
+an outlet for the core developers so that they don’t have to include every cool new feature under the sun
</p>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>squawk_info_for<span style="color: #990000">(</span><span style="color: #009900">@hickwall</span><span style="color: #990000">)</span>
-</tt></pre></div></div>
</li>
+</ul></div>
+<div class="para"><p>After reading this guide you should be familiar with:</p></div>
+<div class="ilist"><ul>
<li>
<p>
-A generator that creates a migration to add squawk columns to a model:
+Creating a plugin from scratch
</p>
-<div class="listingblock">
-<div class="content">
-<pre><tt>script/generate yaffle hickwall</tt></pre>
-</div></div>
</li>
<li>
<p>
-A custom generator command:
+Writing and running tests for the plugin
</p>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000">&lt;</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
- m<span style="color: #990000">.</span>yaffle_definition
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
</li>
<li>
<p>
-A custom route method:
+Storing models, views, controllers, helpers and even other plugins in your plugins
+</p>
+</li>
+<li>
+<p>
+Writing generators
+</p>
+</li>
+<li>
+<p>
+Writing custom Rake tasks in your plugin
+</p>
+</li>
+<li>
+<p>
+Generating RDoc documentation for your plugin
+</p>
+</li>
+<li>
+<p>
+Avoiding common pitfalls with <em>init.rb</em>
</p>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
- map<span style="color: #990000">.</span>yaffles
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
</li>
</ul></div>
-<div class="para"><p>In addition you'll learn how to:</p></div>
+<div class="para"><p>This guide describes how to build a test-driven plugin that will:</p></div>
<div class="ilist"><ul>
<li>
<p>
-test your plugins.
+Extend core ruby classes like Hash and String
</p>
</li>
<li>
<p>
-work with <em>init.rb</em>, how to store model, views, controllers, helpers and even other plugins in your plugins.
+Add methods to ActiveRecord::Base in the tradition of the <em>acts_as</em> plugins
</p>
</li>
<li>
<p>
-create documentation for your plugin.
+Add a view helper that can be used in erb templates
</p>
</li>
<li>
<p>
-write custom Rake tasks in your plugin.
+Add a new generator that will generate a migration
+</p>
+</li>
+<li>
+<p>
+Add a custom generator command
+</p>
+</li>
+<li>
+<p>
+A custom route method that can be used in routes.rb
</p>
</li>
</ul></div>
+<div class="para"><p>For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.</p></div>
</div>
</div>
<h2 id="_preparation">1. Preparation</h2>
<div class="sectionbody">
<h3 id="_create_the_basic_app">1.1. Create the basic app</h3>
-<div class="para"><p>In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:</p></div>
+<div class="para"><p>The examples in this guide require that you have a working rails application. To create a simple rails app execute:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>rails plugin_demo
-cd plugin_demo
+<pre><tt>gem install rails
+rails yaffle_guide
+cd yaffle_guide
script/generate scaffold bird name:string
rake db:migrate
script/server</tt></pre>
@@ -392,22 +407,24 @@ script/server</tt></pre>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
-<td class="content">The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.</td>
+<td class="content">
+<div class="title">Editor's note:</div>The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.</td>
</tr></table>
</div>
-<h3 id="_create_the_plugin">1.2. Create the plugin</h3>
-<div class="para"><p>The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either <em>CamelCased</em> or <em>under_scored</em>, as an argument. Pass <tt>--with-generator</tt> to add an example generator also.</p></div>
+<h3 id="_generate_the_plugin_skeleton">1.2. Generate the plugin skeleton</h3>
+<div class="para"><p>Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either <em>CamelCased</em> or <em>under_scored</em>, as an argument. Pass <tt>--with-generator</tt> to add an example generator also.</p></div>
<div class="para"><p>This creates a plugin in <em>vendor/plugins</em> including an <em>init.rb</em> and <em>README</em> as well as standard <em>lib</em>, <em>task</em>, and <em>test</em> directories.</p></div>
<div class="para"><p>Examples:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>./script/generate plugin BrowserFilters
-./script/generate plugin BrowserFilters --with-generator</tt></pre>
+<pre><tt>./script/generate plugin yaffle
+./script/generate plugin yaffle --with-generator</tt></pre>
</div></div>
-<div class="para"><p>Later in the plugin we will create a generator, so go ahead and add the <tt>--with-generator</tt> option now:</p></div>
+<div class="para"><p>To get more detailed help on the plugin generator, type <tt>./script/generate plugin</tt>.</p></div>
+<div class="para"><p>Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the <tt>--with-generator</tt> option now:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>script/generate plugin yaffle --with-generator</tt></pre>
+<pre><tt>./script/generate plugin yaffle --with-generator</tt></pre>
</div></div>
<div class="para"><p>You should see the following output:</p></div>
<div class="listingblock">
@@ -430,51 +447,37 @@ create vendor/plugins/yaffle/generators/yaffle/templates
create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE</tt></pre>
</div></div>
-<div class="para"><p>For this plugin you won't need the file <em>vendor/plugins/yaffle/lib/yaffle.rb</em> so you can delete that.</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>rm vendor/plugins/yaffle/lib/yaffle.rb</tt></pre>
-</div></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/note.png" alt="Note" />
-</td>
-<td class="content">
-<div class="title">Editor's note:</div>Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be <tt>require "yaffle"</tt>. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean</td>
-</tr></table>
-</div>
+<div class="para"><p>To begin just change one thing - move <em>init.rb</em> to <em>rails/init.rb</em>.</p></div>
<h3 id="_setup_the_plugin_for_testing">1.3. Setup the plugin for testing</h3>
-<div class="para"><p>Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.</p></div>
+<div class="para"><p>If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.</p></div>
<div class="para"><p>To setup your plugin to allow for easy testing you'll need to add 3 files:</p></div>
<div class="ilist"><ul>
<li>
<p>
-A <em>database.yml</em> file with all of your connection strings.
+A <em>database.yml</em> file with all of your connection strings
</p>
</li>
<li>
<p>
-A <em>schema.rb</em> file with your table definitions.
+A <em>schema.rb</em> file with your table definitions
</p>
</li>
<li>
<p>
-A test helper that sets up the database before your tests.
+A test helper method that sets up the database
</p>
</li>
</ul></div>
-<div class="para"><p>For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/database.yml:</strong></p></div>
<div class="listingblock">
<div class="content">
<pre><tt>sqlite:
:adapter: sqlite
- :dbfile: yaffle_plugin.sqlite.db
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
- :dbfile: yaffle_plugin.sqlite3.db
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
@@ -486,11 +489,12 @@ postgresql:
mysql:
:adapter: mysql
:host: localhost
- :username: rails
- :password:
+ :username: root
+ :password: password
:database: yaffle_plugin_test</tt></pre>
</div></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/test/test_helper.rb:</strong></p></div>
+<div class="para"><p>For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/schema.rb:</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -507,203 +511,273 @@ http://www.gnu.org/software/src-highlite -->
t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>last_tweet
t<span style="color: #990000">.</span>datetime <span style="color: #990000">:</span>last_tweeted_at
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ create_table <span style="color: #990000">:</span>woodpeckers<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
-<span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/test_helper.rb</span></span>
-
-ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ENV'</span><span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">'test'</span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/test_helper.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ENV'</span><span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">'test'</span>
ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ROOT'</span><span style="color: #990000">]</span> <span style="color: #990000">||=</span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/../../../..'</span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test/unit'</span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>expand_path<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ROOT'</span><span style="color: #990000">],</span> <span style="color: #FF0000">'config/environment.rb'</span><span style="color: #990000">))</span>
-config <span style="color: #990000">=</span> YAML<span style="color: #990000">::</span><span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>IO<span style="color: #990000">.</span>read<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/database.yml'</span><span style="color: #990000">))</span>
-ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/debug.log"</span><span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> load_schema
+ config <span style="color: #990000">=</span> YAML<span style="color: #990000">::</span><span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>IO<span style="color: #990000">.</span>read<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/database.yml'</span><span style="color: #990000">))</span>
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>logger <span style="color: #990000">=</span> Logger<span style="color: #990000">.</span>new<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/debug.log"</span><span style="color: #990000">)</span>
-db_adapter <span style="color: #990000">=</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'DB'</span><span style="color: #990000">]</span>
+ db_adapter <span style="color: #990000">=</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'DB'</span><span style="color: #990000">]</span>
-<span style="font-style: italic"><span style="color: #9A1900"># no db passed, try one of these fine config-free DBs before bombing.</span></span>
-db_adapter <span style="color: #990000">||=</span>
- <span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rubygems'</span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite'</span>
- <span style="color: #FF0000">'sqlite'</span>
- <span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-style: italic"><span style="color: #9A1900"># no db passed, try one of these fine config-free DBs before bombing.</span></span>
+ db_adapter <span style="color: #990000">||=</span>
<span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
- <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite3'</span>
- <span style="color: #FF0000">'sqlite3'</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rubygems'</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite'</span>
+ <span style="color: #FF0000">'sqlite'</span>
<span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-weight: bold"><span style="color: #0000FF">begin</span></span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'sqlite3'</span>
+ <span style="color: #FF0000">'sqlite3'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> MissingSourceFile
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> db_adapter<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> <span style="color: #FF0000">"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> db_adapter<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
- <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> <span style="color: #FF0000">"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."</span>
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>establish_connection<span style="color: #990000">(</span>config<span style="color: #990000">[</span>db_adapter<span style="color: #990000">])</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/schema.rb"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/../rails/init.rb'</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Now whenever you write a test that requires the database, you can call <em>load_schema</em>.</p></div>
+<h3 id="_run_the_plugin_tests">1.4. Run the plugin tests</h3>
+<div class="para"><p>Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in <em>vendor/plugins/yaffle/test/yaffle_test.rb</em> with a sample test. Replace the contents of that file with:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_test.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
-ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>establish_connection<span style="color: #990000">(</span>config<span style="color: #990000">[</span>db_adapter<span style="color: #990000">])</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
-<span style="font-weight: bold"><span style="color: #0000FF">load</span></span><span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">"/schema.rb"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/../init.rb'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_schema_has_loaded_correctly
+ assert_equal <span style="color: #990000">[],</span> Hickwall<span style="color: #990000">.</span>all
+ assert_equal <span style="color: #990000">[],</span> Wickwall<span style="color: #990000">.</span>all
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>last_tweet<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>last_tweeted_at
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>To run this, go to the plugin directory and run <tt>rake</tt>:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>cd vendor/plugins/yaffle
+rake</tt></pre>
+</div></div>
+<div class="para"><p>You should see output like:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
+-- create_table(:hickwalls, {:force=&gt;true})
+ -&gt; 0.0220s
+-- create_table(:wickwalls, {:force=&gt;true})
+ -&gt; 0.0077s
+-- initialize_schema_migrations_table()
+ -&gt; 0.0007s
+-- assume_migrated_upto_version(0)
+ -&gt; 0.0007s
+Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
+Started
+.
+Finished in 0.002236 seconds.
+
+1 test, 1 assertion, 0 failures, 0 errors</tt></pre>
+</div></div>
+<div class="para"><p>By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>rake DB=sqlite
+rake DB=sqlite3
+rake DB=mysql
+rake DB=postgresql</tt></pre>
+</div></div>
+<div class="para"><p>Now you are ready to test-drive your plugin!</p></div>
</div>
-<h2 id="_add_a_tt_to_squawk_tt_method_to_string">2. Add a <tt>to_squawk</tt> method to String</h2>
+<h2 id="_extending_core_classes">2. Extending core classes</h2>
<div class="sectionbody">
-<div class="para"><p>To update a core class you will have to:</p></div>
+<div class="para"><p>This section will explain how to add a method to String that will be available anywhere in your rails app by:</p></div>
<div class="ilist"><ul>
<li>
<p>
-Write tests for the desired functionality.
-</p>
-</li>
-<li>
-<p>
-Create a file for the code you wish to use.
+Writing tests for the desired behavior
</p>
</li>
<li>
<p>
-Require that file from your <em>init.rb</em>.
+Creating and requiring the correct files
</p>
</li>
</ul></div>
-<div class="para"><p>Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from <em>init.rb</em>. The file you are going to add for this tutorial is <em>lib/core_ext.rb</em>.</p></div>
-<div class="para"><p>First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:</p></div>
+<h3 id="_creating_the_test">2.1. Creating the test</h3>
+<div class="para"><p>In this example you will add a method to String named <tt>to_squawk</tt>. To begin, create a new test file with a few assertions:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/core_ext_test.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/core_ext_test.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test/unit'</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CoreExtTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
- <span style="font-style: italic"><span style="color: #9A1900"># Replace this with your real tests.</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_this_plugin
- flunk
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_to_squawk_prepends_the_word_squawk
+ assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"Hello World"</span><span style="color: #990000">.</span>to_squawk
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Start off by removing the default test, and adding a require statement for your test helper.</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/core_ext_test.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test/unit'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CoreExtTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
<div class="para"><p>Navigate to your plugin directory and run <tt>rake test</tt>:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>cd vendor/plugins/yaffle
rake test</tt></pre>
</div></div>
-<div class="para"><p>Your test should fail with <tt>no such file to load &#8212; ./test/../lib/core_ext.rb (LoadError)</tt> because we haven't created any file yet. Create the file <em>lib/core_ext.rb</em> and re-run the tests. You should see a different error message:</p></div>
+<div class="para"><p>The test above should fail with the message:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt> 1) Error:
+test_to_squawk_prepends_the_word_squawk(CoreExtTest):
+NoMethodError: undefined method `to_squawk' for "Hello World":String
+ ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'</tt></pre>
+</div></div>
+<div class="para"><p>Great - now you are ready to start development.</p></div>
+<h3 id="_organize_your_files">2.2. Organize your files</h3>
+<div class="para"><p>A common pattern in rails plugins is to set up the file structure like this:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>1.) Failure ...
-No tests were specified</tt></pre>
+<pre><tt>|-- lib
+| |-- yaffle
+| | `-- core_ext.rb
+| `-- yaffle.rb</tt></pre>
</div></div>
-<div class="para"><p>Great - now you are ready to start development. The first thing we'll do is to add a method to String called <tt>to_squawk</tt> which will prefix the string with the word &#8220;squawk!&#8221;. The test will look something like this:</p></div>
+<div class="para"><p>The first thing we need to to is to require our <em>lib/yaffle.rb</em> file from <em>rails/init.rb</em>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/rails/init.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CoreExtTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_string_should_respond_to_squawk
- assert_equal <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">,</span> <span style="color: #FF0000">""</span><span style="color: #990000">.</span>respond_to?<span style="color: #990000">(:</span>to_squawk<span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_string_prepend_empty_strings_with_the_word_squawk
- assert_equal <span style="color: #FF0000">"squawk!"</span><span style="color: #990000">,</span> <span style="color: #FF0000">""</span><span style="color: #990000">.</span>to_squawk
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_string_prepend_non_empty_strings_with_the_word_squawk
- assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"Hello World"</span><span style="color: #990000">.</span>to_squawk
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'yaffle'</span>
</tt></pre></div></div>
+<div class="para"><p>Then in <em>lib/yaffle.rb</em> require <em>lib/core_ext.rb</em>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"core_ext"</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/core_ext"</span>
</tt></pre></div></div>
+<div class="para"><p>Finally, create the <em>core_ext.rb</em> file and add the <em>to_squawk</em> method:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/core_ext.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/lib/core_ext.rb</span></span>
-
-String<span style="color: #990000">.</span>class_eval <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+<pre><tt>String<span style="color: #990000">.</span>class_eval <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> to_squawk
<span style="color: #FF0000">"squawk! #{self}"</span><span style="color: #990000">.</span>strip
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>When monkey-patching existing classes it's often better to use <tt>class_eval</tt> instead of opening the class directly.</p></div>
-<div class="para"><p>To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:</p></div>
+<div class="para"><p>To test that your method does what it says it does, run the unit tests with <tt>rake</tt> from your plugin directory. To see this in action, fire up a console and start squawking:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>$ ./script/console
&gt;&gt; "Hello World".to_squawk
=&gt; "squawk! Hello World"</tt></pre>
</div></div>
-<div class="para"><p>If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.</p></div>
+<h3 id="_working_with_init_rb">2.3. Working with init.rb</h3>
+<div class="para"><p>When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, <em>init.rb</em> is invoked via <tt>eval</tt> (not <tt>require</tt>) so it has slightly different behavior.</p></div>
+<div class="para"><p>Under certain circumstances if you reopen classes or modules in <em>init.rb</em> you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from <tt>init.rb</tt>, as shown above.</p></div>
+<div class="para"><p>If you must reopen a class in <tt>init.rb</tt> you can use <tt>module_eval</tt> or <tt>class_eval</tt> to avoid any issues:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>Hash<span style="color: #990000">.</span>class_eval <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> is_a_special_hash?
+ <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Another way is to explicitly define the top-level module space for all modules and classes, like <tt>::Hash</tt>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> <span style="color: #990000">::</span>Hash
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> is_a_special_hash?
+ <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
</div>
-<h2 id="_add_an_tt_acts_as_yaffle_tt_method_to_activerecord">3. Add an <tt>acts_as_yaffle</tt> method to ActiveRecord</h2>
+<h2 id="_add_an_tt_acts_as_yaffle_tt_method_to_active_record">3. Add an <tt>acts_as_yaffle</tt> method to Active Record</h2>
<div class="sectionbody">
-<div class="para"><p>A common pattern in plugins is to add a method called <tt>acts_as_something</tt> to models. In this case, you want to write a method called <tt>acts_as_yaffle</tt> that adds a <tt>squawk</tt> method to your models.</p></div>
-<div class="para"><p>To keep things clean, create a new test file called <em>acts_as_yaffle_test.rb</em> in your plugin's test directory and require your test helper.</p></div>
+<div class="para"><p>A common pattern in plugins is to add a method called <em>acts_as_something</em> to models. In this case, you want to write a method called <em>acts_as_yaffle</em> that adds a <em>squawk</em> method to your models.</p></div>
+<div class="para"><p>To begin, set up your files so that you have:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
- acts_as_yaffle
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/lib/acts_as_yaffle.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'yaffle/acts_as_yaffle'</span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+ <span style="font-style: italic"><span style="color: #9A1900"># your code will go here</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>One of the most common plugin patterns for <tt>acts_as_yaffle</tt> plugins is to structure your file like so:</p></div>
+<div class="para"><p>Note that after requiring <em>acts_as_yaffle</em> you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.</p></div>
+<div class="para"><p>One of the most common plugin patterns for <em>acts_as_yaffle</em> plugins is to structure your file like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -727,139 +801,118 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With structure you can easily separate the methods that will be used for the class (like <tt>Hickwall.some_method</tt>) and the instance (like <tt>@hickwell.some_method</tt>).</p></div>
-<div class="para"><p>Let's add class method named <tt>acts_as_yaffle</tt> - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.</p></div>
-<div class="para"><p>Back in your <tt>acts_as_yaffle</tt> file, update ClassMethods like so:</p></div>
+<h3 id="_add_a_class_method">3.1. Add a class method</h3>
+<div class="para"><p>This plugin will expect that you've added a method to your model named <em>last_squawk</em>. However, the plugin users might have already defined a method on their model named <em>last_squawk</em> that they use for something else. This plugin will allow the name to be changed by adding a class method called <em>yaffle_text_field</em>.</p></div>
+<div class="para"><p>To start out, write a failing test that shows the behavior you'd like:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> ClassMethods
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> acts_as_yaffle<span style="color: #990000">(</span>options <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
- send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> InstanceMethods
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>last_tweet
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
+
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal <span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal <span style="color: #FF0000">"last_squawked_at"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_date_field
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal <span style="color: #FF0000">"last_tweet"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
- assert_equal <span style="color: #FF0000">"last_tweeted_at"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_date_field
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>To make these tests pass, you could modify your <tt>acts_as_yaffle</tt> file like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>included<span style="color: #990000">(</span>base<span style="color: #990000">)</span>
base<span style="color: #990000">.</span>send <span style="color: #990000">:</span>extend<span style="color: #990000">,</span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> acts_as_yaffle<span style="color: #990000">(</span>options <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
- cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
+ cattr_accessor <span style="color: #990000">:</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_text_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_text_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">).</span>to_s
- <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_date_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_date_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawked_at<span style="color: #990000">).</span>to_s
- send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> InstanceMethods
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> InstanceMethods
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle
</tt></pre></div></div>
-<div class="para"><p>Now you can add tests for the instance methods, and the instance method itself:</p></div>
+<h3 id="_add_an_instance_method">3.2. Add an instance method</h3>
+<div class="para"><p>This plugin will add a method named <em>squawk</em> to any Active Record objects that call <em>acts_as_yaffle</em>. The <em>squawk</em> method will simply set the value of one of the fields in the database.</p></div>
+<div class="para"><p>To start out, write a failing test that shows the behavior you'd like:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Hickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Wickwall <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ acts_as_yaffle <span style="color: #990000">:</span>yaffle_text_field <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>last_tweet
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ActsAsYaffleTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal <span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal <span style="color: #FF0000">"last_squawked_at"</span><span style="color: #990000">,</span> Hickwall<span style="color: #990000">.</span>yaffle_date_field
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_text_field_should_be_last_squawk
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal <span style="color: #FF0000">"last_tweet"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal <span style="color: #FF0000">"last_tweeted_at"</span><span style="color: #990000">,</span> Wickwall<span style="color: #990000">.</span>yaffle_date_field
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_hickwalls_squawk_should_populate_last_squawk
hickwall <span style="color: #990000">=</span> Hickwall<span style="color: #990000">.</span>new
hickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> hickwall<span style="color: #990000">.</span>last_squawk
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_hickwalls_squawk_should_populate_last_squawked_at
- hickwall <span style="color: #990000">=</span> Hickwall<span style="color: #990000">.</span>new
- hickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
- assert_equal Date<span style="color: #990000">.</span>today<span style="color: #990000">,</span> hickwall<span style="color: #990000">.</span>last_squawked_at
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_wickwalls_squawk_should_populate_last_tweet
- wickwall <span style="color: #990000">=</span> Wickwall<span style="color: #990000">.</span>new
- wickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
- assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> wickwall<span style="color: #990000">.</span>last_tweet
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall <span style="color: #990000">=</span> Wickwall<span style="color: #990000">.</span>new
wickwall<span style="color: #990000">.</span>squawk<span style="color: #990000">(</span><span style="color: #FF0000">"Hello World"</span><span style="color: #990000">)</span>
- assert_equal Date<span style="color: #990000">.</span>today<span style="color: #990000">,</span> wickwall<span style="color: #990000">.</span>last_tweeted_at
+ assert_equal <span style="color: #FF0000">"squawk! Hello World"</span><span style="color: #990000">,</span> wickwall<span style="color: #990000">.</span>last_tweet
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>Run this test to make sure the last two tests fail, then update <em>acts_as_yaffle.rb</em> to look like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>included<span style="color: #990000">(</span>base<span style="color: #990000">)</span>
base<span style="color: #990000">.</span>send <span style="color: #990000">:</span>extend<span style="color: #990000">,</span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> ClassMethods
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> acts_as_yaffle<span style="color: #990000">(</span>options <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
- cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
+ cattr_accessor <span style="color: #990000">:</span>yaffle_text_field
<span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_text_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_text_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">).</span>to_s
- <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>yaffle_date_field <span style="color: #990000">=</span> <span style="color: #990000">(</span>options<span style="color: #990000">[:</span>yaffle_date_field<span style="color: #990000">]</span> <span style="color: #990000">||</span> <span style="color: #990000">:</span>last_squawked_at<span style="color: #990000">).</span>to_s
send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> InstanceMethods
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -867,130 +920,122 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> InstanceMethods
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> squawk<span style="color: #990000">(</span>string<span style="color: #990000">)</span>
write_attribute<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_text_field<span style="color: #990000">,</span> string<span style="color: #990000">.</span>to_squawk<span style="color: #990000">)</span>
- write_attribute<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_date_field<span style="color: #990000">,</span> Date<span style="color: #990000">.</span>today<span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle
</tt></pre></div></div>
-<div class="para"><p>Note the use of <tt>write_attribute</tt> to write to the field in model.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">
+<div class="title">Editor's note:</div>The use of <tt>write_attribute</tt> to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use <tt>send("#{self.class.yaffle_text_field}=", string.to_squawk)</tt>.</td>
+</tr></table>
</div>
-<h2 id="_create_a_tt_squawk_info_for_tt_view_helper">4. Create a <tt>squawk_info_for</tt> view helper</h2>
+</div>
+<h2 id="_create_a_generator">4. Create a generator</h2>
<div class="sectionbody">
-<div class="para"><p>Creating a view helper is a 3-step process:</p></div>
+<div class="para"><p>Many plugins ship with generators. When you created the plugin above, you specified the &#8212;with-generator option, so you already have the generator stubs in <em>vendor/plugins/yaffle/generators/yaffle</em>.</p></div>
+<div class="para"><p>Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.</p></div>
+<div class="para"><p>To create a generator you must:</p></div>
<div class="ilist"><ul>
<li>
<p>
-Add an appropriately named file to the <em>lib</em> directory.
+Add your instructions to the <em>manifest</em> method of the generator
+</p>
+</li>
+<li>
+<p>
+Add any necessary template files to the templates directory
</p>
</li>
<li>
<p>
-Require the file and hooks in <em>init.rb</em>.
+Test the generator manually by running various combinations of <tt>script/generate</tt> and <tt>script/destroy</tt>
</p>
</li>
<li>
<p>
-Write the tests.
+Update the USAGE file to add helpful documentation for your generator
</p>
</li>
</ul></div>
-<div class="para"><p>First, create the test to define the functionality you want:</p></div>
+<h3 id="_testing_generators">4.1. Testing generators</h3>
+<div class="para"><p>Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Creates a new fake rails root directory that will serve as destination
+</p>
+</li>
+<li>
+<p>
+Runs the generator forward and backward, making whatever assertions are necessary
+</p>
+</li>
+<li>
+<p>
+Removes the fake rails root
+</p>
+</li>
+</ul></div>
+<div class="para"><p>For the generator in this section, the test could look something like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_generator_test.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/view_helpers_test.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/generate'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/destroy'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">include</span></span> YaffleViewHelper
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> GeneratorTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ViewHelpersTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_squawk_info_for_should_return_the_text_and_date
- time <span style="color: #990000">=</span> Time<span style="color: #990000">.</span>now
- hickwall <span style="color: #990000">=</span> Hickwall<span style="color: #990000">.</span>new
- hickwall<span style="color: #990000">.</span>last_squawk <span style="color: #990000">=</span> <span style="color: #FF0000">"Hello World"</span>
- hickwall<span style="color: #990000">.</span>last_squawked_at <span style="color: #990000">=</span> time
- assert_equal <span style="color: #FF0000">"Hello World, #{time.to_s}"</span><span style="color: #990000">,</span> squawk_info_for<span style="color: #990000">(</span>hickwall<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> fake_rails_root
+ File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'rails_root'</span><span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Then add the following statements to init.rb:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/init.rb</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"view_helpers"</span>
-ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> YaffleViewHelper
-</tt></pre></div></div>
-<div class="para"><p>Then add the view helpers file and</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/lib/view_helpers.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> YaffleViewHelper
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> squawk_info_for<span style="color: #990000">(</span>yaffle<span style="color: #990000">)</span>
- returning <span style="color: #FF0000">""</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>result<span style="color: #990000">|</span>
- result <span style="color: #990000">&lt;&lt;</span> yaffle<span style="color: #990000">.</span>read_attribute<span style="color: #990000">(</span>yaffle<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_text_field<span style="color: #990000">)</span>
- result <span style="color: #990000">&lt;&lt;</span> <span style="color: #FF0000">", "</span>
- result <span style="color: #990000">&lt;&lt;</span> yaffle<span style="color: #990000">.</span>read_attribute<span style="color: #990000">(</span>yaffle<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">class</span></span><span style="color: #990000">.</span>yaffle_date_field<span style="color: #990000">).</span>to_s
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> file_list
+ Dir<span style="color: #990000">.</span>glob<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"db"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"*"</span><span style="color: #990000">))</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>You can also test this in script/console by using the <tt>helper</tt> method:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>$ ./script/console
-&gt;&gt; helper.squawk_info_for(@some_yaffle_instance)</tt></pre>
-</div></div>
-</div>
-<h2 id="_create_a_migration_generator">5. Create a migration generator</h2>
-<div class="sectionbody">
-<div class="para"><p>When you created the plugin above, you specified the &#8212;with-generator option, so you already have the generator stubs in your plugin.</p></div>
-<div class="para"><p>We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.</p></div>
-<div class="para"><p>Type:</p></div>
-<div class="literalblock">
-<div class="content">
-<pre><tt>script/generate</tt></pre>
-</div></div>
-<div class="para"><p>You should see the line:</p></div>
-<div class="literalblock">
-<div class="content">
-<pre><tt>Plugins (vendor/plugins): yaffle</tt></pre>
-</div></div>
-<div class="para"><p>When you run <tt>script/generate yaffle</tt> you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>Description:
- Creates a migration that adds yaffle squawk fields to the given model
-Example:
- ./script/generate yaffle hickwall
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ FileUtils<span style="color: #990000">.</span>mkdir_p<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="color: #009900">@original_files</span> <span style="color: #990000">=</span> file_list
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- This will create:
- db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall</tt></pre>
-</div></div>
-<div class="para"><p>Now you can add code to your generator:</p></div>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ FileUtils<span style="color: #990000">.</span>rm_r<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_correct_file_name
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"bird"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=&gt;</span> fake_rails_root<span style="color: #990000">)</span>
+ new_file <span style="color: #990000">=</span> <span style="color: #990000">(</span>file_list <span style="color: #990000">-</span> <span style="color: #009900">@original_files</span><span style="color: #990000">).</span>first
+ assert_match <span style="color: #FF6600">/add_yaffle_fields_to_bird/</span><span style="color: #990000">,</span> new_file
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>You can run <em>rake</em> from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.</p></div>
+<h3 id="_adding_to_the_manifest">4.2. Adding to the manifest</h3>
+<div class="para"><p>This example will demonstrate how to use one of the built-in generator methods named <em>migration_template</em> to create a migration file. To start, update your generator file to look like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000">&lt;</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000">&lt;</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
record <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>m<span style="color: #990000">|</span>
m<span style="color: #990000">.</span>migration_template <span style="color: #FF0000">'migration:migration.rb'</span><span style="color: #990000">,</span> <span style="color: #FF0000">"db/migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>assigns <span style="color: #990000">=&gt;</span> yaffle_local_assigns<span style="color: #990000">,</span>
<span style="color: #990000">:</span>migration_file_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
- <span style="color: #FF0000">}</span>
+ <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -1006,91 +1051,100 @@ http://www.gnu.org/software/src-highlite -->
assigns<span style="color: #990000">[:</span>class_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
assigns<span style="color: #990000">[:</span>table_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> custom_file_name
assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #990000">[</span>Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"string"</span><span style="color: #990000">)]</span>
- assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000">&lt;&lt;</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawked_at"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"datetime"</span><span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Note that you need to be aware of whether or not table names are pluralized.</p></div>
-<div class="para"><p>This does a few things:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Reuses the built in rails <tt>migration_template</tt> method.
-</p>
-</li>
-<li>
-<p>
-Reuses the built-in rails migration template.
-</p>
-</li>
-</ul></div>
-<div class="para"><p>When you run the generator like</p></div>
-<div class="literalblock">
+<div class="para"><p>The generator creates a new file in <em>db/migrate</em> with a timestamp and an <em>add_column</em> statement. It reuses the built in rails <tt>migration_template</tt> method, and reuses the built-in rails migration template.</p></div>
+<div class="para"><p>It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.</p></div>
+<h3 id="_manually_test_the_generator">4.3. Manually test the generator</h3>
+<div class="para"><p>To run the generator, type the following at the command line:</p></div>
+<div class="listingblock">
<div class="content">
-<pre><tt>script/generate yaffle bird</tt></pre>
+<pre><tt>./script/generate yaffle bird</tt></pre>
</div></div>
-<div class="para"><p>You will see a new file:</p></div>
+<div class="para"><p>and you will see a new file:</p></div>
+<div class="para"><p><strong>db/migrate/20080529225649_add_yaffle_fields_to_birds.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddYaffleFieldsToBirds <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AddYaffleFieldsToBirds <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
- add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawked_at<span style="color: #990000">,</span> <span style="color: #990000">:</span>datetime
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
- remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawked_at
remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<h3 id="_the_usage_file">4.4. The USAGE file</h3>
+<div class="para"><p>Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>script/generate</tt></pre>
+</div></div>
+<div class="para"><p>You should see something like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Installed Generators
+ Plugins (vendor/plugins): yaffle
+ Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration</tt></pre>
+</div></div>
+<div class="para"><p>When you run <tt>script/generate yaffle</tt> you should see the contents of your <em>vendor/plugins/yaffle/generators/yaffle/USAGE</em> file.</p></div>
+<div class="para"><p>For this plugin, update the USAGE file looks like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Description:
+ Creates a migration that adds yaffle squawk fields to the given model
+
+Example:
+ ./script/generate yaffle hickwall
+
+ This will create:
+ db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall</tt></pre>
+</div></div>
</div>
-<h2 id="_add_a_custom_generator_command">6. Add a custom generator command</h2>
+<h2 id="_add_a_custom_generator_command">5. Add a custom generator command</h2>
<div class="sectionbody">
-<div class="para"><p>You may have noticed above that you can used one of the built-in rails migration commands <tt>m.migration_template</tt>. You can create your own commands for these, using the following steps:</p></div>
-<div class="olist"><ol>
-<li>
-<p>
-Add the require and hook statements to init.rb.
-</p>
-</li>
-<li>
-<p>
-Create the commands - creating 3 sets, Create, Destroy, List.
-</p>
-</li>
-<li>
-<p>
-Add the method to your generator.
-</p>
-</li>
-</ol></div>
-<div class="para"><p>Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:</p></div>
+<div class="para"><p>You may have noticed above that you can used one of the built-in rails migration commands <tt>migration_template</tt>. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.</p></div>
+<div class="para"><p>This section describes how you you can create your own commands to add and remove a line of text from <em>routes.rb</em>. This example creates a very simple method that adds or removes a text file.</p></div>
+<div class="para"><p>To start, add the following test method:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/generator_test.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/init.rb</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"commands"</span>
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_definition
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"bird"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=&gt;</span> fake_rails_root<span style="color: #990000">)</span>
+ definition <span style="color: #990000">=</span> File<span style="color: #990000">.</span>read<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">))</span>
+ assert_match <span style="color: #FF6600">/Yaffle\:/</span><span style="color: #990000">,</span> definition
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>Run <tt>rake</tt> to watch the test fail, then make the test pass add the following:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/templates/definition.txt</strong></p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Yaffle: A bird</tt></pre>
+</div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/lib/commands.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/commands"</span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/commands.rb</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/commands'</span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
@@ -1113,42 +1167,230 @@ http://www.gnu.org/software/src-highlite -->
file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Update
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_definition
+ file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update
+</tt></pre></div></div>
+<div class="para"><p>Finally, call your new method in the manifest:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000">&lt;</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
+ m<span style="color: #990000">.</span>yaffle_definition
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+</div>
+<h2 id="_add_a_model">6. Add a model</h2>
+<div class="sectionbody">
+<div class="para"><p>This section describes how to add a model named <em>Woodpecker</em> to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt># File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
-
-Yaffle is a bird</tt></pre>
+<pre><tt>vendor/plugins/yaffle/
+|-- lib
+| |-- app
+| | |-- controllers
+| | |-- helpers
+| | |-- models
+| | | `-- woodpecker.rb
+| | `-- views
+| |-- yaffle
+| | |-- acts_as_yaffle.rb
+| | |-- commands.rb
+| | `-- core_ext.rb
+| `-- yaffle.rb</tt></pre>
</div></div>
+<div class="para"><p>As always, start with a test:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/yaffle/woodpecker_test.rb:</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> YaffleGenerator <span style="color: #990000">&lt;</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
- m<span style="color: #990000">.</span>yaffle_definition
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckerTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ load_schema
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_woodpecker
+ assert_kind_of Woodpecker<span style="color: #990000">,</span> Woodpecker<span style="color: #990000">.</span>new
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>This example just uses the built-in "file" method, but you could do anything that Ruby allows.</p></div>
+<div class="para"><p>This is just a simple test to make sure the class is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="color: #990000">%</span>w<span style="color: #FF0000">{</span> models <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
+ path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'app'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
+ <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000">&lt;&lt;</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000">&lt;&lt;</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the <em>load_once_paths</em> allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/app/models/woodpecker.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Woodpecker <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Finally, add the following to your plugin's <em>schema.rb</em>:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/schema.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>ActiveRecord<span style="color: #990000">::</span>Schema<span style="color: #990000">.</span>define<span style="color: #990000">(:</span>version <span style="color: #990000">=&gt;</span> <span style="color: #993399">0</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ create_table <span style="color: #990000">:</span>woodpeckers<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.</p></div>
</div>
-<h2 id="_add_a_custom_route">7. Add a Custom Route</h2>
+<h2 id="_add_a_controller">7. Add a controller</h2>
<div class="sectionbody">
-<div class="para"><p>Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in <a href="http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2">http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2</a>.</p></div>
+<div class="para"><p>This section describes how to add a controller named <em>woodpeckers</em> to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.</p></div>
+<div class="para"><p>You can test your plugin's controller as you would test any other controller:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/test/routing_test.rb</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'woodpeckers_controller'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'action_controller/test_process'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersController<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> rescue_action<span style="color: #990000">(</span>e<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> e <span style="font-weight: bold"><span style="color: #0000FF">end</span></span><span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"#{File.dirname(__FILE__)}/test_helper"</span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersControllerTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ <span style="color: #009900">@controller</span> <span style="color: #990000">=</span> WoodpeckersController<span style="color: #990000">.</span>new
+ <span style="color: #009900">@request</span> <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>TestRequest<span style="color: #990000">.</span>new
+ <span style="color: #009900">@response</span> <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>TestResponse<span style="color: #990000">.</span>new
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_index
+ get <span style="color: #990000">:</span>index
+ assert_response <span style="color: #990000">:</span>success
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="color: #990000">%</span>w<span style="color: #FF0000">{</span> models controllers <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
+ path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'app'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
+ <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000">&lt;&lt;</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000">&lt;&lt;</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
+ render <span style="color: #990000">:</span>text <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Squawk!"</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to <a href="http://localhost:3000/woodpeckers">http://localhost:3000/woodpeckers</a> to see your controller in action.</p></div>
+</div>
+<h2 id="_add_a_helper">8. Add a helper</h2>
+<div class="sectionbody">
+<div class="para"><p>This section describes how to add a helper named <em>WoodpeckersHelper</em> to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.</p></div>
+<div class="para"><p>You can test your plugin's helper as you would test any other helper:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/woodpeckers_helper_test.rb</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">include</span></span> WoodpeckersHelper
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> WoodpeckersHelperTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_tweet
+ assert_equal <span style="color: #FF0000">"Tweet! Hello"</span><span style="color: #990000">,</span> tweet<span style="color: #990000">(</span><span style="color: #FF0000">"Hello"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="color: #990000">%</span>w<span style="color: #FF0000">{</span> models controllers helpers <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
+ path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'app'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
+ <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000">&lt;&lt;</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000">&lt;&lt;</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> WoodpeckersHelper
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> WoodpeckersHelper
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> tweet<span style="color: #990000">(</span>text<span style="color: #990000">)</span>
+ <span style="color: #FF0000">"Tweet! #{text}"</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.</p></div>
+</div>
+<h2 id="_add_a_custom_route">9. Add a Custom Route</h2>
+<div class="sectionbody">
+<div class="para"><p>Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in <a href="http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2">http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2</a>.</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/routing_test.rb</strong></p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"#{File.dirname(__FILE__)}/test_helper"</span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> RoutingTest <span style="color: #990000">&lt;</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
@@ -1174,24 +1416,22 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"routing"</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"routing"</span>
ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>RouteSet<span style="color: #990000">::</span>Mapper<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>MapperExtensions
</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/routing.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/lib/routing.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Routing <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MapperExtensions
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffles
@@ -1201,51 +1441,22 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p><strong>config/routes.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: config/routes.rb</span></span>
-
-ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
+<pre><tt>ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
<span style="color: #990000">...</span>
map<span style="color: #990000">.</span>yaffles
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>You can also see if your routes work by running <tt>rake routes</tt> from your app directory.</p></div>
</div>
-<h2 id="_odds_and_ends">8. Odds and ends</h2>
+<h2 id="_odds_and_ends">10. Odds and ends</h2>
<div class="sectionbody">
-<h3 id="_work_with_init_rb">8.1. Work with init.rb</h3>
-<div class="para"><p>The plugin initializer script <em>init.rb</em> is invoked via <tt>eval</tt> (not <tt>require</tt>) so it has slightly different behavior.</p></div>
-<div class="para"><p>If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:</p></div>
-<div class="para"><p>The first way is to explicitly define the top-level module space for all modules and classes, like <tt>::Hash</tt>:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> <span style="color: #990000">::</span>Hash
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> is_a_special_hash?
- <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>OR you can use <tt>module_eval</tt> or <tt>class_eval</tt>:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt># File: vendor/plugins/yaffle/init.rb
-
-Hash.class_eval do
- def is_a_special_hash?
- true
- end
-end</tt></pre>
-</div></div>
-<h3 id="_generate_rdoc_documentation">8.2. Generate RDoc Documentation</h3>
+<h3 id="_generate_rdoc_documentation">10.1. Generate RDoc Documentation</h3>
<div class="para"><p>Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.</p></div>
<div class="para"><p>The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:</p></div>
<div class="ilist"><ul>
@@ -1277,35 +1488,16 @@ Warning, gotchas or tips that might help save users time.
<div class="content">
<pre><tt>rake rdoc</tt></pre>
</div></div>
-<h3 id="_store_models_views_helpers_and_controllers_in_your_plugins">8.3. Store models, views, helpers, and controllers in your plugins</h3>
-<div class="para"><p>You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/init.rb</span></span>
-
-<span style="color: #990000">%</span>w<span style="color: #FF0000">{</span> models controllers helpers <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
- path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>directory<span style="color: #990000">,</span> <span style="color: #FF0000">'lib'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
- <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000">&lt;&lt;</span> path
- Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000">&lt;&lt;</span> path
- Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser.</p></div>
-<div class="para"><p>Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.</p></div>
-<h3 id="_write_custom_rake_tasks_in_your_plugin">8.4. Write custom Rake tasks in your plugin</h3>
+<h3 id="_write_custom_rake_tasks_in_your_plugin">10.2. Write custom Rake tasks in your plugin</h3>
<div class="para"><p>When you created the plugin with the built-in rails generator, it generated a rake file for you in <em>vendor/plugins/yaffle/tasks/yaffle.rake</em>. Any rake task you add here will be available to the app.</p></div>
<div class="para"><p>Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/tasks/yaffle.rake</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># File: vendor/plugins/yaffle/tasks/yaffle.rake</span></span>
-
-namespace <span style="color: #990000">:</span>yaffle <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+<pre><tt>namespace <span style="color: #990000">:</span>yaffle <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
desc <span style="color: #FF0000">"Prints out the word 'Yaffle'"</span>
task <span style="color: #990000">:</span>squawk <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>environment <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
puts <span style="color: #FF0000">"squawk!"</span>
@@ -1318,7 +1510,7 @@ namespace <span style="color: #990000">:</span>yaffle <span style="font-weight:
<pre><tt>yaffle:squawk # Prints out the word 'Yaffle'</tt></pre>
</div></div>
<div class="para"><p>You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.</p></div>
-<h3 id="_store_plugins_in_alternate_locations">8.5. Store plugins in alternate locations</h3>
+<h3 id="_store_plugins_in_alternate_locations">10.3. Store plugins in alternate locations</h3>
<div class="para"><p>You can store plugins wherever you want - you just have to add those plugins to the plugins path in <em>environment.rb</em>.</p></div>
<div class="para"><p>Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.</p></div>
<div class="para"><p>You can even store plugins inside of other plugins for complete plugin madness!</p></div>
@@ -1329,14 +1521,14 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>config<span style="color: #990000">.</span>plugin_paths <span style="color: #990000">&lt;&lt;</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>RAILS_ROOT<span style="color: #990000">,</span><span style="color: #FF0000">"vendor"</span><span style="color: #990000">,</span><span style="color: #FF0000">"plugins"</span><span style="color: #990000">,</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span><span style="color: #FF0000">"lib"</span><span style="color: #990000">,</span><span style="color: #FF0000">"plugins"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<h3 id="_create_your_own_plugin_loaders_and_plugin_locators">8.6. Create your own Plugin Loaders and Plugin Locators</h3>
+<h3 id="_create_your_own_plugin_loaders_and_plugin_locators">10.4. Create your own Plugin Loaders and Plugin Locators</h3>
<div class="para"><p>If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.</p></div>
-<h3 id="_use_custom_plugin_generators">8.7. Use Custom Plugin Generators</h3>
+<h3 id="_use_custom_plugin_generators">10.5. Use Custom Plugin Generators</h3>
<div class="para"><p>If you are an RSpec fan, you can install the <tt>rspec_plugin_generator</tt> gem, which will generate the spec folder and database for you. See <a href="http://github.com/pat-maddox/rspec-plugin-generator/tree/master">http://github.com/pat-maddox/rspec-plugin-generator/tree/master</a>.</p></div>
</div>
-<h2 id="_appendix">9. Appendix</h2>
+<h2 id="_appendix">11. Appendix</h2>
<div class="sectionbody">
-<h3 id="_references">9.1. References</h3>
+<h3 id="_references">11.1. References</h3>
<div class="ilist"><ul>
<li>
<p>
@@ -1359,7 +1551,7 @@ http://www.gnu.org/software/src-highlite -->
</p>
</li>
</ul></div>
-<h3 id="_final_plugin_directory_structure">9.2. Final plugin directory structure</h3>
+<h3 id="_final_plugin_directory_structure">11.2. Final plugin directory structure</h3>
<div class="para"><p>The final plugin should have a directory structure that looks something like this:</p></div>
<div class="listingblock">
<div class="content">
diff --git a/railties/doc/guides/html/debugging_rails_applications.html b/railties/doc/guides/html/debugging_rails_applications.html
index bf1e442d59..0653caaf7a 100644
--- a/railties/doc/guides/html/debugging_rails_applications.html
+++ b/railties/doc/guides/html/debugging_rails_applications.html
@@ -208,6 +208,8 @@ ul#navMain {
<li><a href="#_inspect">inspect</a></li>
+ <li><a href="#_debugging_javascript">Debugging Javascript</a></li>
+
</ul>
</li>
<li>
@@ -253,6 +255,19 @@ ul#navMain {
</ul>
</li>
<li>
+ <a href="#_debugging_memory_leaks">Debugging Memory Leaks</a>
+ <ul>
+
+ <li><a href="#_bleakhouse">BleakHouse</a></li>
+
+ <li><a href="#_valgrind">Valgrind</a></li>
+
+ </ul>
+ </li>
+ <li>
+ <a href="#_plugins_for_debugging">Plugins for Debugging</a>
+ </li>
+ <li>
<a href="#_references">References</a>
</li>
<li>
@@ -325,10 +340,7 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>You'll see something like this:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>--- !ruby/object:Post
attributes:
updated_at: 2008-09-05 22:55:47
@@ -340,8 +352,8 @@ attributes:
attributes_cache: {}
-Title: Rails debugging guide
-</tt></pre></div></div>
+Title: Rails debugging guide</tt></pre>
+</div></div>
<h3 id="_to_yaml">1.2. to_yaml</h3>
<div class="para"><p>Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:</p></div>
<div class="listingblock">
@@ -358,10 +370,7 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>The <tt>to_yaml</tt> method converts the method to YAML format leaving it more readable, and then the <tt>simple_format</tt> helper is used to render each line as in the console. This is how <tt>debug</tt> method does its magic.</p></div>
<div class="para"><p>As a result of this, you will have something like this in your view:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>--- !ruby/object:Post
attributes:
updated_at: 2008-09-05 22:55:47
@@ -372,8 +381,8 @@ id: "1"
created_at: 2008-09-05 22:55:47
attributes_cache: {}
-Title: Rails debugging guide
-</tt></pre></div></div>
+Title: Rails debugging guide</tt></pre>
+</div></div>
<h3 id="_inspect">1.3. inspect</h3>
<div class="para"><p>Another useful method for displaying object values is <tt>inspect</tt>, especially when working with arrays or hashes. This will print the object value as a string. For example:</p></div>
<div class="listingblock">
@@ -389,14 +398,37 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>Will be rendered as follows:</p></div>
<div class="listingblock">
+<div class="content">
+<pre><tt>[1, 2, 3, 4, 5]
+
+Title: Rails debugging guide</tt></pre>
+</div></div>
+<h3 id="_debugging_javascript">1.4. Debugging Javascript</h3>
+<div class="para"><p>Rails has built-in support to debug RJS, to active it, set <tt>ActionView::Base.debug_rjs</tt> to <em>true</em>, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).</p></div>
+<div class="para"><p>To enable it, add the following in the <tt>Rails::Initializer do |config|</tt> block inside <tt>environment.rb</tt>:</p></div>
+<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>[1, 2, 3, 4, 5]
-
-Title: Rails debugging guide
+<pre><tt>config<span style="color: #990000">.</span>action_view<span style="color: #990000">[:</span>debug_rjs<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Or, at any time, setting <tt>ActionView::Base.debug_rjs</tt> to <em>true</em>:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>debug_rjs <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">For more information on debugging javascript refer to <a href="http://getfirebug.com/">Firebug</a>, the popular debugger for Firefox.</td>
+</tr></table>
+</div>
</div>
<h2 id="_the_logger">2. The Logger</h2>
<div class="sectionbody">
@@ -488,11 +520,8 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>Here's an example of the log generated by this method:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>Processing PostsController#create (for <span style="color: #009900">127.0.0.1</span> at 2008-09-08 11:52:54) [POST]
+<div class="content">
+<pre><tt>Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
Parameters: {"commit"=&gt;"Create", "post"=&gt;{"title"=&gt;"Debugging Rails",
@@ -506,8 +535,8 @@ Post should be valid: true
'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
The post was saved and now is the user is going to be redirected...
Redirected to #&lt;Post:0x20af760&gt;
-Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
-</tt></pre></div></div>
+Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]</tt></pre>
+</div></div>
<div class="para"><p>Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia.</p></div>
</div>
<h2 id="_debugging_with_ruby_debug">3. Debugging with ruby-debug</h2>
@@ -540,12 +569,9 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>If you see the message in the console or logs:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>***** Debugger requested, but was not available: Start server with --debugger to enable *****
-</tt></pre></div></div>
+<div class="content">
+<pre><tt>***** Debugger requested, but was not available: Start server with --debugger to enable *****</tt></pre>
+</div></div>
<div class="para"><p>Make sure you have started your web server with the option <tt>&#8212;debugger</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -576,7 +602,7 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>@posts = Post.find(:all)
(rdb:7)</tt></pre>
</div></div>
-<div class="para"><p>Now it's time to play and dig into your application. A good place to start is by asking the debugger for help&#8230; so type: <tt>help</tt> (You didn't see that coming, right?)</p></div>
+<div class="para"><p>Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help&#8230; so type: <tt>help</tt> (You didn't see that coming, right?)</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>(rdb:7) help
@@ -913,7 +939,7 @@ No breakpoints.</tt></pre>
</li>
<li>
<p>
-<tt>finish</tt> [frame-number] (or <tt>fin</tt>): execute until the selected stack frame returns. If no frame number is given, the application run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
+<tt>finish</tt> [frame-number] (or <tt>fin</tt>): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
</p>
</li>
</ul></div>
@@ -969,16 +995,104 @@ No breakpoints.</tt></pre>
</div>
<div class="para"><p>Here's a good start for an <tt>.rdebugrc</tt>:</p></div>
<div class="listingblock">
+<div class="content">
+<pre><tt>set autolist
+set forcestep
+set listsize 25</tt></pre>
+</div></div>
+</div>
+<h2 id="_debugging_memory_leaks">4. Debugging Memory Leaks</h2>
+<div class="sectionbody">
+<div class="para"><p>A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.</p></div>
+<div class="para"><p>In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.</p></div>
+<h3 id="_bleakhouse">4.1. BleakHouse</h3>
+<div class="para"><p><a href="http://github.com/fauna/bleak_house/tree/master">BleakHouse</a> is a library for finding memory leaks.</p></div>
+<div class="para"><p>If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.</p></div>
+<div class="para"><p>To install it run:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>sudo gem install bleak_house</tt></pre>
+</div></div>
+<div class="para"><p>Then setup you application for profiling. Then add the following at the bottom of config/environment.rb:</p></div>
+<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>set autolist
-set forcestep
-set listsize 25
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'bleak_house'</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">'BLEAK_HOUSE'</span><span style="color: #990000">]</span>
</tt></pre></div></div>
+<div class="para"><p>Start a server instance with BleakHouse integration:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house ./script/server</tt></pre>
+</div></div>
+<div class="para"><p>Make sure to run a couple hundred requests to get better data samples, then press <tt>CTRL-C</tt>. The server will stop and Bleak House will produce a dumpfile in <tt>/tmp</tt>:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>** BleakHouse: working...
+** BleakHouse: complete
+** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.</tt></pre>
+</div></div>
+<div class="para"><p>To analyze it, just run the listed command. The top 20 leakiest lines will be listed:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt> 191691 total objects
+ Final heap size 191691 filled, 220961 free
+ Displaying top 20 most common line/class pairs
+ 89513 __null__:__null__:__node__
+ 41438 __null__:__null__:String
+ 2348 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:Array
+ 1508 /opt/local//lib/ruby/gems/1.8/specifications/gettext-1.90.0.gemspec:14:String
+ 1021 /opt/local//lib/ruby/gems/1.8/specifications/heel-0.2.0.gemspec:14:String
+ 951 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:111:String
+ 935 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:String
+ 834 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:146:Array
+ ...</tt></pre>
+</div></div>
+<div class="para"><p>This way you can find where your application is leaking memory and fix it.</p></div>
+<div class="para"><p>If <a href="http://github.com/fauna/bleak_house/tree/master">BleakHouse</a> doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.</p></div>
+<h3 id="_valgrind">4.2. Valgrind</h3>
+<div class="para"><p><a href="http://valgrind.org/">Valgrind</a> is a Linux-only application for detecting C-based memory leaks and race conditions.</p></div>
+<div class="para"><p>There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls <tt>malloc()</tt> but is doesn't properly call <tt>free()</tt>, this memory won't be available until the app terminates.</p></div>
+<div class="para"><p>For further information on how to install Valgrind and use with Ruby, refer to <a href="http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/">Valgrind and Ruby</a> by Evan Weaver.</p></div>
</div>
-<h2 id="_references">4. References</h2>
+<h2 id="_plugins_for_debugging">5. Plugins for Debugging</h2>
+<div class="sectionbody">
+<div class="para"><p>There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<a href="http://github.com/drnic/rails-footnotes/tree/master">Footnotes</a>: Every Rails page has footnotes that give request information and link back to your source via TextMate.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/ntalbott/query_trace/tree/master">Query Trace</a>: Adds query origin tracing to your logs.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/dan-manges/query_stats/tree/master">Query Stats</a>: A Rails plugin to track database queries.
+</p>
+</li>
+<li>
+<p>
+<a href="http://code.google.com/p/query-reviewer/">Query Reviewer</a>: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/rails/exception_notification/tree/master">Exception Notifier</a>: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
+</p>
+</li>
+<li>
+<p>
+<a href="http://github.com/defunkt/exception_logger/tree/master">Exception Logger</a>: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
+</p>
+</li>
+</ul></div>
+</div>
+<h2 id="_references">6. References</h2>
<div class="sectionbody">
<div class="ilist"><ul>
<li>
@@ -1026,14 +1140,24 @@ set listsize 25
<a href="http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging">Ruby on Rails Wiki: How to Configure Logging</a>
</p>
</li>
+<li>
+<p>
+<a href="http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html">Bleak House Documentation</a>
+</p>
+</li>
</ul></div>
</div>
-<h2 id="_changelog">5. Changelog</h2>
+<h2 id="_changelog">7. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
+November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by <a href="../authors.html#miloops">Emilio Tagua</a>
+</p>
+</li>
+<li>
+<p>
October 19, 2008: Copy editing pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html
index f8396bb517..02c1654aa5 100644
--- a/railties/doc/guides/html/finders.html
+++ b/railties/doc/guides/html/finders.html
@@ -199,9 +199,6 @@ ul#navMain {
<h2>Chapters</h2>
<ol>
<li>
- <a href="#_in_the_beginning_8230">In the beginning&#8230;</a>
- </li>
- <li>
<a href="#_the_sample_models">The Sample Models</a>
</li>
<li>
@@ -260,6 +257,21 @@ ul#navMain {
</li>
<li>
<a href="#_named_scopes">Named Scopes</a>
+ <ul>
+
+ <li><a href="#_simple_named_scopes">Simple Named Scopes</a></li>
+
+ <li><a href="#_combining_named_scopes">Combining Named Scopes</a></li>
+
+ <li><a href="#_runtime_evaluation_of_named_scope_conditions">Runtime Evaluation of Named Scope Conditions</a></li>
+
+ <li><a href="#_named_scopes_with_multiple_models">Named Scopes with Multiple Models</a></li>
+
+ <li><a href="#_arguments_to_named_scopes">Arguments to Named Scopes</a></li>
+
+ <li><a href="#_anonymous_scopes">Anonymous Scopes</a></li>
+
+ </ul>
</li>
<li>
<a href="#_existence_of_objects">Existence of Objects</a>
@@ -293,25 +305,48 @@ ul#navMain {
<h1>Rails Finders</h1>
<div id="preamble">
<div class="sectionbody">
-<div class="para"><p>This guide is all about the <tt>find</tt> method defined in <tt>ActiveRecord::Base</tt>, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master.</p></div>
-</div>
+<div class="para"><p>This guide covers the <tt>find</tt> method defined in <tt>ActiveRecord::Base</tt>, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Find records using a variety of methods and conditions
+</p>
+</li>
+<li>
+<p>
+Specify the order, retrieved attributes, grouping, and other properties of the found records
+</p>
+</li>
+<li>
+<p>
+Use eager loading to cut down on the number of database queries in your application
+</p>
+</li>
+<li>
+<p>
+Use dynamic finders
+</p>
+</li>
+<li>
+<p>
+Create named scopes to add custom finding behavior to your models
+</p>
+</li>
+<li>
+<p>
+Check for the existence of particular records
+</p>
+</li>
+<li>
+<p>
+Perform aggregate calculations on Active Record models
+</p>
+</li>
+</ul></div>
+<div class="para"><p>If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.</p></div>
</div>
-<h2 id="_in_the_beginning_8230">1. In the beginning&#8230;</h2>
-<div class="sectionbody">
-<div class="para"><p>In the beginning there was SQL. SQL looked like this:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients
-<span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> id <span style="color: #990000">=</span> <span style="color: #FF0000">'1'</span>
-<span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">0</span><span style="color: #990000">,</span><span style="color: #993399">1</span>
-<span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">ORDER</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> id <span style="font-weight: bold"><span style="color: #0000FF">DESC</span></span> <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">0</span><span style="color: #990000">,</span><span style="color: #993399">1</span>
-</tt></pre></div></div>
-<div class="para"><p>In Rails (unlike some other frameworks) you don't usually have to type SQL because Active Record is there to help you find your records.</p></div>
</div>
-<h2 id="_the_sample_models">2. The Sample Models</h2>
+<h2 id="_the_sample_models">1. The Sample Models</h2>
<div class="sectionbody">
<div class="para"><p>This guide demonstrates finding using the following models:</p></div>
<div class="listingblock">
@@ -342,11 +377,11 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_database_agnostic">3. Database Agnostic</h2>
+<h2 id="_database_agnostic">2. Database Agnostic</h2>
<div class="sectionbody">
<div class="para"><p>Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.</p></div>
</div>
-<h2 id="_ids_first_last_and_all">4. IDs, First, Last and All</h2>
+<h2 id="_ids_first_last_and_all">3. IDs, First, Last and All</h2>
<div class="sectionbody">
<div class="para"><p><tt>ActiveRecord::Base</tt> has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is <tt>find</tt>. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type <tt>Client.find(1)</tt> which would execute this query on your database:</p></div>
<div class="listingblock">
@@ -373,27 +408,29 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(+</span>clients<span style="color: #990000">+.+</span>id<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span> <span style="color: #990000">(</span><span style="color: #993399">1</span><span style="color: #990000">,</span><span style="color: #993399">2</span><span style="color: #990000">))</span>
</tt></pre></div></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>&gt;&gt; Client.find(1,2)
=&gt; [#&lt;Client id: 1, name: =&gt; "Ryan", locked: false, orders_count: 2,
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"&gt;,
#&lt;Client id: 2, name: =&gt; "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"&gt;]
-</tt></pre></div></div>
+ created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"&gt;]</tt></pre>
+</div></div>
<div class="para"><p>Note that if you pass in a list of numbers that the result will be returned as an array, not as a single <tt>Client</tt> object.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If <tt>find(id)</tt> or <tt>find([id1, id2])</tt> fails to find any records, it will raise a <tt>RecordNotFound</tt> exception.</td>
+</tr></table>
+</div>
<div class="para"><p>If you wanted to find the first client you would simply type <tt>Client.first</tt> and that would find the first client created in your clients table:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>&gt;&gt; Client.first
=&gt; #&lt;Client id: 1, name: =&gt; "Ryan", locked: false, orders_count: 2,
- created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"&gt;
-</tt></pre></div></div>
+ created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"&gt;</tt></pre>
+</div></div>
<div class="para"><p>If you were running script/server you might see the following output:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -405,14 +442,11 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>Indicating the query that Rails has performed on your database.</p></div>
<div class="para"><p>To find the last client you would simply type <tt>Client.find(:last)</tt> and that would find the last client created in your clients table:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>&gt;&gt; Client.find(:last)
=&gt; #&lt;Client id: 2, name: =&gt; "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"&gt;
-</tt></pre></div></div>
+ created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"&gt;</tt></pre>
+</div></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -422,28 +456,31 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>To find all the clients you would simply type <tt>Client.all</tt> and that would find all the clients in your clients table:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>&gt;&gt; Client.all
=&gt; [#&lt;Client id: 1, name: =&gt; "Ryan", locked: false, orders_count: 2,
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"&gt;,
#&lt;Client id: 2, name: =&gt; "Michael", locked: false, orders_count: 3,
- created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"&gt;]
-</tt></pre></div></div>
+ created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"&gt;]</tt></pre>
+</div></div>
<div class="para"><p>As alternatives to calling <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt>, you can use the class methods <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt> instead. <tt>Client.first</tt>, <tt>Client.last</tt> and <tt>Client.all</tt> just call their longer counterparts: <tt>Client.find(:first)</tt>, <tt>Client.find(:last)</tt> and <tt>Client.find(:all)</tt> respectively.</p></div>
<div class="para"><p>Be aware that <tt>Client.first</tt>/<tt>Client.find(:first)</tt> and <tt>Client.last</tt>/<tt>Client.find(:last)</tt> will both return a single object, where as <tt>Client.all</tt>/<tt>Client.find(:all)</tt> will return an array of Client objects, just as passing in an array of ids to find will do also.</p></div>
</div>
-<h2 id="_conditions">5. Conditions</h2>
+<h2 id="_conditions">4. Conditions</h2>
<div class="sectionbody">
-<h3 id="_pure_string_conditions">5.1. Pure String Conditions</h3>
+<div class="para"><p>The <tt>find</tt> method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.</p></div>
+<h3 id="_pure_string_conditions">4.1. Pure String Conditions</h3>
<div class="para"><p>If you'd like to add conditions to your find, you could just specify them in there, just like <tt>Client.first(:conditions &#8658; "orders_count = <em>2</em>")</tt>. This will find all clients where the <tt>orders_count</tt> field's value is 2.</p></div>
-<h3 id="_array_conditions">5.2. Array Conditions</h3>
-<div class="literalblock">
-<div class="content">
-<pre><tt>Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions =&gt; ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions =&gt; ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.</tt></pre>
-</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/warning.png" alt="Warning" />
+</td>
+<td class="content">Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, <tt>Client.first(:conditions &#8658; "name LIKE <em>%#{params[:name]}%</em>")</tt> is not safe. See the next section for the preferred way to handle conditions using an array.</td>
+</tr></table>
+</div>
+<h3 id="_array_conditions">4.2. Array Conditions</h3>
+<div class="para"><p>Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like <tt>Client.first(:conditions &#8658; ["orders_count = ?", params[:orders]])</tt>. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like <tt>Client.first(:conditions &#8658; ["orders_count = ? AND locked = ?", params[:orders], false])</tt>. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has <em>2</em> as its value for the orders_count field and <em>false</em> for its locked field.</p></div>
<div class="para"><p>The reason for doing code like:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -510,12 +547,9 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>Got a packet bigger than 'max_allowed_packet' bytes: _query_
-</tt></pre></div></div>
+<div class="content">
+<pre><tt>Got a packet bigger than 'max_allowed_packet' bytes: _query_</tt></pre>
+</div></div>
<div class="para"><p>Where <em>query</em> is the actual query used to get that error.</p></div>
<div class="para"><p>In this example it would be better to use greater-than and less-than operators in SQL, like so:</p></div>
<div class="listingblock">
@@ -536,7 +570,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="color: #990000">[</span><span style="color: #FF0000">"created_at &gt;= ? AND created_at &lt;= ?"</span><span style="color: #990000">,</span> params<span style="color: #990000">[:</span>start_date<span style="color: #990000">],</span> params<span style="color: #990000">[:</span>end_date<span style="color: #990000">]])</span>
</tt></pre></div></div>
<div class="para"><p>Just like in Ruby.</p></div>
-<h3 id="_hash_conditions">5.3. Hash Conditions</h3>
+<h3 id="_hash_conditions">4.3. Hash Conditions</h3>
<div class="para"><p>Similar to the array style of params you can also specify keys in your conditions:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -548,17 +582,17 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>This makes for clearer readability if you have a large number of variable conditions.</p></div>
</div>
-<h2 id="_ordering">6. Ordering</h2>
+<h2 id="_ordering">5. Ordering</h2>
<div class="sectionbody">
<div class="para"><p>If you're getting a set of records and want to force an order, you can use <tt>Client.all(:order &#8658; "created_at")</tt> which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using <tt>Client.all(:order &#8658; "created_at desc")</tt></p></div>
</div>
-<h2 id="_selecting_certain_fields">7. Selecting Certain Fields</h2>
+<h2 id="_selecting_certain_fields">6. Selecting Certain Fields</h2>
<div class="sectionbody">
<div class="para"><p>To select certain fields, you can use the select option like this: <tt>Client.first(:select &#8658; "viewable_by, locked")</tt>. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute <tt>SELECT viewable_by, locked FROM clients LIMIT 0,1</tt> on your database.</p></div>
</div>
-<h2 id="_limit_amp_offset">8. Limit &amp; Offset</h2>
+<h2 id="_limit_amp_offset">7. Limit &amp; Offset</h2>
<div class="sectionbody">
-<div class="para"><p>If you want to limit the amount of records to a certain subset of all the records retreived you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retreived from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:</p></div>
+<div class="para"><p>If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -590,7 +624,7 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">5</span><span style="color: #990000">,</span> <span style="color: #993399">5</span>
</tt></pre></div></div>
</div>
-<h2 id="_group">9. Group</h2>
+<h2 id="_group">8. Group</h2>
<div class="sectionbody">
<div class="para"><p>The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:</p></div>
<div class="listingblock">
@@ -610,9 +644,9 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>orders<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">GROUP</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> <span style="color: #009900">date</span><span style="color: #990000">(</span>created_at<span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_read_only">10. Read Only</h2>
+<h2 id="_read_only">9. Read Only</h2>
<div class="sectionbody">
-<div class="para"><p>Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an <tt>Active Record::ReadOnlyRecord</tt> error. To set this option, specify it like this:</p></div>
+<div class="para"><p>Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an <tt>Active Record::ReadOnlyRecord</tt> exception. To set this option, specify it like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -620,7 +654,7 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>first<span style="color: #990000">(:</span>readonly <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<div class="para"><p>If you assign this record to a variable <tt>client</tt>, calling the following code will raise an ActiveRecord::ReadOnlyRecord:</p></div>
+<div class="para"><p>If you assign this record to a variable <tt>client</tt>, calling the following code will raise an <tt>ActiveRecord::ReadOnlyRecord</tt> exception:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -631,7 +665,7 @@ client<span style="color: #990000">.</span>locked <span style="color: #990000">=
client<span style="color: #990000">.</span>save
</tt></pre></div></div>
</div>
-<h2 id="_lock">11. Lock</h2>
+<h2 id="_lock">10. Lock</h2>
<div class="sectionbody">
<div class="para"><p>If you're wanting to stop race conditions for a specific record (for example, you're incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.</p></div>
<div class="listingblock">
@@ -645,13 +679,13 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_making_it_all_work_together">12. Making It All Work Together</h2>
+<h2 id="_making_it_all_work_together">11. Making It All Work Together</h2>
<div class="sectionbody">
-<div class="para"><p>You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.</p></div>
+<div class="para"><p>You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.</p></div>
</div>
-<h2 id="_eager_loading">13. Eager Loading</h2>
+<h2 id="_eager_loading">12. Eager Loading</h2>
<div class="sectionbody">
-<div class="para"><p>Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use <tt>Client.all(:include &#8658; :address)</tt>. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all), :include &#8658; [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:</p></div>
+<div class="para"><p>Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use <tt>Client.all(:include &#8658; :address)</tt>. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include &#8658; [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -694,7 +728,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="color: #990000">[</span><span style="color: #FF0000">"orders.created_at &gt;= ? AND orders.created_at &lt;= ?"</span><span style="color: #990000">,</span> Time<span style="color: #990000">.</span>now <span style="color: #990000">-</span> <span style="color: #993399">2</span><span style="color: #990000">.</span>weeks<span style="color: #990000">,</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">])</span>
</tt></pre></div></div>
</div>
-<h2 id="_dynamic_finders">14. Dynamic finders</h2>
+<h2 id="_dynamic_finders">13. Dynamic finders</h2>
<div class="sectionbody">
<div class="para"><p>For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called <tt>name</tt> on your Client model for example, you get <tt>find_by_name</tt> and <tt>find_all_by_name</tt> for free from Active Record. If you have also have a <tt>locked</tt> field on the client model, you also get <tt>find_by_locked</tt> and <tt>find_all_by_locked</tt>. If you want to find both by name and locked, you can chain these finders together by simply typing <tt>and</tt> between the fields for example <tt>Client.find_by_name_and_locked(<em>Ryan</em>, true)</tt>. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type <tt>find_by_name(params[:name])</tt> than it is to type <tt>first(:conditions &#8658; ["name = ?", params[:name]])</tt>.</p></div>
<div class="para"><p>There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like <tt>find_or_create_by_name(params[:name])</tt>. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for <tt>Client.find_or_create_by_name(<em>Ryan</em>)</tt>:</p></div>
@@ -719,7 +753,7 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>will either assign an existing client object with the name <em>Ryan</em> to the client local variable, or initialize new object similar to calling <tt>Client.new(:name &#8658; <em>Ryan</em>)</tt>. From here, you can modify other fields in client by calling the attribute setters on it: <tt>client.locked = true</tt> and when you want to write it to the database just call <tt>save</tt> on it.</p></div>
</div>
-<h2 id="_finding_by_sql">15. Finding By SQL</h2>
+<h2 id="_finding_by_sql">14. Finding By SQL</h2>
<div class="sectionbody">
<div class="para"><p>If you'd like to use your own SQL to find records a table you can use <tt>find_by_sql</tt>. The <tt>find_by_sql</tt> method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:</p></div>
<div class="listingblock">
@@ -729,11 +763,11 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>find_by_sql<span style="color: #990000">(</span><span style="color: #FF0000">"SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<div class="para"><p><tt>find_by_sql</tt> provides you with a simple way of making custom calls to the database and retreiving instantiated objects.</p></div>
+<div class="para"><p><tt>find_by_sql</tt> provides you with a simple way of making custom calls to the database and retrieving instantiated objects.</p></div>
</div>
-<h2 id="_tt_select_all_tt">16. <tt>select_all</tt></h2>
+<h2 id="_tt_select_all_tt">15. <tt>select_all</tt></h2>
<div class="sectionbody">
-<div class="para"><p><tt>find_by_sql</tt> has a close relative called <tt>select_all</tt>. <tt>select_all</tt> will retreive objects from the database using custom SQL just like <tt>find_by_sql</tt> but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.</p></div>
+<div class="para"><p><tt>find_by_sql</tt> has a close relative called <tt>connection#select_all</tt>. <tt>select_all</tt> will retrieve objects from the database using custom SQL just like <tt>find_by_sql</tt> but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -742,13 +776,15 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>connection<span style="color: #990000">.</span>select_all<span style="color: #990000">(</span><span style="color: #FF0000">"SELECT * FROM `clients` WHERE `id` = '1'"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_working_with_associations">17. Working with Associations</h2>
+<h2 id="_working_with_associations">16. Working with Associations</h2>
<div class="sectionbody">
-<div class="para"><p>When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like <tt>Client.find(params[:id]).orders.find_by_sent_and_received(true, false)</tt>. Having this find method available on associations is extremely helpful when using nested controllers.</p></div>
+<div class="para"><p>When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like <tt>Client.find(params[:id]).orders.find_by_sent_and_received(true, false)</tt>. Having this find method available on associations is extremely helpful when using nested controllers.</p></div>
</div>
-<h2 id="_named_scopes">18. Named Scopes</h2>
+<h2 id="_named_scopes">17. Named Scopes</h2>
<div class="sectionbody">
-<div class="para"><p>Named scopes are another way to add custom finding behavior to the models in the application. Suppose want to find all clients who are male. Yould use this code:</p></div>
+<div class="para"><p>Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.</p></div>
+<h3 id="_simple_named_scopes">17.1. Simple Named Scopes</h3>
+<div class="para"><p>Suppose want to find all clients who are male. You could use this code:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -758,7 +794,7 @@ http://www.gnu.org/software/src-highlite -->
named_scope <span style="color: #990000">:</span>males<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>gender <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"male"</span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>And you could call it like <tt>Client.males.all</tt> to get all the clients who are male. Please note that if you do not specify the <tt>all</tt> on the end you will get a <tt>Scope</tt> object back, not a set of records which you do get back if you put the <tt>all</tt> on the end.</p></div>
+<div class="para"><p>Then you could call <tt>Client.males.all</tt> to get all the clients who are male. Please note that if you do not specify the <tt>all</tt> on the end you will get a <tt>Scope</tt> object back, not a set of records which you do get back if you put the <tt>all</tt> on the end.</p></div>
<div class="para"><p>If you wanted to find all the clients who are active, you could use this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -769,7 +805,8 @@ http://www.gnu.org/software/src-highlite -->
named_scope <span style="color: #990000">:</span>active<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>active <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>You can call this new named_scope by doing <tt>Client.active.all</tt> and this will do the same query as if we just used <tt>Client.all(:conditions &#8658; ["active = ?", true])</tt>. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do <tt>Client.active.first</tt>.</p></div>
+<div class="para"><p>You can call this new named_scope with <tt>Client.active.all</tt> and this will do the same query as if we just used <tt>Client.all(:conditions &#8658; ["active = ?", true])</tt>. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do <tt>Client.active.first</tt>.</p></div>
+<h3 id="_combining_named_scopes">17.2. Combining Named Scopes</h3>
<div class="para"><p>If you wanted to find all the clients who are active and male you can stack the named scopes like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -786,6 +823,7 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>males<span style="color: #990000">.</span>active<span style="color: #990000">.</span>all<span style="color: #990000">(:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span><span style="color: #FF0000">"age &gt; ?"</span><span style="color: #990000">,</span> params<span style="color: #990000">[:</span>age<span style="color: #990000">]])</span>
</tt></pre></div></div>
+<h3 id="_runtime_evaluation_of_named_scope_conditions">17.3. Runtime Evaluation of Named Scope Conditions</h3>
<div class="para"><p>Consider the following code:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -807,6 +845,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.</p></div>
+<h3 id="_named_scopes_with_multiple_models">17.4. Named Scopes with Multiple Models</h3>
<div class="para"><p>In a named scope you can use <tt>:include</tt> and <tt>:joins</tt> options just like in find.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -819,6 +858,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This method, called as <tt>Client.active_within_2_weeks.all</tt>, will return all clients who have placed orders in the past 2 weeks.</p></div>
+<h3 id="_arguments_to_named_scopes">17.5. Arguments to Named Scopes</h3>
<div class="para"><p>If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -841,7 +881,8 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>This will work with <tt>Client.recent(2.weeks.ago).all</tt> and <tt>Client.recent.all</tt>, with the latter always returning records with a created_at date between right now and 2 weeks ago.</p></div>
<div class="para"><p>Remember that named scopes are stackable, so you will be able to do <tt>Client.recent(2.weeks.ago).unlocked.all</tt> to find all clients created between right now and 2 weeks ago and have their locked field set to false.</p></div>
-<div class="para"><p>Finally, if you wish to define named scopes on the fly you can use the scoped method:</p></div>
+<h3 id="_anonymous_scopes">17.6. Anonymous Scopes</h3>
+<div class="para"><p>All Active Record models come with a named scope named <tt>scoped</tt>, which allows you to create anonymous scopes. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -853,8 +894,17 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>Anonymous scopes are most useful to create scopes "on the fly":</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>Client<span style="color: #990000">.</span>scoped<span style="color: #990000">(:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>gender <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"male"</span> <span style="color: #FF0000">}</span><span style="color: #990000">)</span>
+</tt></pre></div></div>
+<div class="para"><p>Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.</p></div>
</div>
-<h2 id="_existence_of_objects">19. Existence of Objects</h2>
+<h2 id="_existence_of_objects">18. Existence of Objects</h2>
<div class="sectionbody">
<div class="para"><p>If you simply want to check for the existence of the object there's a method called <tt>exists?</tt>. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.</p></div>
<div class="listingblock">
@@ -864,7 +914,7 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>exists?<span style="color: #990000">(</span><span style="color: #993399">1</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<div class="para"><p>The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.</p></div>
+<div class="para"><p>The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -884,7 +934,7 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>exists?<span style="color: #990000">(:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"first_name = 'Ryan'"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_calculations">20. Calculations</h2>
+<h2 id="_calculations">19. Calculations</h2>
<div class="sectionbody">
<div class="para"><p>This section uses count as an example method in this preamble, but the options described apply to all sub-sections.</p></div>
<div class="para"><p><tt>count</tt> takes conditions much in the same way <tt>exists?</tt> does:</p></div>
@@ -922,10 +972,10 @@ http://www.gnu.org/software/src-highlite -->
<span style="color: #990000">(</span>clients<span style="color: #990000">.</span>first_name <span style="color: #990000">=</span> <span style="color: #FF0000">'name'</span> <span style="font-weight: bold"><span style="color: #0000FF">AND</span></span> orders<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">status</span></span> <span style="color: #990000">=</span> <span style="color: #FF0000">'received'</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>This code specifies <tt>clients.first_name</tt> just in case one of the join tables has a field also called <tt>first_name</tt> and it uses <tt>orders.status</tt> because that's the name of our join table.</p></div>
-<h3 id="_count">20.1. Count</h3>
+<h3 id="_count">19.1. Count</h3>
<div class="para"><p>If you want to see how many records are in your model's table you could call <tt>Client.count</tt> and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use <tt>Client.count(:age)</tt>.</p></div>
<div class="para"><p>For options, please see the parent section, Calculations.</p></div>
-<h3 id="_average">20.2. Average</h3>
+<h3 id="_average">19.2. Average</h3>
<div class="para"><p>If you want to see the average of a certain number in one of your tables you can call the <tt>average</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -936,7 +986,7 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.</p></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
-<h3 id="_minimum">20.3. Minimum</h3>
+<h3 id="_minimum">19.3. Minimum</h3>
<div class="para"><p>If you want to find the minimum value of a field in your table you can call the <tt>minimum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -946,7 +996,7 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>minimum<span style="color: #990000">(</span><span style="color: #FF0000">"age"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
-<h3 id="_maximum">20.4. Maximum</h3>
+<h3 id="_maximum">19.4. Maximum</h3>
<div class="para"><p>If you want to find the maximum value of a field in your table you can call the <tt>maximum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -956,7 +1006,7 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>Client<span style="color: #990000">.</span>maximum<span style="color: #990000">(</span><span style="color: #FF0000">"age"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
-<h3 id="_sum">20.5. Sum</h3>
+<h3 id="_sum">19.5. Sum</h3>
<div class="para"><p>If you want to find the sum of a field for all records in your table you can call the <tt>sum</tt> method on the class that relates to the table. This method call will look something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -967,23 +1017,28 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>For options, please see the parent section, <a href="#_calculations">Calculations</a></p></div>
</div>
-<h2 id="_credits">21. Credits</h2>
+<h2 id="_credits">20. Credits</h2>
<div class="sectionbody">
<div class="para"><p>Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.</p></div>
<div class="para"><p>Thanks to Mike Gunderloy for his tips on creating this guide.</p></div>
</div>
-<h2 id="_changelog">22. Changelog</h2>
+<h2 id="_changelog">21. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
-October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section.
+November 8, 2008: Editing pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> . First release version.
+</p>
+</li>
+<li>
+<p>
+October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
</p>
</li>
<li>
<p>
-October 27, 2008: Fixed up all points specified in <a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6">this comment</a> with an exception of the final point.
+October 27, 2008: Fixed up all points specified in <a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6">this comment</a> with an exception of the final point by Ryan Bigg
</p>
</li>
<li>
diff --git a/railties/doc/guides/html/form_helpers.html b/railties/doc/guides/html/form_helpers.html
index 28c317411b..7ff4a13a6a 100644
--- a/railties/doc/guides/html/form_helpers.html
+++ b/railties/doc/guides/html/form_helpers.html
@@ -220,6 +220,16 @@ ul#navMain {
</ul>
</li>
+ <li>
+ <a href="#_making_select_boxes_with_ease">Making select boxes with ease</a>
+ <ul>
+
+ <li><a href="#_the_select_tag_and_options">The select tag and options</a></li>
+
+ <li><a href="#_select_boxes_for_dealing_with_models">Select boxes for dealing with models</a></li>
+
+ </ul>
+ </li>
</ol>
</div>
@@ -227,7 +237,7 @@ ul#navMain {
<h1>Rails form helpers</h1>
<div id="preamble">
<div class="sectionbody">
-<div class="para"><p>Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.</p></div>
+<div class="para"><p>Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.</p></div>
<div class="para"><p>In this guide we will:</p></div>
<div class="ilist"><ul>
<li>
@@ -392,7 +402,7 @@ a submit element.
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
-<td class="content">Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly <tt>expecting tASSOC</tt> syntax error.</td>
+<td class="content">Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an <tt>expecting tASSOC</tt> syntax error.</td>
</tr></table>
</div>
<h3 id="_checkboxes_radio_buttons_and_other_controls">1.3. Checkboxes, radio buttons and other controls</h3>
@@ -431,7 +441,7 @@ output:
<td class="icon">
<img src="./images/icons/important.png" alt="Important" />
</td>
-<td class="content">Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region.</td>
+<td class="content">Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.</td>
</tr></table>
</div>
<div class="para"><p>Other form controls we might mention are the text area, password input and hidden input:</p></div>
@@ -458,7 +468,7 @@ output:
</div>
<h3 id="_how_do_forms_with_put_or_delete_methods_work">1.4. How do forms with PUT or DELETE methods work?</h3>
<div class="para"><p>Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers <em>don't support</em> methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?</p></div>
-<div class="para"><p>Rails works around this issue by emulating other methods over POST with a hidden input named <tt>"<em>method"</tt> that is set to reflect the _real</em> method:</p></div>
+<div class="para"><p>Rails works around this issue by emulating other methods over POST with a hidden input named <tt>"_method"</tt> that is set to reflect the wanted method:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>form_tag(search_path, :method =&gt; "put")
@@ -563,6 +573,64 @@ form_for(@article)</tt></pre>
</tr></table>
</div>
</div>
+<h2 id="_making_select_boxes_with_ease">3. Making select boxes with ease</h2>
+<div class="sectionbody">
+<div class="para"><p>Select boxes in HTML require a significant amount of markup (one <tt>OPTION</tt> element for each option to choose from), therefore it makes the most sense for them to be dynamically generated from data stored in arrays or hashes.</p></div>
+<div class="para"><p>Here is what our wanted markup might look like:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>&lt;select name="city_id" id="city_id"&gt;
+ &lt;option value="1"&gt;Lisabon&lt;/option&gt;
+ &lt;option value="2"&gt;Madrid&lt;/option&gt;
+ ...
+ &lt;option value="12"&gt;Berlin&lt;/option&gt;
+&lt;/select&gt;</tt></pre>
+</div></div>
+<div class="para"><p>Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.</p></div>
+<h3 id="_the_select_tag_and_options">3.1. The select tag and options</h3>
+<div class="para"><p>The most generic helper is <tt>select_tag</tt>, which &#8212; as the name implies &#8212; simply generates the <tt>SELECT</tt> tag that encapsulates the options:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>&lt;%= select_tag(:city_id, '&lt;option value="1"&gt;Lisabon&lt;/option&gt;...') %&gt;</tt></pre>
+</div></div>
+<div class="para"><p>This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.</p></div>
+<div class="para"><p>We can generate option tags with the <tt>options_for_select</tt> helper:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>&lt;%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %&gt;
+
+output:
+
+&lt;option value="1"&gt;Lisabon&lt;/option&gt;
+&lt;option value="2"&gt;Madrid&lt;/option&gt;
+...</tt></pre>
+</div></div>
+<div class="para"><p>For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).</p></div>
+<div class="para"><p>Now you can combine <tt>select_tag</tt> and <tt>options_for_select</tt> to achieve the desired, complete markup:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>&lt;%= select_tag(:city_id, options_for_select(...)) %&gt;</tt></pre>
+</div></div>
+<div class="para"><p>Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The <tt>options_for_select</tt> helper supports this with an optional second argument:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>&lt;%= options_for_select(cities_array, 2) %&gt;
+
+output:
+
+&lt;option value="1"&gt;Lisabon&lt;/option&gt;
+&lt;option value="2" selected="selected"&gt;Madrid&lt;/option&gt;
+...</tt></pre>
+</div></div>
+<div class="para"><p>So whenever Rails sees that the internal value of an option being generated matches this value, it will add the <tt>selected</tt> attribute to that option.</p></div>
+<h3 id="_select_boxes_for_dealing_with_models">3.2. Select boxes for dealing with models</h3>
+<div class="para"><p>Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a <tt>city_id</tt> attribute.</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>...</tt></pre>
+</div></div>
+<div class="para"><p>&#8230;</p></div>
+</div>
</div>
</div>
diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html
index 797ae2fb3a..5111d0c645 100644
--- a/railties/doc/guides/html/getting_started_with_rails.html
+++ b/railties/doc/guides/html/getting_started_with_rails.html
@@ -712,7 +712,7 @@ The <tt>production</tt> environment is used when you deploy your application for
</li>
</ul></div>
<h4 id="_configuring_a_sqlite_database">3.3.1. Configuring a SQLite Database</h4>
-<div class="para"><p>Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.</p></div>
+<div class="para"><p>Rails comes with built-in support for <a href="http://www.sqlite.org/">SQLite</a>, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.</p></div>
<div class="para"><p>Here's the section of the default configuration file with connection information for the development environment:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1159,7 +1159,7 @@ http://www.gnu.org/software/src-highlite -->
<td class="content">For more information on finding records with Active Record, see <a href="../finders.html">Active Record Finders</a>.</td>
</tr></table>
</div>
-<div class="para"><p>The <tt>respond_to</tt> block handles both HTML and XML calls to this action. If you borwse to <tt>http://localhost:3000/posts.xml</tt>, you'll see all of the posts in XML format. The HTML format looks for a view in <tt>app/views/posts/</tt> with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's <tt>app/view/posts/index.html.erb</tt>:</p></div>
+<div class="para"><p>The <tt>respond_to</tt> block handles both HTML and XML calls to this action. If you browse to <tt>http://localhost:3000/posts.xml</tt>, you'll see all of the posts in XML format. The HTML format looks for a view in <tt>app/views/posts/</tt> with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's <tt>app/view/posts/index.html.erb</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1457,51 +1457,57 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use <em>partials</em> to clean up duplication in views and <em>filters</em> to help with duplication in controllers.</p></div>
<h3 id="_using_partials_to_eliminate_view_duplication">7.1. Using Partials to Eliminate View Duplication</h3>
<div class="para"><p>As you saw earlier, the scaffold-generated views for the <tt>new</tt> and <tt>edit</tt> actions are largely identical. You can pull the shared code out into a <tt>partial</tt> template. This requires editing the new and edit views, and adding a new template:</p></div>
-<div class="para"><p><tt>new.html.erb</tt>:
-[source, ruby]</p></div>
+<div class="para"><p><tt>new.html.erb</tt>:</p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt>&lt;h1&gt;New post&lt;/h1&gt;
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="color: #FF0000">&lt;h1&gt;</span>New post<span style="color: #FF0000">&lt;/h1&gt;</span>
-&lt;%= render :partial =&gt; "form" %&gt;
+<span style="color: #FF0000">&lt;%= render :partial =&gt;</span> <span style="color: #FF0000">"form"</span> <span style="color: #990000">%&gt;</span>
-&lt;%= link_to 'Back', posts_path %&gt;</tt></pre>
-</div></div>
-<div class="para"><p><tt>edit.html.erb</tt>:
-[source, ruby]</p></div>
+<span style="color: #FF0000">&lt;%= link_to 'Back', posts_path %&gt;</span>
+</tt></pre></div></div>
+<div class="para"><p><tt>edit.html.erb</tt>:</p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt>&lt;h1&gt;Editing post&lt;/h1&gt;
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="color: #FF0000">&lt;h1&gt;</span>Editing post<span style="color: #FF0000">&lt;/h1&gt;</span>
-&lt;%= render :partial =&gt; "form" %&gt;
+<span style="color: #FF0000">&lt;%= render :partial =&gt;</span> <span style="color: #FF0000">"form"</span> <span style="color: #990000">%&gt;</span>
-&lt;%= link_to 'Show', @post %&gt; |
-&lt;%= link_to 'Back', posts_path %&gt;</tt></pre>
-</div></div>
-<div class="para"><p><tt>_form.html.erb</tt>:
-[source, ruby]</p></div>
+<span style="color: #FF0000">&lt;%= link_to 'Show', @post %&gt;</span> <span style="color: #990000">|</span>
+<span style="color: #FF0000">&lt;%= link_to 'Back', posts_path %&gt;</span>
+</tt></pre></div></div>
+<div class="para"><p><tt>_form.html.erb</tt>:</p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt>&lt;% form_for(@post) do |f| %&gt;
- &lt;%= f.error_messages %&gt;
-
- &lt;p&gt;
- &lt;%= f.label :name %&gt;&lt;br /&gt;
- &lt;%= f.text_field :name %&gt;
- &lt;/p&gt;
- &lt;p&gt;
- &lt;%= f.label :title, "title" %&gt;&lt;br /&gt;
- &lt;%= f.text_field :title %&gt;
- &lt;/p&gt;
- &lt;p&gt;
- &lt;%= f.label :content %&gt;&lt;br /&gt;
- &lt;%= f.text_area :content %&gt;
- &lt;/p&gt;
- &lt;p&gt;
- &lt;%= f.submit "Save" %&gt;
- &lt;/p&gt;
-&lt;% end %&gt;</tt></pre>
-</div></div>
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="color: #FF0000">&lt;% form_for(@post) do |f| %&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.error_messages %&gt;</span>
+
+ <span style="color: #FF0000">&lt;p&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.label :name %&gt;&lt;br /&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.text_field :name %&gt;</span>
+ <span style="color: #FF0000">&lt;/p&gt;</span>
+ <span style="color: #FF0000">&lt;p&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.label :title, "title" %&gt;&lt;br /&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.text_field :title %&gt;</span>
+ <span style="color: #FF0000">&lt;/p&gt;</span>
+ <span style="color: #FF0000">&lt;p&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.label :content %&gt;&lt;br /&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.text_area :content %&gt;</span>
+ <span style="color: #FF0000">&lt;/p&gt;</span>
+ <span style="color: #FF0000">&lt;p&gt;</span>
+ <span style="color: #FF0000">&lt;%= f.submit "Save" %&gt;</span>
+ <span style="color: #FF0000">&lt;/p&gt;</span>
+<span style="color: #FF0000">&lt;% end %&gt;</span>
+</tt></pre></div></div>
<div class="para"><p>Now, when Rails renders the <tt>new</tt> or <tt>edit</tt> view, it will insert the <tt>_form</tt> partial at the indicated point. Note the naming convention for partials: if you refer to a partial named <tt>form</tt> inside of a view, the corresponding file is <tt>_form.html.erb</tt>, with a leading underscore.</p></div>
<div class="para"><p>For more information on partials, refer to the <a href="../layouts_and_rendering.html">Layouts and Rending in Rails</a> guide.</p></div>
<h3 id="_using_filters_to_eliminate_controller_duplication">7.2. Using Filters to Eliminate Controller Duplication</h3>
@@ -1721,32 +1727,32 @@ http://www.gnu.org/software/src-highlite -->
</li>
<li>
<p>
-+app/helpers/comments_helper.rb - A view helper file
+<tt>app/helpers/comments_helper.rb</tt> - A view helper file
</p>
</li>
<li>
<p>
-+app/views/comments/index.html.erb - The view for the index action
+<tt>app/views/comments/index.html.erb</tt> - The view for the index action
</p>
</li>
<li>
<p>
-+app/views/comments/show.html.erb - The view for the show action
+<tt>app/views/comments/show.html.erb</tt> - The view for the show action
</p>
</li>
<li>
<p>
-+app/views/comments/new.html.erb - The view for the new action
+<tt>app/views/comments/new.html.erb</tt> - The view for the new action
</p>
</li>
<li>
<p>
-+app/views/comments/edit.html.erb - The view for the edit action
+<tt>app/views/comments/edit.html.erb</tt> - The view for the edit action
</p>
</li>
<li>
<p>
-+test/functional/comments_controller_test.rb - The functional tests for the controller
+<tt>test/functional/comments_controller_test.rb</tt> - The functional tests for the controller
</p>
</li>
</ul></div>
@@ -1984,7 +1990,7 @@ http://www.gnu.org/software/src-highlite -->
<div class="ilist"><ul>
<li>
<p>
-The [http://manuals.rubyonrails.org/]Ruby On Rails guides
+The <a href="http://manuals.rubyonrails.org/">Ruby On Rails guides</a>
</p>
</li>
<li>
@@ -2003,6 +2009,19 @@ The <a href="http://wiki.rubyonrails.org/rails">Rails wiki</a>
</p>
</li>
</ul></div>
+<div class="para"><p>Rails also comes with built-in help that you can generate using the rake command-line utility:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Running <tt>rake doc:guides</tt> will put a full copy of the Rails Guides in the <tt>/doc/guides</tt> folder of your application. Open <tt>/doc/guides/index.html</tt> in your web browser to explore the Guides.
+</p>
+</li>
+<li>
+<p>
+Running <tt>rake doc:rails</tt> will put a full copy of the API documentation for Rails in the <tt>/doc/api</tt> folder of your application. Open <tt>/doc/api/index.html</tt> in your web browser to explore the API documentation.
+</p>
+</li>
+</ul></div>
</div>
<h2 id="_changelog">10. Changelog</h2>
<div class="sectionbody">
@@ -2010,6 +2029,11 @@ The <a href="http://wiki.rubyonrails.org/rails">Rails wiki</a>
<div class="ilist"><ul>
<li>
<p>
+November 3, 2008: Formatting patch from Dave Rothlisberger
+</p>
+</li>
+<li>
+<p>
November 1, 2008: First approved version by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html
index 306257678b..991b10c7e8 100644
--- a/railties/doc/guides/html/index.html
+++ b/railties/doc/guides/html/index.html
@@ -250,7 +250,7 @@ ul#navMain {
<div class="sidebar-content">
<div class="sidebar-title"><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></div>
<div class="para"><p>This guide covers the basic layout features of Action Controller and Action View,
-including rendering and redirecting, using +content_for_ blocks, and working
+including rendering and redirecting, using <tt>content_for</tt> blocks, and working
with partials.</p></div>
</div></div>
<div class="sidebarblock">
@@ -276,14 +276,6 @@ understand how to use routing in your own Rails applications, start here.</p></d
<div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="actioncontroller_basics.html">Basics of Action Controller</a></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/caution.png" alt="Caution" />
-</td>
-<td class="content"><a href="http://rails.lighthouseapp.com/projects/16213/tickets/17">Lighthouse Ticket</a></td>
-</tr></table>
-</div>
<div class="para"><p>This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.</p></div>
</div></div>
<div class="sidebarblock">
@@ -318,20 +310,12 @@ Enjoy.</p></div>
<div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="security.html">Securing Rails Applications</a></div>
-<div class="para"><p>This manual describes common security problems in web applications and how to
+<div class="para"><p>This guide describes common security problems in web applications and how to
avoid them with Rails.</p></div>
</div></div>
<div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="debugging_rails_applications.html">Debugging Rails Applications</a></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/caution.png" alt="Caution" />
-</td>
-<td class="content"><a href="http://rails.lighthouseapp.com/projects/16213/tickets/5">Lighthouse Ticket</a></td>
-</tr></table>
-</div>
<div class="para"><p>This guide describes how to debug Rails applications. It covers the different
ways of achieving this and how to understand what is happening "behind the scenes"
of your code.</p></div>
diff --git a/railties/doc/guides/html/layouts_and_rendering.html b/railties/doc/guides/html/layouts_and_rendering.html
index 1c9ef8ce24..7138c45853 100644
--- a/railties/doc/guides/html/layouts_and_rendering.html
+++ b/railties/doc/guides/html/layouts_and_rendering.html
@@ -1305,6 +1305,14 @@ http://www.gnu.org/software/src-highlite -->
<pre><tt>&lt;%= render :partial =&gt; "product", :collection =&gt; @products, :as =&gt; :item %&gt;
</tt></pre></div></div>
<div class="para"><p>With this change, you can access an instance of the <tt>@products</tt> collection as the <tt>item</tt> local variable within the partial.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by <tt>_counter</tt>. For example, if you're rendering <tt>@products</tt>, within the partial you can refer to <tt>product_counter</tt> to tell you how many times the partial has been rendered.</td>
+</tr></table>
+</div>
<div class="para"><p>You can also specify a second partial to be rendered between instances of the main partial by using the <tt>:spacer_template</tt> option:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1366,6 +1374,11 @@ http://www.gnu.org/software/src-highlite -->
<div class="ilist"><ul>
<li>
<p>
+November 9, 2008: Added partial collection counter by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
+</p>
+</li>
+<li>
+<p>
November 1, 2008: Added <tt>:js</tt> option for <tt>render</tt> by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
diff --git a/railties/doc/guides/html/migrations.html b/railties/doc/guides/html/migrations.html
index fd466d3a02..8b580d8086 100644
--- a/railties/doc/guides/html/migrations.html
+++ b/railties/doc/guides/html/migrations.html
@@ -717,7 +717,7 @@ version is the numerical prefix on the migration's filename. For example to migr
<div class="content">
<pre><tt>rake db:rollback STEP=3</tt></pre>
</div></div>
-<div class="para"><p>will run the <tt>down</tt> method fron the last 3 migrations.</p></div>
+<div class="para"><p>will run the <tt>down</tt> method from the last 3 migrations.</p></div>
<div class="para"><p>The <tt>db:migrate:redo</tt> task is a shortcut for doing a rollback and then migrating back up again. As with the <tt>db:rollback</tt> task you can use the <tt>STEP</tt> parameter if you need to go more than one version back, for example</p></div>
<div class="listingblock">
<div class="content">
@@ -865,7 +865,7 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either <tt>schema.rb</tt> or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.</p></div>
<div class="para"><p>There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.</p></div>
<div class="para"><p>For example, this is how the test database is created: the current development database is dumped (either to <tt>schema.rb</tt> or <tt>development.sql</tt>) and then loaded into the test database.</p></div>
-<div class="para"><p>Schema files are also useful if want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The <a href="http://agilewebdevelopment.com/plugins/annotate_models">annotate_models</a> plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.</p></div>
+<div class="para"><p>Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The <a href="http://agilewebdevelopment.com/plugins/annotate_models">annotate_models</a> plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.</p></div>
<h3 id="_types_of_schema_dumps">6.2. Types of schema dumps</h3>
<div class="para"><p>There are two ways to dump the schema. This is set in <tt>config/environment.rb</tt> by the <tt>config.active_record.schema_format</tt> setting, which may be either <tt>:sql</tt> or <tt>:ruby</tt>.</p></div>
<div class="para"><p>If <tt>:ruby</tt> is selected then the schema is stored in <tt>db/schema.rb</tt>. If you look at this file you'll find that it looks an awful lot like one very big migration:</p></div>
@@ -899,7 +899,7 @@ http://www.gnu.org/software/src-highlite -->
</div>
<h2 id="foreign_key">7. Active Record and Referential Integrity</h2>
<div class="sectionbody">
-<div class="para"><p>The Active Record way is that intelligence belongs in your models, not in the database. As such features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.</p></div>
+<div class="para"><p>The Active Record way is that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.</p></div>
<div class="para"><p>Validations such as <tt>validates_uniqueness_of</tt> are one way in which models can enforce data integrity. The <tt>:dependent</tt> option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.</p></div>
<div class="para"><p>Although Active Record does not provide any tools for working directly with such features, the <tt>execute</tt> method can be used to execute arbitrary SQL. There are also a number of plugins such as <a href="http://agilewebdevelopment.com/plugins/search?search=redhillonrails">redhillonrails</a> which add foreign key support to Active Record (including support for dumping foreign keys in <tt>schema.rb</tt>).</p></div>
</div>
diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html
index a1f1f98cfb..947d0836ce 100644
--- a/railties/doc/guides/html/routing_outside_in.html
+++ b/railties/doc/guides/html/routing_outside_in.html
@@ -925,6 +925,16 @@ cellspacing="0" cellpadding="4">
<tt>:name_prefix</tt>
</p>
</li>
+<li>
+<p>
+<tt>:only</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>:except</tt>
+</p>
+</li>
</ul></div>
<div class="para"><p>You can also add additional routes via the <tt>:member</tt> and <tt>:collection</tt> options, which are discussed later in this guide.</p></div>
<h4 id="_using_controller">3.6.1. Using :controller</h4>
@@ -1419,6 +1429,34 @@ map<span style="color: #990000">.</span>resources <span style="color: #990000">:
<td class="content">You can also use <tt>:name_prefix</tt> with non-RESTful routes.</td>
</tr></table>
</div>
+<h4 id="_using_only_and_except">3.7.8. Using :only and :except</h4>
+<div class="para"><p>By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the <tt>:only</tt> and <tt>:except</tt> options to fine-tune this behavior. The <tt>:only</tt> option specifies that only certain routes should be generated:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>index<span style="color: #990000">,</span> <span style="color: #990000">:</span>show<span style="color: #990000">]</span>
+</tt></pre></div></div>
+<div class="para"><p>With this declaration, a <tt>GET</tt> request to <tt>/photos</tt> would succeed, but a <tt>POST</tt> request to <tt>/photos</tt> (which would ordinarily be routed to the create action) will fail.</p></div>
+<div class="para"><p>The <tt>:except</tt> option specifies a route or list of routes that should <em>not</em> be generated:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>except <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>destroy
+</tt></pre></div></div>
+<div class="para"><p>In this case, all of the normal routes except the route for <tt>destroy</tt> (a <tt>DELETE</tt> request to <tt>/photos/<em>id</em></tt>) will be generated.</p></div>
+<div class="para"><p>In addition to an action or a list of actions, you can also supply the special symbols <tt>:all</tt> or <tt>:none</tt> to the <tt>:only</tt> and <tt>:except</tt> options.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">If your application has many RESTful routes, using <tt>:only</tt> and <tt>:accept</tt> to generate only the routes that you actually need can cut down on memory use and speed up the routing process.</td>
+</tr></table>
+</div>
<h3 id="_nested_resources">3.8. Nested Resources</h3>
<div class="para"><p>It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:</p></div>
<div class="listingblock">
@@ -1690,15 +1728,7 @@ http://www.gnu.org/software/src-highlite -->
/magazines/2/photos ==&gt; magazines_photos_path(2)
/photos/3 ==&gt; photo_path(3)</tt></pre>
</div></div>
-<div class="para"><p>With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you <em>can</em> supply more information. All of the nested routes continue to work, just as they would without shallow nesting, but less-deeply nested routes (even direct routes) work as well. So, with the declaration above, all of these routes refer to the same resource:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>/publishers/1/magazines/2/photos/3 ==&gt; publisher_magazine_photo_path(1,2,3)
-/magazines/2/photos/3 ==&gt; magazine_photo_path(2,3)
-/photos/3 ==&gt; photo_path(3)</tt></pre>
-</div></div>
-<div class="para"><p>Shallow nesting gives you the flexibility to use the shorter direct routes when you like, while still preserving the longer nested routes for times when they add code clarity.</p></div>
-<div class="para"><p>If you like, you can combine shallow nesting with the <tt>:has_one</tt> and <tt>:has_many</tt> options:</p></div>
+<div class="para"><p>With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. If you like, you can combine shallow nesting with the <tt>:has_one</tt> and <tt>:has_many</tt> options:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
diff --git a/railties/doc/guides/html/testing_rails_applications.html b/railties/doc/guides/html/testing_rails_applications.html
index 73634ef328..b8a99767ee 100644
--- a/railties/doc/guides/html/testing_rails_applications.html
+++ b/railties/doc/guides/html/testing_rails_applications.html
@@ -202,7 +202,7 @@ ul#navMain {
<a href="#_why_write_tests_for_your_rails_applications">Why Write Tests for your Rails Applications?</a>
</li>
<li>
- <a href="#_before_you_start_writing_tests">Before you Start Writing Tests</a>
+ <a href="#_introduction_to_testing">Introduction to Testing</a>
<ul>
<li><a href="#_the_3_environments">The 3 Environments</a></li>
@@ -214,9 +214,11 @@ ul#navMain {
</ul>
</li>
<li>
- <a href="#_unit_testing_your_models">Unit Testing Your Models</a>
+ <a href="#_unit_testing_your_models">Unit Testing your Models</a>
<ul>
+ <li><a href="#_preparing_you_application_for_testing">Preparing you Application for Testing</a></li>
+
<li><a href="#_running_tests">Running Tests</a></li>
<li><a href="#_what_to_include_in_your_unit_tests">What to Include in Your Unit Tests</a></li>
@@ -233,7 +235,7 @@ ul#navMain {
<li><a href="#_what_to_include_in_your_functional_tests">What to include in your Functional Tests</a></li>
- <li><a href="#_available_request_types_for_functional_tests">Available Request Types for Functional Tests===</a></li>
+ <li><a href="#_available_request_types_for_functional_tests">Available Request Types for Functional Tests</a></li>
<li><a href="#_the_4_hashes_of_the_apocalypse">The 4 Hashes of the Apocalypse</a></li>
@@ -256,6 +258,18 @@ ul#navMain {
</ul>
</li>
<li>
+ <a href="#_rake_tasks_for_running_your_tests">Rake Tasks for Running your Tests</a>
+ </li>
+ <li>
+ <a href="#_brief_note_about_test_unit">Brief Note About Test::Unit</a>
+ </li>
+ <li>
+ <a href="#_setup_and_teardown">Setup and Teardown</a>
+ </li>
+ <li>
+ <a href="#_testing_routes">Testing Routes</a>
+ </li>
+ <li>
<a href="#_testing_your_mailers">Testing Your Mailers</a>
<ul>
@@ -268,9 +282,6 @@ ul#navMain {
</ul>
</li>
<li>
- <a href="#_rake_tasks_for_testing">Rake Tasks for Testing</a>
- </li>
- <li>
<a href="#_other_testing_approaches">Other Testing Approaches</a>
</li>
<li>
@@ -309,12 +320,7 @@ Identify other popular testing approaches and plugins
<div class="ilist"><ul>
<li>
<p>
-Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
-</p>
-</li>
-<li>
-<p>
-Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
+Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
</p>
</li>
<li>
@@ -324,16 +330,16 @@ By simply running your Rails tests you can ensure your code adheres to the desir
</li>
<li>
<p>
-Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
+Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
</p>
</li>
</ul></div>
</div>
-<h2 id="_before_you_start_writing_tests">2. Before you Start Writing Tests</h2>
+<h2 id="_introduction_to_testing">2. Introduction to Testing</h2>
<div class="sectionbody">
-<div class="para"><p>Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.</p></div>
+<div class="para"><p>Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.</p></div>
<h3 id="_the_3_environments">2.1. The 3 Environments</h3>
-<div class="para"><p>Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.</p></div>
+<div class="para"><p>Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.</p></div>
<div class="para"><p>One place you'll find this distinction is in the <tt>config/database.yml</tt> file. This YAML configuration file has 3 different sections defining 3 unique database setups:</p></div>
<div class="ilist"><ul>
<li>
@@ -370,9 +376,9 @@ fixtures<span style="color: #990000">/</span> functional<span style="color
<h3 id="_the_low_down_on_fixtures">2.3. The Low-Down on Fixtures</h3>
<div class="para"><p>For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.</p></div>
<h4 id="_what_are_fixtures">2.3.1. What Are Fixtures?</h4>
-<div class="para"><p><em>Fixtures</em> is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: <strong>YAML</strong> or <strong>CSV</strong>.</p></div>
+<div class="para"><p><em>Fixtures</em> is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: <strong>YAML</strong> or <strong>CSV</strong>. In this guide we will use <strong>YAML</strong> which is the preferred format.</p></div>
<div class="para"><p>You'll find fixtures under your <tt>test/fixtures</tt> directory. When you run <tt>script/generate model</tt> to create a new model, fixture stubs will be automatically created and placed in this directory.</p></div>
-<h4 id="_yaml_the_camel_is_a_mammal_with_enamel">2.3.2. YAML the Camel is a Mammal with Enamel</h4>
+<h4 id="_yaml">2.3.2. YAML</h4>
<div class="para"><p>YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the <strong>.yml</strong> file extension (as in <tt>users.yml</tt>).</p></div>
<div class="para"><p>Here's a sample YAML fixture file:</p></div>
<div class="listingblock">
@@ -382,81 +388,18 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-style: italic"><span style="color: #9A1900"># low &amp; behold! I am a YAML comment!</span></span>
david<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">1</span>
name<span style="color: #990000">:</span> David Heinemeier Hansson
birthday<span style="color: #990000">:</span> <span style="color: #993399">1979</span><span style="color: #990000">-</span><span style="color: #993399">10</span><span style="color: #990000">-</span><span style="color: #993399">15</span>
profession<span style="color: #990000">:</span> Systems development
steve<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">2</span>
name<span style="color: #990000">:</span> Steve Ross Kellock
birthday<span style="color: #990000">:</span> <span style="color: #993399">1974</span><span style="color: #990000">-</span><span style="color: #993399">09</span><span style="color: #990000">-</span><span style="color: #993399">27</span>
profession<span style="color: #990000">:</span> guy with keyboard
</tt></pre></div></div>
<div class="para"><p>Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.</p></div>
-<h4 id="_comma_seperated">2.3.3. Comma Seperated</h4>
-<div class="para"><p>Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the <em>test/fixtures</em> directory, but these end with the <tt>.csv</tt> file extension (as in <tt>celebrity_holiday_figures.csv</tt>).</p></div>
-<div class="para"><p>A CSV fixture looks like this:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>id, username, password, stretchable, comments
-1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
-2, ebunny, ihateeggs, true, Hoppity hop y'all
-3, tfairy, ilovecavities, true, "Pull your teeth, I will"
-</tt></pre></div></div>
-<div class="para"><p>The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Leading and trailing spaces are trimmed from each value when it is imported
-</p>
-</li>
-<li>
-<p>
-If you use a comma as data, the cell must be encased in quotes
-</p>
-</li>
-<li>
-<p>
-If you use a quote as data, you must escape it with a 2nd quote
-</p>
-</li>
-<li>
-<p>
-Don't use blank lines
-</p>
-</li>
-<li>
-<p>
-Nulls can be defined by including no data between a pair of commas
-</p>
-</li>
-</ul></div>
-<div class="para"><p>Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-<tt>celebrity-holiday-figures-1</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>celebrity-holiday-figures-2</tt>
-</p>
-</li>
-<li>
-<p>
-<tt>celebrity-holiday-figures-3</tt>
-</p>
-</li>
-</ul></div>
-<div class="para"><p>The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.</p></div>
-<h4 id="_erb_in_it_up">2.3.4. ERb'in It Up</h4>
+<h4 id="_erb_in_it_up">2.3.3. ERb'in It Up</h4>
<div class="para"><p>ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.</p></div>
-<div class="para"><p>I'll demonstrate with a YAML file:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -464,16 +407,16 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% earth_size = 20 -%&gt;</span>
mercury<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">1</span>
size<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= earth_size / 50 %&gt;</span>
+ brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= 113.days.ago.to_s(:db) %&gt;</span>
venus<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">2</span>
size<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= earth_size / 2 %&gt;</span>
+ brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= 67.days.ago.to_s(:db) %&gt;</span>
mars<span style="color: #990000">:</span>
- id<span style="color: #990000">:</span> <span style="color: #993399">3</span>
size<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= earth_size - 69 %&gt;</span>
+ brightest_on<span style="color: #990000">:</span> <span style="color: #FF0000">&lt;%= 13.days.from_now.to_s(:db) %&gt;</span>
</tt></pre></div></div>
<div class="para"><p>Anything encased within the</p></div>
<div class="listingblock">
@@ -483,8 +426,8 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% %&gt;</span>
</tt></pre></div></div>
-<div class="para"><p>tag is considered Ruby code. When this fixture is loaded, the <tt>size</tt> attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.</p></div>
-<h4 id="_fixtures_in_action">2.3.5. Fixtures in Action</h4>
+<div class="para"><p>tag is considered Ruby code. When this fixture is loaded, the <tt>size</tt> attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The <tt>brightest_on</tt> attribute will also be evaluated and formatted by Rails to be compatible with the database.</p></div>
+<h4 id="_fixtures_in_action">2.3.4. Fixtures in Action</h4>
<div class="para"><p>Rails by default automatically loads all fixtures from the <em>test/fixtures</em> folder for your unit and functional test. Loading involves three steps:</p></div>
<div class="ilist"><ul>
<li>
@@ -503,7 +446,7 @@ Dump the fixture data into a variable in case you want to access it directly
</p>
</li>
</ul></div>
-<h4 id="_hashes_with_special_powers">2.3.6. Hashes with Special Powers</h4>
+<h4 id="_hashes_with_special_powers">2.3.5. Hashes with Special Powers</h4>
<div class="para"><p>Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -516,8 +459,7 @@ users<span style="color: #990000">(:</span>david<span style="color: #990000">)</
<span style="font-style: italic"><span style="color: #9A1900"># this will return the property for david called id</span></span>
users<span style="color: #990000">(:</span>david<span style="color: #990000">).</span>id
</tt></pre></div></div>
-<div class="para"><p>But, by there's another side to fixtures&#8230; at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!</p></div>
-<div class="para"><p>Now you can get at the methods only available to that class.</p></div>
+<div class="para"><p>Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -530,22 +472,28 @@ david <span style="color: #990000">=</span> users<span style="color: #990000">(:
email<span style="color: #990000">(</span>david<span style="color: #990000">.</span>girlfriend<span style="color: #990000">.</span>email<span style="color: #990000">,</span> david<span style="color: #990000">.</span>location_tonight<span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
-<h2 id="_unit_testing_your_models">3. Unit Testing Your Models</h2>
+<h2 id="_unit_testing_your_models">3. Unit Testing your Models</h2>
<div class="sectionbody">
<div class="para"><p>In Rails, unit tests are what you write to test your models.</p></div>
-<div class="para"><p>When you create a model using <tt>script/generate</tt>, among other things it creates a test stub in the <tt>test/unit</tt> folder, as well as a fixture for the model:</p></div>
+<div class="para"><p>For this guide we will be using Rails <em>scaffolding</em>. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">For more information on Rails <em>scaffolding</em>, refer to <a href="../getting_started_with_rails.html">Getting Started with Rails</a></td>
+</tr></table>
+</div>
+<div class="para"><p>When you use <tt>script/generate scaffold</tt>, for a resource among other things it creates a test stub in the <tt>test/unit</tt> folder:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>$ script/generate model Post
+<div class="content">
+<pre><tt>$ script/generate scaffold post title:string body:text
...
create app/models/post.rb
create test/unit/post_test.rb
create test/fixtures/posts.yml
-...
-</tt></pre></div></div>
+...</tt></pre>
+</div></div>
<div class="para"><p>The default test stub in <tt>test/unit/post_test.rb</tt> looks like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -617,7 +565,46 @@ is the user's password greater than 5 characters?
</li>
</ul></div>
<div class="para"><p>Every test contains one or more assertions. Only when all the assertions are successful the test passes.</p></div>
-<h3 id="_running_tests">3.1. Running Tests</h3>
+<h3 id="_preparing_you_application_for_testing">3.1. Preparing you Application for Testing</h3>
+<div class="para"><p>Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>$ rake db<span style="color: #990000">:</span>migrate
+<span style="color: #990000">...</span>
+$ rake db<span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">test</span></span><span style="color: #990000">:</span>load
+</tt></pre></div></div>
+<div class="para"><p>Above <tt>rake db:migrate</tt> runs any pending migrations on the <em>developemnt</em> environment and updates <tt>db/schema.rb</tt>. <tt>rake db:test:load</tt> recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run <tt>db:test:prepare</tt> as it first checks for pending migrations and warns you appropriately.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content"><tt>db:test:prepare</tt> will fail with an error if db/schema.rb doesn't exists.</td>
+</tr></table>
+</div>
+<h4 id="_rake_tasks_for_preparing_you_application_for_testing">3.1.1. Rake Tasks for Preparing you Application for Testing ==</h4>
+<div class="para"><p>--------------------------------`----------------------------------------------------
+Tasks Description</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>+rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.</tt></pre>
+</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">You can see all these rake tasks and their descriptions by running <tt>rake &#8212;tasks &#8212;describe</tt></td>
+</tr></table>
+</div>
+<h3 id="_running_tests">3.2. Running Tests</h3>
<div class="para"><p>Running a test is as simple as invoking the file containing the test cases through Ruby:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -637,10 +624,7 @@ Finished <span style="font-weight: bold"><span style="color: #0000FF">in</span><
<div class="para"><p>This will run all the test methods from the test case.</p></div>
<div class="para"><p>You can also run a particular test method from the test case by using the <tt>-n</tt> switch with the <tt>test method name</tt>.</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>$ ruby unit/post_test.rb -n test_truth
Loaded suite unit/post_test
@@ -648,74 +632,98 @@ Started
.
Finished in 0.023513 seconds.
-1 tests, 1 assertions, 0 failures, 0 errors
-</tt></pre></div></div>
+1 tests, 1 assertions, 0 failures, 0 errors</tt></pre>
+</div></div>
<div class="para"><p>The <tt>.</tt> (dot) above indicates a passing test. When a test fails you see an <tt>F</tt>; when a test throws an error you see an <tt>E</tt> in its place. The last line of the output is the summary.</p></div>
-<div class="para"><p>To see how a test failure is reported, you can add a failing test to the <tt>post_test.rb</tt> test case:</p></div>
+<div class="para"><p>To see how a test failure is reported, you can add a failing test to the <tt>post_test.rb</tt> test case.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_have_atleast_one_post
- post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>first<span style="color: #990000">)</span>
- assert_not_nil post
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_not_save_post_without_title
+ post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>new
+ assert <span style="color: #990000">!</span>post<span style="color: #990000">.</span>save
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:</p></div>
+<div class="para"><p>Let us run this newly added test.</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>$ ruby unit/post_test.rb
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.027274 seconds.
+F
+Finished in 0.197094 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-&lt;nil&gt; expected to not be nil.
+&lt;false&gt; is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
-</tt></pre></div></div>
+1 tests, 1 assertions, 1 failures, 0 errors</tt></pre>
+</div></div>
<div class="para"><p>In the output, <tt>F</tt> denotes a failure. You can see the corresponding trace shown under <tt>1)</tt> along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_have_atleast_one_post
- post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>first<span style="color: #990000">)</span>
- assert_not_nil post<span style="color: #990000">,</span> <span style="color: #FF0000">"Should not be nil as Posts table should have atleast one post"</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_not_save_post_without_title
+ post <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>new
+ assert <span style="color: #990000">!</span>post<span style="color: #990000">.</span>save<span style="color: #990000">,</span> <span style="color: #FF0000">"Saved the post without a title"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Running this test shows the friendlier assertion message:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>$ ruby unit/post_test.rb
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.024727 seconds.
+F
+Finished in 0.198093 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-&lt;nil&gt; expected to not be nil.
+Saved the post without a title.
+&lt;false&gt; is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 1 failures, 0 errors</tt></pre>
+</div></div>
+<div class="para"><p>Now to get this test to pass we can add a model level validation for the <em>title</em> field.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Post <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>title
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
+<div class="para"><p>Now the test should pass. Let us verify by running the test again:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+Loaded suite unit/post_test
+Started
+.
+Finished in 0.193608 seconds.
+
+1 tests, 1 assertions, 0 failures, 0 errors</tt></pre>
+</div></div>
+<div class="para"><p>Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as <em>Test-Driven Development</em> (TDD).</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">Many Rails developers practice <em>Test-Driven Development</em> (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with <a href="http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html">15 TDD steps to create a Rails application</a>.</td>
+</tr></table>
+</div>
<div class="para"><p>To see how an error gets reported, here's a test containing an error:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -730,34 +738,23 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>Now you can see even more output in the console from running the tests:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>$ ruby unit/post_test.rb
+<div class="content">
+<pre><tt>$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
-FE.
-Finished in 0.108389 seconds.
-
- 1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-&lt;nil&gt; expected to not be nil.
+E
+Finished in 0.195757 seconds.
- 2) Error:
+ 1) Error:
test_should_report_error(PostTest):
-NameError: undefined local variable or method `some_undefined_variable' for #&lt;PostTest:0x304a7b0&gt;
+NameError: undefined local variable or method `some_undefined_variable' for #&lt;PostTest:0x2cc9de8&gt;
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
- unit/post_test.rb:15:in `test_should_report_error'
+ unit/post_test.rb:16:in `test_should_report_error'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
-3 tests, 2 assertions, 1 failures, 1 errors
-</tt></pre></div></div>
+1 tests, 0 assertions, 0 failures, 1 errors</tt></pre>
+</div></div>
<div class="para"><p>Notice the <em>E</em> in the output. It denotes a test with error.</p></div>
<div class="admonitionblock">
<table><tr>
@@ -767,17 +764,9 @@ NameError: undefined local variable or method `some_undefined_variable' for #&lt
<td class="content">The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.</td>
</tr></table>
</div>
-<h3 id="_what_to_include_in_your_unit_tests">3.2. What to Include in Your Unit Tests</h3>
+<h3 id="_what_to_include_in_your_unit_tests">3.3. What to Include in Your Unit Tests</h3>
<div class="para"><p>Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.</p></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/tip.png" alt="Tip" />
-</td>
-<td class="content">Many Rails developers practice <em>test-driven development</em> (TDD), in which the tests are written <em>before</em> the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with <a href="http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html">15 TDD steps to create a Rails application</a>.</td>
-</tr></table>
-</div>
-<h3 id="_assertions_available">3.3. Assertions Available</h3>
+<h3 id="_assertions_available">3.4. Assertions Available</h3>
<div class="para"><p>By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.</p></div>
<div class="para"><p>There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with <tt>test/unit</tt>, the testing library used by Rails. The <tt>[msg]</tt> parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.</p></div>
<div class="tableblock">
@@ -961,7 +950,7 @@ cellspacing="0" cellpadding="4">
<td class="content">Creating your own assertions is an advanced topic that we won't cover in this tutorial.</td>
</tr></table>
</div>
-<h3 id="_rails_specific_assertions">3.4. Rails Specific Assertions</h3>
+<h3 id="_rails_specific_assertions">3.5. Rails Specific Assertions</h3>
<div class="para"><p>Rails adds some custom assertions of its own to the <tt>test/unit</tt> framework:</p></div>
<div class="tableblock">
<table rules="all"
@@ -1081,34 +1070,8 @@ was the appropriate message displayed to the user in the view
</p>
</li>
</ul></div>
-<div class="para"><p>When you use <tt>script/generate</tt> to create a controller, it automatically creates a functional test for that controller in <tt>test/functional</tt>. For example, if you create a post controller:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt>$ script/generate controller post
-<span style="color: #990000">...</span>
- create app/controllers/post_controller<span style="color: #990000">.</span>rb
- create test/functional/post_controller_test<span style="color: #990000">.</span>rb
-<span style="color: #990000">...</span>
-</tt></pre></div></div>
-<div class="para"><p>Now if you take a look at the file <tt>posts_controller_test.rb</tt> in the <tt>test/functional</tt> directory, you should see:</p></div>
-<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test_helper'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PostsControllerTest <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>TestCase
- <span style="font-style: italic"><span style="color: #9A1900"># Replace this with your real tests.</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_truth
- assert <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:</p></div>
+<div class="para"><p>Now that we have used Rails scaffold generator for our <tt>Post</tt> resource, it has already created the controller code and functional tests. You can take look at the file <tt>posts_controller_test.rb</tt> in the <tt>test/functional</tt> directory.</p></div>
+<div class="para"><p>Let me take you through one such test, <tt>test_should_get_index</tt> from the file <tt>posts_controller_test.rb</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1160,7 +1123,30 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>get<span style="color: #990000">(:</span>view<span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'id'</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'12'</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #FF0000">'message'</span> <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'booya!'</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span>
</tt></pre></div></div>
-<h3 id="_available_request_types_for_functional_tests">4.2. Available Request Types for Functional Tests===</h3>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">If you try running <tt>test_should_create_post</tt> test from <tt>posts_controller_test.rb</tt> it will fail on account of the newly added model level validation and rightly so.</td>
+</tr></table>
+</div>
+<div class="para"><p>Let us modify <tt>test_should_create_post</tt> test in <tt>posts_controller_test.rb</tt> so that all our test pass:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_create_post
+ assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ post <span style="color: #990000">:</span>create<span style="color: #990000">,</span> <span style="color: #990000">:</span>post <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>title <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'Some title'</span><span style="color: #FF0000">}</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ assert_redirected_to post_path<span style="color: #990000">(</span>assigns<span style="color: #990000">(:</span>post<span style="color: #990000">))</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Now you can try running all the tests and they should pass.</p></div>
+<h3 id="_available_request_types_for_functional_tests">4.2. Available Request Types for Functional Tests</h3>
<div class="para"><p>If you're familiar with the HTTP protocol, you'll know that <tt>get</tt> is a type of request. There are 5 request types supported in Rails functional tests:</p></div>
<div class="ilist"><ul>
<li>
@@ -1582,10 +1568,159 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_testing_your_mailers">6. Testing Your Mailers</h2>
+<h2 id="_rake_tasks_for_running_your_tests">6. Rake Tasks for Running your Tests</h2>
+<div class="sectionbody">
+<div class="para"><p>You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.</p></div>
+<div class="para"><p>--------------------------------`----------------------------------------------------
+Tasks Description</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)</tt></pre>
+</div></div>
+</div>
+<h2 id="_brief_note_about_test_unit">7. Brief Note About Test::Unit</h2>
+<div class="sectionbody">
+<div class="para"><p>Ruby ships with a boat load of libraries. One little gem of a library is <tt>Test::Unit</tt>, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in <tt>Test::Unit::Assertions</tt>. The class <tt>ActiveSupport::TestCase</tt> which we have been using in our unit and functional tests extends <tt>Test::Unit::TestCase</tt> that it is how we can use all the basic assertions in our tests.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">For more information on <tt>Test::Unit</tt>, refer to <a href="http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/">test/unit Documentation</a></td>
+</tr></table>
+</div>
+</div>
+<h2 id="_setup_and_teardown">8. Setup and Teardown</h2>
+<div class="sectionbody">
+<div class="para"><p>If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in <tt>Posts</tt> controller:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'test_helper'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PostsControllerTest <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>TestCase
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called before every single test</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> posts<span style="color: #990000">(:</span>one<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called after every single test</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ <span style="font-style: italic"><span style="color: #9A1900"># as we are re-initializing @post before every test</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># setting it to nil here is not essential but I hope</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># you understand how you can use the teardown method</span></span>
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_show_post
+ get <span style="color: #990000">:</span>show<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ assert_response <span style="color: #990000">:</span>success
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_destroy_post
+ assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">,</span> <span style="color: #990000">-</span><span style="color: #993399">1</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ delete <span style="color: #990000">:</span>destroy<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ assert_redirected_to posts_path
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Above, the <tt>setup</tt> method is called before each test and so <tt>@post</tt> is available for each of the tests. Rails implements <tt>setup</tt> and <tt>teardown</tt> as ActiveSupport::Callbacks. Which essentially means you need not only use <tt>setup</tt> and <tt>teardown</tt> as methods in your tests. You could specify them by using:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+a block
+</p>
+</li>
+<li>
+<p>
+a method (like in the earlier example)
+</p>
+</li>
+<li>
+<p>
+a method name as a symbol
+</p>
+</li>
+<li>
+<p>
+a lambda
+</p>
+</li>
+</ul></div>
+<div class="para"><p>Let's see the earlier example by specifying <tt>setup</tt> callback by specifying a method name as a symbol:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'../test_helper'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> PostsControllerTest <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>TestCase
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called before every single test</span></span>
+ setup <span style="color: #990000">:</span>initialize_post
+
+ <span style="font-style: italic"><span style="color: #9A1900"># called after every single test</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_show_post
+ get <span style="color: #990000">:</span>show<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ assert_response <span style="color: #990000">:</span>success
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_update_post
+ put <span style="color: #990000">:</span>update<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id<span style="color: #990000">,</span> <span style="color: #990000">:</span>post <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #FF0000">}</span>
+ assert_redirected_to post_path<span style="color: #990000">(</span>assigns<span style="color: #990000">(:</span>post<span style="color: #990000">))</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_destroy_post
+ assert_difference<span style="color: #990000">(</span><span style="color: #FF0000">'Post.count'</span><span style="color: #990000">,</span> <span style="color: #990000">-</span><span style="color: #993399">1</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ delete <span style="color: #990000">:</span>destroy<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>id
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ assert_redirected_to posts_path
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ private
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> initialize_post
+ <span style="color: #009900">@post</span> <span style="color: #990000">=</span> posts<span style="color: #990000">(:</span>one<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_testing_routes">9. Testing Routes</h2>
+<div class="sectionbody">
+<div class="para"><p>Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default <tt>show</tt> action of <tt>Posts</tt> controller above should look like:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_should_route_to_post
+ assert_routing <span style="color: #FF0000">'/posts/1'</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"posts"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"show"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"1"</span> <span style="color: #FF0000">}</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_testing_your_mailers">10. Testing Your Mailers</h2>
<div class="sectionbody">
<div class="para"><p>Testing mailer classes requires some specific tools to do a thorough job.</p></div>
-<h3 id="_keeping_the_postman_in_check">6.1. Keeping the Postman in Check</h3>
+<h3 id="_keeping_the_postman_in_check">10.1. Keeping the Postman in Check</h3>
<div class="para"><p>Your <tt>ActionMailer</tt> classes &#8212; like every other part of your Rails application &#8212; should be tested to ensure that it is working as expected.</p></div>
<div class="para"><p>The goals of testing your <tt>ActionMailer</tt> classes are to ensure that:</p></div>
<div class="ilist"><ul>
@@ -1605,14 +1740,14 @@ the right emails are being sent at the right times
</p>
</li>
</ul></div>
-<h4 id="_from_all_sides">6.1.1. From All Sides</h4>
+<h4 id="_from_all_sides">10.1.1. From All Sides</h4>
<div class="para"><p>There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture &#8212; yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.</p></div>
-<h3 id="_unit_testing">6.2. Unit Testing</h3>
+<h3 id="_unit_testing">10.2. Unit Testing</h3>
<div class="para"><p>In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.</p></div>
-<h4 id="_revenge_of_the_fixtures">6.2.1. Revenge of the Fixtures</h4>
+<h4 id="_revenge_of_the_fixtures">10.2.1. Revenge of the Fixtures</h4>
<div class="para"><p>For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output <em>should</em> look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within <tt>test/fixtures</tt> directly corresponds to the name of the mailer. So, for a mailer named <tt>UserMailer</tt>, the fixtures should reside in <tt>test/fixtures/user_mailer</tt> directory.</p></div>
<div class="para"><p>When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.</p></div>
-<h4 id="_the_basic_test_case">6.2.2. The Basic Test case</h4>
+<h4 id="_the_basic_test_case">10.2.2. The Basic Test case</h4>
<div class="para"><p>Here's a unit test to test a mailer named <tt>UserMailer</tt> whose action <tt>invite</tt> is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an <tt>invite</tt> action.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1638,19 +1773,16 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>In this test, <tt>@expected</tt> is an instance of <tt>TMail::Mail</tt> that you can use in your tests. It is defined in <tt>ActionMailer::TestCase</tt>. The test above uses <tt>@expected</tt> to construct an email, which it then asserts with email created by the custom mailer. The <tt>invite</tt> fixture is the body of the email and is used as the sample content to assert against. The helper <tt>read_fixture</tt> is used to read in the content from this file.</p></div>
<div class="para"><p>Here's the content of the <tt>invite</tt> fixture:</p></div>
<div class="listingblock">
-<div class="content"><!-- Generator: GNU source-highlight 2.9
-by Lorenzo Bettini
-http://www.lorenzobettini.it
-http://www.gnu.org/software/src-highlite -->
+<div class="content">
<pre><tt>Hi friend@example.com,
You have been invited.
-Cheers!
-</tt></pre></div></div>
+Cheers!</tt></pre>
+</div></div>
<div class="para"><p>This is the right time to understand a little more about writing tests for your mailers. The line <tt>ActionMailer::Base.delivery_method = :test</tt> in <tt>config/environments/test.rb</tt> sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (<tt>ActionMailer::Base.deliveries</tt>).</p></div>
<div class="para"><p>However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be.</p></div>
-<h3 id="_functional_testing">6.3. Functional Testing</h3>
+<h3 id="_functional_testing">10.3. Functional Testing</h3>
<div class="para"><p>Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1673,36 +1805,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_rake_tasks_for_testing">7. Rake Tasks for Testing</h2>
-<div class="sectionbody">
-<div class="para"><p>You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.</p></div>
-<div class="para"><p>--------------------------------`----------------------------------------------------
-Tasks Description</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
-+rake test:units+ Runs all the unit tests from +test/unit+
-+rake test:functionals+ Runs all the functional tests from +test/functional+
-+rake test:integration+ Runs all the integration tests from +test/integration+
-+rake test:recent+ Tests recent changes
-+rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
-+rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
-+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.</tt></pre>
-</div></div>
-<div class="admonitionblock">
-<table><tr>
-<td class="icon">
-<img src="./images/icons/tip.png" alt="Tip" />
-</td>
-<td class="content">You can see all these rake task and their descriptions by running <tt>rake &#8212;tasks &#8212;describe</tt></td>
-</tr></table>
-</div>
-</div>
-<h2 id="_other_testing_approaches">8. Other Testing Approaches</h2>
+<h2 id="_other_testing_approaches">11. Other Testing Approaches</h2>
<div class="sectionbody">
<div class="para"><p>The built-in <tt>test/unit</tt> based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:</p></div>
<div class="ilist"><ul>
@@ -1728,18 +1831,23 @@ link: <a href="http://rspec.info/">RSpec</a>, a behavior-driven development fram
</li>
</ul></div>
</div>
-<h2 id="_changelog">9. Changelog</h2>
+<h2 id="_changelog">12. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
+November 13, 2008: Revised based on feedback from Pratik Naik by <a href="../authors.html#asurve">Akshay Surve</a> (not yet approved for publication)
+</p>
+</li>
+<li>
+<p>
October 14, 2008: Edit and formatting pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
<li>
<p>
-October 12, 2008: First draft by <a href="../authors.html#asurve">Akashay Surve</a> (not yet approved for publication)
+October 12, 2008: First draft by <a href="../authors.html#asurve">Akshay Surve</a> (not yet approved for publication)
</p>
</li>
</ul></div>
diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt
index 2e9e9b8aa1..1e5c21f913 100644
--- a/railties/doc/guides/source/2_2_release_notes.txt
+++ b/railties/doc/guides/source/2_2_release_notes.txt
@@ -44,7 +44,7 @@ The internal documentation of Rails, in the form of code comments, has been impr
All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.
-If you want to these generate guides locally, inside your application:
+If you want to generate these guides locally, inside your application:
[source, ruby]
-------------------------------------------------------
@@ -118,11 +118,12 @@ There are two big additions to talk about here: transactional migrations and poo
=== Transactional Migrations
-Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported *on PostgreSQL only*. The code is extensible to other database types in the future.
+Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.
* Lead Contributor: link:http://adam.blog.heroku.com/[Adam Wiggins]
* More information:
- link:http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/[DDL Transactions]
+ - link:http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/[A major milestone for DB2 on Rails]
=== Connection Pooling
@@ -208,11 +209,11 @@ Active Record association proxies now respect the scope of methods on the proxie
== Action Controller
-On the controller side, there are a couple of changes that will help tidy up your routes.
+On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.
=== Shallow Route Nesting
-Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you _can_ supply more information.
+Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
[source, ruby]
-------------------------------------------------------
@@ -249,7 +250,17 @@ map.resources :photos, :collection => { :search => [:get, :post] }
* Lead Contributor: link:http://brennandunn.com/[Brennan Dunn]
-Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions.
+=== Resources With Specific Actions
+
+By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources.
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :only => [:index, :show]
+map.resources :products, :except => :destroy
+-------------------------------------------------------
+
+* Lead Contributor: link:http://experthuman.com/[Tom Stuart]
=== Other Action Controller Changes
@@ -259,6 +270,8 @@ Action Controller now offers good support for HTTP conditional GET requests, as
* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type.
+* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
+* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+.
== Action View
@@ -274,6 +287,8 @@ Action Mailer now supports mailer layouts. You can make your HTML emails as pret
* More information:
- link:http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts[What's New in Edge Rails: Mailer Layouts]
+Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.
+
== Active Support
Active Support now offers built-in memoization for Rails applications, the +each_with_object+ method, prefix support on delegates, and various other new utility methods.
@@ -388,7 +403,7 @@ You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the com
* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source
* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations.
* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+
-* +script/generate+ works without deprecation warnings when RubyGems 1.3.0 is present
+* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.
== Deprecated
diff --git a/railties/doc/guides/source/actioncontroller_basics/changelog.txt b/railties/doc/guides/source/actioncontroller_basics/changelog.txt
new file mode 100644
index 0000000000..4ee16af19e
--- /dev/null
+++ b/railties/doc/guides/source/actioncontroller_basics/changelog.txt
@@ -0,0 +1,5 @@
+== Changelog ==
+
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17[Lighthouse ticket]
+
+* November 4, 2008: First release version by Tore Darrell
diff --git a/railties/doc/guides/source/actioncontroller_basics/cookies.txt b/railties/doc/guides/source/actioncontroller_basics/cookies.txt
index d451f3f7a6..88b99de3ee 100644
--- a/railties/doc/guides/source/actioncontroller_basics/cookies.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/cookies.txt
@@ -31,4 +31,4 @@ class CommentsController < ApplicationController
end
-----------------------------------------
-Note that while for session values, you set the key to `nil`, to delete a cookie value, you use `cookies.delete(:key)`.
+Note that while for session values, you set the key to `nil`, to delete a cookie value, you should use `cookies.delete(:key)`.
diff --git a/railties/doc/guides/source/actioncontroller_basics/csrf.txt b/railties/doc/guides/source/actioncontroller_basics/csrf.txt
new file mode 100644
index 0000000000..87e3d39c88
--- /dev/null
+++ b/railties/doc/guides/source/actioncontroller_basics/csrf.txt
@@ -0,0 +1,32 @@
+== Request Forgery Protection ==
+
+Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
+
+If you generate a form like this:
+
+[source, ruby]
+-----------------------------------------
+<% form_for @user do |f| -%>
+ <%= f.text_field :username %>
+ <%= f.text_field :password -%>
+<% end -%>
+-----------------------------------------
+
+You will see how the token gets added as a hidden field:
+
+[source, html]
+-----------------------------------------
+<form action="/users/1" method="post">
+<div><!-- ... --><input type="hidden" value="67250ab105eb5ad10851c00a5621854a23af5489" name="authenticity_token"/></div>
+<!-- Fields -->
+</form>
+-----------------------------------------
+
+Rails adds this token to every form that's generated using the link:../form_helpers.html[form helpers], so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method `form_authenticity_token`:
+
+.Add a JavaScript variable containing the token for use with Ajax
+-----------------------------------------
+<%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %>
+-----------------------------------------
+
+The link:../security.html[Security Guide] has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
diff --git a/railties/doc/guides/source/actioncontroller_basics/filters.txt b/railties/doc/guides/source/actioncontroller_basics/filters.txt
index a6f688d144..df67977efd 100644
--- a/railties/doc/guides/source/actioncontroller_basics/filters.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/filters.txt
@@ -1,6 +1,6 @@
== Filters ==
-Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first:
+Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
[source, ruby]
---------------------------------
@@ -27,7 +27,7 @@ private
end
---------------------------------
-The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704[before_filter] method:
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the `before_filter` method:
[source, ruby]
---------------------------------
@@ -38,7 +38,7 @@ class ApplicationController < ActionController::Base
end
---------------------------------
-In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this, so to prevent this filter from running you can use link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711[skip_before_filter] :
+In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter` :
[source, ruby]
---------------------------------
@@ -49,9 +49,9 @@ class LoginsController < Application
end
---------------------------------
-Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+Now, the +LoginsController+'s "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
-=== After filters and around filters ===
+=== After Filters and Around Filters ===
In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
@@ -75,11 +75,11 @@ private
end
---------------------------------
-=== Other ways to use filters ===
+=== Other Ways to Use Filters ===
While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
-The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritte to use a block:
+The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
[source, ruby]
---------------------------------
@@ -92,7 +92,7 @@ end
Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
-The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class:
+The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
[source, ruby]
---------------------------------
@@ -114,6 +114,6 @@ class LoginFilter
end
---------------------------------
-Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action.
+Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action.
The Rails API documentation has link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html[more information on using filters].
diff --git a/railties/doc/guides/source/actioncontroller_basics/http_auth.txt b/railties/doc/guides/source/actioncontroller_basics/http_auth.txt
index 7df0e635bf..8deb40c2c9 100644
--- a/railties/doc/guides/source/actioncontroller_basics/http_auth.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/http_auth.txt
@@ -1,12 +1,12 @@
== HTTP Basic Authentication ==
-Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, link:http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610[authenticate_or_request_with_http_basic].
+Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, `authenticate_or_request_with_http_basic`.
[source, ruby]
-------------------------------------
class AdminController < ApplicationController
- USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c"
+ USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
before_filter :authenticate
@@ -14,7 +14,7 @@ private
def authenticate
authenticate_or_request_with_http_basic do |username, password|
- username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD
+ username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD
end
end
diff --git a/railties/doc/guides/source/actioncontroller_basics/index.txt b/railties/doc/guides/source/actioncontroller_basics/index.txt
index 0b884e590b..6865ace97b 100644
--- a/railties/doc/guides/source/actioncontroller_basics/index.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/index.txt
@@ -1,7 +1,15 @@
Action Controller basics
=======================
-In this guide you will learn how controllers work and how they fit into the request cycle in your application. You will learn how to make use of the many tools provided by Action Controller to work with the session, cookies and filters and how to use the built-in HTTP authentication and data streaming facilities. In the end, we will take a look at some tools that will be useful once your controllers are ready and working, like how to filter sensitive parameters from the log and how to rescue and deal with exceptions that may be raised during the request.
+In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:
+
+* Follow the flow of a request through a controller
+* Understand why and how to store data in the session or cookies
+* Work with filters to execute code during request processing
+* Use Action Controller's built-in HTTP authentication
+* Stream data directly to the user's browser
+* Filter sensitive parameters so they do not appear in the application's log
+* Deal with exceptions that may be raised during request processing
include::introduction.txt[]
@@ -17,6 +25,8 @@ include::filters.txt[]
include::verification.txt[]
+include::csrf.txt[]
+
include::request_response_objects.txt[]
include::http_auth.txt[]
@@ -26,3 +36,5 @@ include::streaming.txt[]
include::parameter_filtering.txt[]
include::rescue.txt[]
+
+include::changelog.txt[]
diff --git a/railties/doc/guides/source/actioncontroller_basics/introduction.txt b/railties/doc/guides/source/actioncontroller_basics/introduction.txt
index e4b0953b95..6ea217dbb9 100644
--- a/railties/doc/guides/source/actioncontroller_basics/introduction.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/introduction.txt
@@ -1,7 +1,9 @@
-== What does a controller do? ==
+== What Does a Controller do? ==
Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
-A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model.
+A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
+
+NOTE: For more details on the routing process, see link:../routing_outside_in.html[Rails Routing from the Outside In].
diff --git a/railties/doc/guides/source/actioncontroller_basics/methods.txt b/railties/doc/guides/source/actioncontroller_basics/methods.txt
index 370b492e41..68204c189a 100644
--- a/railties/doc/guides/source/actioncontroller_basics/methods.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/methods.txt
@@ -1,16 +1,16 @@
-== Methods and actions ==
+== Methods and Actions ==
-A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) gets run.
+A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.
[source, ruby]
----------------------------------------------
-class ClientsController < ActionController::Base
+class ClientsController < ApplicationController
# Actions are public methods
def new
end
- # These methods are responsible for producing output
+ # Action methods are responsible for producing output
def edit
end
@@ -23,9 +23,9 @@ private
end
----------------------------------------------
-Private methods in a controller are also used as filters, which will be covered later in this guide.
+There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.
-As an example, if the user goes to `/clients/new` in your application to add a new client, a ClientsController instance will be created and the `new` method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
+As an example, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of ClientsController and run the `new` method. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
[source, ruby]
----------------------------------------------
@@ -35,3 +35,5 @@ end
----------------------------------------------
The link:../layouts_and_rendering.html[Layouts & rendering guide] explains this in more detail.
+
+ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
diff --git a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
index c4577d4f6d..e29f631038 100644
--- a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
@@ -1,6 +1,6 @@
-== Parameter filtering ==
+== Parameter Filtering ==
-Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000837[filter_parameter_logging] method can be used to filter out sensitive information from the log. It works by replacing certain keys in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
[source, ruby]
-------------------------
diff --git a/railties/doc/guides/source/actioncontroller_basics/params.txt b/railties/doc/guides/source/actioncontroller_basics/params.txt
index 7f494d7c9b..e8a2d3d058 100644
--- a/railties/doc/guides/source/actioncontroller_basics/params.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/params.txt
@@ -1,14 +1,15 @@
== Parameters ==
-You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller:
+You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller:
[source, ruby]
-------------------------------------
class ClientsController < ActionController::Base
- # This action uses query string parameters because it gets run by a HTTP GET request,
- # but this does not make any difference to the way in which the parameters are accessed.
- # The URL for this action would look like this in order to list activated clients: /clients?status=activated
+ # This action uses query string parameters because it gets run by a HTTP
+ # GET request, but this does not make any difference to the way in which
+ # the parameters are accessed. The URL for this action would look like this
+ # in order to list activated clients: /clients?status=activated
def index
if params[:status] = "activated"
@clients = Client.activated
@@ -34,14 +35,16 @@ class ClientsController < ActionController::Base
end
-------------------------------------
-=== Hash and array parameters ===
+=== Hash and Array Parameters ===
The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
-------------------------------------
-GET /clients?ids[]=1&ids[2]&ids[]=3
+GET /clients?ids[]=1&ids[]=2&ids[]=3
-------------------------------------
+NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
+
The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
To send a hash you include the key name inside the brackets:
@@ -55,8 +58,36 @@ To send a hash you include the key name inside the brackets:
</form>
-------------------------------------
-The value of `params[:client]` when this form is submitted will be `{:name => "Acme", :phone => "12345", :address => {:postcode => "12345", :city => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`.
+The value of `params[:client]` when this form is submitted will be `{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`.
+
+Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.
+
+=== Routing Parameters ===
+
+The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the `:status` parameter in a "pretty" URL:
+
+[source, ruby]
+------------------------------------
+# ...
+map.connect "/clients/:status", :controller => "clients", :action => "index", :foo => "bar"
+# ...
+------------------------------------
+
+In this case, when a user opens the URL `/clients/active`, `params[:status]` will be set to "active". When this route is used, `params[:foo]` will also be set to "bar" just like it was passed in the query string in the same way `params[:action]` will contain "index".
-=== Routing parameters ===
+=== `default_url_options` ===
+
+You can set global default parameters that will be used when generating URLs with `default_url_options`. To do this, define a method with that name in your controller:
+
+------------------------------------
+class ApplicationController < ActionController::Base
+
+ #The options parameter is the hash passed in to +url_for+
+ def default_url_options(options)
+ {:locale => I18n.locale}
+ end
+
+end
+------------------------------------
-The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available.
+These options will be used as a starting-point when generating, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
diff --git a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
index 493bd4cb43..07a8ec2574 100644
--- a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
@@ -1,13 +1,13 @@
-== The request and response objects ==
+== The +request+ and +response+ Objects ==
-In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[AbstractRequest] and the `response` method contains the link:http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb[response object] representing what is going to be sent back to the client.
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of AbstractRequest and the `response` method returns a +response+ object representing what is going to be sent back to the client.
-=== The request ===
+=== The +request+ Object ===
-The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation].
+The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation]. Among the properties that you can access on this object are:
* host - The hostname used for this request.
- * domain - The hostname without the first part (usually "www").
+ * domain - The hostname without the first segment (usually "www").
* format - The content type requested by the client.
* method - The HTTP method used for the request.
* get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
@@ -18,18 +18,26 @@ The request object contains a lot of useful information about the request coming
* remote_ip - The IP address of the client.
* url - The entire URL used for the request.
-==== path_parameters, query_parameters and request_parameters ====
+==== +path_parameters+, +query_parameters+ and +request_parameters+ ====
-TODO: Does this belong here?
+Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
-Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action.
+=== The +response+ Object ===
-=== The response ===
-
-The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
+The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
* body - This is the string of data being sent back to the client. This is most often HTML.
* status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
* location - The URL the client is being redirected to, if any.
* content_type - The content type of the response.
* charset - The character set being used for the response. Default is "utf8".
+ * headers - Headers used for the response.
+
+==== Setting Custom Headers ====
+
+If you want to set custom headers for a response then `response.headers` is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to `headers` with the name and value:
+
+[source, ruby]
+-------------------------------------
+response.headers["Content-Type"] = "application/pdf"
+-------------------------------------
diff --git a/railties/doc/guides/source/actioncontroller_basics/rescue.txt b/railties/doc/guides/source/actioncontroller_basics/rescue.txt
index ec03006764..3353df617c 100644
--- a/railties/doc/guides/source/actioncontroller_basics/rescue.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/rescue.txt
@@ -2,15 +2,15 @@
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
-=== The default 500 and 404 templates ===
+=== The Default 500 and 404 Templates ===
By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
=== `rescue_from` ===
-If you want to do something a bit more elaborate when catching errors, you can use link::http://api.rubyonrails.org/classes/ActionController/Rescue/ClassMethods.html#M000620[rescue_from], which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the `:with` option. You can also use a block directly instead of an explicit Proc object.
+If you want to do something a bit more elaborate when catching errors, you can use `rescue_from`, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the `:with` option. You can also use a block directly instead of an explicit Proc object.
-Let's see how we can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.
+Here's how you can use +rescue_from+ to intercept all ActiveRecord::RecordNotFound errors and do something with them.
[source, ruby]
-----------------------------------
@@ -27,7 +27,7 @@ private
end
-----------------------------------
-Of course, this example is anything but elaborate and doesn't improve the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
+Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
[source, ruby]
-----------------------------------
diff --git a/railties/doc/guides/source/actioncontroller_basics/session.txt b/railties/doc/guides/source/actioncontroller_basics/session.txt
index 467cffbf85..ae5f876777 100644
--- a/railties/doc/guides/source/actioncontroller_basics/session.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/session.txt
@@ -1,15 +1,17 @@
== Session ==
-Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and can use one of a number of different storage mechanisms:
+Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
* CookieStore - Stores everything on the client.
- * DRBStore - Stores the data on a DRb client.
- * MemCacheStore - Stores the data in MemCache.
+ * DRbStore - Stores the data on a DRb server.
+ * MemCacheStore - Stores the data in a memcache.
* ActiveRecordStore - Stores the data in a database using Active Record.
-All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server.
+All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).
-The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
+Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
+
+Read more about session storage in the link:../security.html[Security Guide].
If you need a different session storage mechanism, you can change it in the `config/environment.rb` file:
@@ -19,9 +21,9 @@ If you need a different session storage mechanism, you can change it in the `con
config.action_controller.session_store = :active_record_store
------------------------------------------
-=== Disabling the session ===
+=== Disabling the Session ===
-Sometimes you don't need a session, and you can turn it off to avoid the unnecessary overhead. To do this, use the link:http://api.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html#M000649[session] class method in your controller:
+Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the `session` class method in your controller:
[source, ruby]
------------------------------------------
@@ -41,7 +43,7 @@ class LoginsController < ActionController::Base
end
------------------------------------------
-Or even a single action:
+Or even for specified actions:
[source, ruby]
------------------------------------------
@@ -50,11 +52,11 @@ class ProductsController < ActionController::Base
end
------------------------------------------
-=== Accessing the session ===
+=== Accessing the Session ===
In your controller you can access the session through the `session` instance method.
-NOTE: There are two `session` methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. The class method is used outside of method definitions while the instance methods is used inside methods, in actions or filters.
+NOTE: There are two `session` methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values.
Session values are stored using key/value pairs like a hash:
@@ -65,7 +67,7 @@ class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key :current_user_id
- # This is a common way to do user login in a Rails application; logging in sets the
+ # This is a common way to handle user login in a Rails application; logging in sets the
# session value and logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
@@ -108,11 +110,11 @@ class LoginsController < ApplicationController
end
------------------------------------------
-To reset the entire session, use link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000855[reset_session].
+To reset the entire session, use `reset_session`.
=== The flash ===
-The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request:
+The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
[source, ruby]
------------------------------------------
@@ -127,7 +129,7 @@ class LoginsController < ApplicationController
end
------------------------------------------
-The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout:
+The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
------------------------------------------
<html>
@@ -163,7 +165,7 @@ class MainController < ApplicationController
end
------------------------------------------
-==== flash.now ====
+==== +flash.now+ ====
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the `create` action fails to save a resource and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use `flash.now` in the same way you use the normal `flash`:
diff --git a/railties/doc/guides/source/actioncontroller_basics/streaming.txt b/railties/doc/guides/source/actioncontroller_basics/streaming.txt
index 41d56935b9..dc8ebe6d55 100644
--- a/railties/doc/guides/source/actioncontroller_basics/streaming.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/streaming.txt
@@ -1,6 +1,6 @@
-== Streaming and file downloads ==
+== Streaming and File Downloads ==
-Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624[send_data] and the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623[send_file] methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the `send_data` and the `send_file` methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
To stream data to the client, use `send_data`:
@@ -31,7 +31,7 @@ end
The `download_pdf` action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:disposition` option to "inline". The opposite and default value for this option is "attachment".
-=== Sending files ===
+=== Sending Files ===
If you want to send a file that already exists on disk, use the `send_file` method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.
@@ -48,15 +48,15 @@ class ClientsController < ApplicationController
end
----------------------------
-This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option.
+This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `:stream` option or adjust the block size with the `:buffer_size` option.
-WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk as someone could gain access to files they are not meant to have access to.
+WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
-=== RESTful downloads ===
+=== RESTful Downloads ===
-While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action:
+While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the `show` action, without any streaming:
[source, ruby]
----------------------------
@@ -75,7 +75,7 @@ class ClientsController < ApplicationController
end
----------------------------
-In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`:
+In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`:
[source, ruby]
----------------------------
diff --git a/railties/doc/guides/source/actioncontroller_basics/verification.txt b/railties/doc/guides/source/actioncontroller_basics/verification.txt
index 39046eee85..5d8ee6117e 100644
--- a/railties/doc/guides/source/actioncontroller_basics/verification.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/verification.txt
@@ -1,8 +1,8 @@
== Verification ==
-Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the link:http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html[API codumentation] as "essentially a special kind of before_filter".
+Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the link:http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html[API documentation] as "essentially a special kind of before_filter".
-Let's see how we can use verification to make sure the user supplies a username and a password in order to log in:
+Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
[source, ruby]
---------------------------------------
@@ -34,7 +34,7 @@ class LoginsController < ApplicationController
verify :params => [:username, :password],
:render => {:action => "new"},
:add_flash => {:error => "Username and password required to log in"},
- :only => :create #Only run this verification for the "create" action
+ :only => :create # Only run this verification for the "create" action
end
---------------------------------------
diff --git a/railties/doc/guides/source/active_record_basics.txt b/railties/doc/guides/source/active_record_basics.txt
index 15fc544f25..892adb2d43 100644
--- a/railties/doc/guides/source/active_record_basics.txt
+++ b/railties/doc/guides/source/active_record_basics.txt
@@ -1,7 +1,7 @@
Active Record Basics
====================
-Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of AcitveRecord.
+Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of ActiveRecord.
After reading this guide readers should have a strong grasp of the Active Record pattern and how it can be used with or without Rails. Hopefully, some of the philosophical and theoretical intentions discussed here will also make them a stronger and better developer.
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
new file mode 100644
index 0000000000..fd6eb86b0b
--- /dev/null
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -0,0 +1,404 @@
+Active Record Validations and Callbacks
+=======================================
+
+This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.
+
+After reading this guide and trying out the presented concepts, we hope that you'll be able to:
+
+* Correctly use all the built-in Active Record validation helpers
+* Create your own custom validation methods
+* Work with the error messages generated by the validation proccess
+* Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
+* Create special classes that encapsulate common behaviour for your callbacks
+* Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
+
+== Motivations to validate your Active Record objects
+
+The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
+
+There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:
+
+* Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
+* Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
+* Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
+
+== How it works
+
+=== When does validation happens?
+
+There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it'll be recorded to it's table. Active Record uses the +new_record?+ instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+end
+------------------------------------------------------------------
+
+We can see how it works by looking at the following script/console output:
+
+------------------------------------------------------------------
+>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
+=> #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
+>> p.new_record?
+=> true
+>> p.save
+=> true
+>> p.new_record?
+=> false
+------------------------------------------------------------------
+
+Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+
+=== The meaning of 'valid'
+
+For verifying if an object is valid, Active Record uses the +valid?+ method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the +errors+ instance method. The proccess is really simple: If the +errors+ method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the +errors+ collection.
+
+== The declarative validation helpers
+
+Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's +errors+ collection, this message being associated with the field being validated.
+
+Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.
+
+All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when it fails, respectively. The +:on+ option takes one the values +:save+ (it's the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.
+
+=== The +validates_acceptance_of+ helper
+
+Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_acceptance_of :terms_of_service
+end
+------------------------------------------------------------------
+
+The default error message for +validates_acceptance_of+ is "_must be accepted_"
+
++validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_acceptance_of :terms_of_service, :accept => 'yes'
+end
+------------------------------------------------------------------
+
+
+=== The +validates_associated+ helper
+
+You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects.
+
+[source, ruby]
+------------------------------------------------------------------
+class Library < ActiveRecord::Base
+ has_many :books
+ validates_associated :books
+end
+------------------------------------------------------------------
+
+This validation will work with all the association types.
+
+CAUTION: Pay attention not to use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
+
+The default error message for +validates_associated+ is "_is invalid_". Note that the errors for each failed validation in the associated objects will be set there and not in this model.
+
+=== The +validates_confirmation_of+ helper
+
+You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with '_confirmation' appended.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_confirmation_of :email
+end
+------------------------------------------------------------------
+
+In your view template you could use something like
+------------------------------------------------------------------
+<%= text_field :person, :email %>
+<%= text_field :person, :email_confirmation %>
+------------------------------------------------------------------
+
+NOTE: This check is performed only if +email_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide):
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_confirmation_of :email
+ validates_presence_of :email_confirmation
+end
+------------------------------------------------------------------
+
+The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_"
+
+=== The +validates_each+ helper
+
+This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_each :name, :surname do |model, attr, value|
+ model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/
+ end
+end
+------------------------------------------------------------------
+
+The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.
+
+=== The +validates_exclusion_of+ helper
+
+This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
+
+[source, ruby]
+------------------------------------------------------------------
+class MovieFile < ActiveRecord::Base
+ validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
+end
+------------------------------------------------------------------
+
+The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
+
+The default error message for +validates_exclusion_of+ is "_is not included in the list_".
+
+=== The +validates_format_of+ helper
+
+This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the +:with+ option.
+
+[source, ruby]
+------------------------------------------------------------------
+class Product < ActiveRecord::Base
+ validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
+end
+------------------------------------------------------------------
+
+The default error message for +validates_format_of+ is "_is invalid_".
+
+=== The +validates_inclusion_of+ helper
+
+This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
+
+[source, ruby]
+------------------------------------------------------------------
+class Coffee < ActiveRecord::Base
+ validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
+end
+------------------------------------------------------------------
+
+The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
+
+The default error message for +validates_inclusion_of+ is "_is not included in the list_".
+
+=== The +validates_length_of+ helper
+
+This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_length_of :name, :minimum => 2
+ validates_length_of :bio, :maximum => 500
+ validates_length_of :password, :in => 6..20
+ validates_length_of :registration_number, :is => 6
+end
+------------------------------------------------------------------
+
+The possible length constraint options are:
+
+* +:minimum+ - The attribute cannot have less than the specified length.
+* +:maximum+ - The attribute cannot have more than the specified length.
+* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
+* +:is+ - The attribute length must be equal to a given value.
+
+The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the +:message+ option to specify an error message.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
+end
+------------------------------------------------------------------
+
+This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
+
+=== The +validates_numericallity_of+ helper
+
+This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
+
+If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z/$$+ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using +Kernel.Float+.
+
+[source, ruby]
+------------------------------------------------------------------
+class Player < ActiveRecord::Base
+ validates_numericallity_of :points
+ validates_numericallity_of :games_played, :integer_only => true
+end
+------------------------------------------------------------------
+
+The default error message for +validates_numericallity_of+ is "_is not a number_".
+
+=== The +validates_presence_of+ helper
+
+This helper validates that the attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_presence_of :name, :login, :email
+end
+------------------------------------------------------------------
+
+NOTE: If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.
+
+[source, ruby]
+------------------------------------------------------------------
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+ validates_presence_of :order_id
+end
+------------------------------------------------------------------
+
+NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
+
+The default error message for +validates_presence_of+ is "_can't be empty_".
+
+=== The +validates_uniqueness_of+ helper
+
+This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.
+
+[source, ruby]
+------------------------------------------------------------------
+class Account < ActiveRecord::Base
+ validates_uniqueness_of :email
+end
+------------------------------------------------------------------
+
+The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.
+
+There is a +:scope+ option that you can use to specify other attributes that must be used to define uniqueness:
+
+[source, ruby]
+------------------------------------------------------------------
+class Holiday < ActiveRecord::Base
+ validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
+end
+------------------------------------------------------------------
+
+There is also a +:case_sensitive+ option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_uniqueness_of :name, :case_sensitive => false
+end
+------------------------------------------------------------------
+
+The default error message for +validates_uniqueness_of+ is "_has already been taken_".
+
+== Common validation options
+
+There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which we'll cover right at the next topic.
+
+=== The +:allow_nil+ option
+
+You may use the +:allow_nil+ option everytime you just want to trigger a validation if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+.
+
+[source, ruby]
+------------------------------------------------------------------
+class Coffee < ActiveRecord::Base
+ validates_inclusion_of :size, :in => %w(small medium large),
+ :message => "%s is not a valid size", :allow_nil => true
+end
+------------------------------------------------------------------
+
+=== The +:message+ option
+
+As stated before, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
+
+=== The +:on+ option
+
+As stated before, the +:on+ option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on =$$>$$ :create+ to run the validation only when a new record is created or +:on =$$>$$ :update+ to run the validation only when a record is updated.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
+ validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
+ validates_presence_of :name, :on => :save # => that's the default
+end
+------------------------------------------------------------------
+
+== Conditional validation
+
+Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a Ruby Proc. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option.
+
+=== Using a symbol with the +:if+ and +:unless+ options
+
+You can associated the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
+
+[source, ruby]
+------------------------------------------------------------------
+class Order < ActiveRecord::Base
+ validates_presence_of :card_number, :if => :paid_with_card?
+
+ def paid_with_card?
+ payment_type == "card"
+ end
+end
+------------------------------------------------------------------
+
+=== Using a string with the +:if+ and +:unless+ options
+
+You can also use a string that will be evaluated using +:eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_presence_of :surname, :if => "name.nil?"
+end
+------------------------------------------------------------------
+
+=== Using a Proc object with the +:if+ and :+unless+ options
+
+Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.
+
+[source, ruby]
+------------------------------------------------------------------
+class Account < ActiveRecord::Base
+ validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
+end
+------------------------------------------------------------------
+
+== Writing your own validation methods
+
+When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the +validate+, +validate_on_create+ or +validate_on_update+ methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's +errors+ collection.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ def validate_on_create
+ errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ end
+end
+------------------------------------------------------------------
+
+If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
+
+ def expiration_date_cannot_be_in_the_past
+ errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ end
+
+ def discount_cannot_be_greater_than_total_value
+ errors.add(:discount, "can't be greater than total value") unless discount <= total_value
+ end
+end
+------------------------------------------------------------------
+
+== Changelog
+
+http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
diff --git a/railties/doc/guides/source/authors.txt b/railties/doc/guides/source/authors.txt
index 8d0970e4f6..94dfc4db08 100644
--- a/railties/doc/guides/source/authors.txt
+++ b/railties/doc/guides/source/authors.txt
@@ -23,3 +23,17 @@ Cofounder of http://www.eventioz.com[Eventioz]. He has been using Rails since 20
Can be found at gmail, twitter, freenode, everywhere as miloops.
***********************************************************
+.Heiko Webers
+[[hawe]]
+***********************************************************
+Heiko Webers is the founder of http://www.bauland42.de[bauland42], a German web application security consulting and development
+company focused on Ruby on Rails. He blogs at http://www.rorsecurity.info. After 10 years of desktop application development,
+Heiko has rarely looked back.
+***********************************************************
+
+.Tore Darell
+[[toretore]]
+***********************************************************
+Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
+and unobtrusive JavaScript. His home on the internet is his blog http://tore.darell.no/[Sneaky Abstractions].
+***********************************************************
diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt
index d5b8b03669..e680b79d55 100644
--- a/railties/doc/guides/source/caching_with_rails.txt
+++ b/railties/doc/guides/source/caching_with_rails.txt
@@ -10,59 +10,65 @@ need to return to those hungry web clients in the shortest time possible.
This is an introduction to the three types of caching techniques that Rails
provides by default without the use of any third party plugins.
-To get started make sure Base.perform_caching is set to true for your
-environment.
+To get started make sure config.action_controller.perform_caching is set
+to true for your environment. This flag is normally set in the
+corresponding config/environments/*.rb and caching is disabled by default
+there for development and test, and enabled for production.
[source, ruby]
-----------------------------------------------------
-Base.perform_caching = true
+config.action_controller.perform_caching = true
-----------------------------------------------------
=== Page Caching
Page caching is a Rails mechanism which allows the request for a generated
page to be fulfilled by the webserver, without ever having to go through the
-Rails stack at all. Obviously, this is super fast. Unfortunately, it can't be
+Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
applied to every situation (such as pages that need authentication) and since
the webserver is literally just serving a file from the filesystem, cache
expiration is an issue that needs to be dealt with.
So, how do you enable this super-fast cache behavior? Simple, let's say you
-have a controller called ProductController and a 'list' action that lists all
+have a controller called ProductsController and a 'list' action that lists all
the products
[source, ruby]
-----------------------------------------------------
-class ProductController < ActionController
+class ProductsController < ActionController
- cache_page :list
+ caches_page :index
- def list; end
+ def index; end
end
-----------------------------------------------------
-The first time anyone requestsion products/list, Rails will generate a file
-called list.html and the webserver will then look for that file before it
-passes the next request for products/list to your Rails application.
+The first time anyone requests products/index, Rails will generate a file
+called index.html and the webserver will then look for that file before it
+passes the next request for products/index to your Rails application.
By default, the page cache directory is set to Rails.public_path (which is
-usually set to RAILS_ROOT + "/public") and this can be configured by changing
-the configuration setting Base.cache_public_directory
-
-The page caching mechanism will automatically add a .html exxtension to
+usually set to RAILS_ROOT + "/public") and this can be configured by
+changing the configuration setting ActionController::Base.page_cache_directory. Changing the
+default from /public helps avoid naming conflicts, since you may want to
+put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the
+cached files from.
+
+The Page Caching mechanism will automatically add a .html exxtension to
requests for pages that do not have an extension to make it easy for the
webserver to find those pages and this can be configured by changing the
-configuration setting Base.page_cache_extension
+configuration setting ActionController::Base.page_cache_extension.
In order to expire this page when a new product is added we could extend our
example controler like this:
[source, ruby]
-----------------------------------------------------
-class ProductController < ActionController
+class ProductsController < ActionController
- cache_page :list
+ caches_page :list
def list; end
@@ -80,11 +86,11 @@ to expire cached objects when things change. This is covered in the section on S
=== Action Caching
-One of the issues with page caching is that you cannot use it for pages that
+One of the issues with Page Caching is that you cannot use it for pages that
require to restrict access somehow. This is where Action Caching comes in.
Action Caching works like Page Caching except for the fact that the incoming
web request does go from the webserver to the Rails stack and Action Pack so
-that before_filters can be run on it before the cache is served, so that
+that before filters can be run on it before the cache is served, so that
authentication and other restrictions can be used while still serving the
result of the output from a cached copy.
@@ -95,10 +101,10 @@ object, but still cache those pages:
[source, ruby]
-----------------------------------------------------
-class ProductController < ActionController
+class ProductsController < ActionController
before_filter :authenticate, :only => [ :edit, :create ]
- cache_page :list
+ caches_page :list
caches_action :edit
def list; end
@@ -120,7 +126,7 @@ or the number of items in the cart can be left uncached. This feature is
available as of Rails 2.2.
-[More: more examples? Walk-through of action caching from request to response?
+[More: more examples? Walk-through of Action Caching from request to response?
Description of Rake tasks to clear cached files? Show example of
subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
to expire_action?]
@@ -132,15 +138,15 @@ a page or action and serving it out to the world. Unfortunately, dynamic web
applications usually build pages with a variety of components not all of which
have the same caching characteristics. In order to address such a dynamically
created page where different parts of the page need to be cached and expired
-differently Rails provides a mechanism called Fragment caching.
+differently Rails provides a mechanism called Fragment Caching.
-Fragment caching allows a fragment of view logic to be wrapped in a cache
+Fragment Caching allows a fragment of view logic to be wrapped in a cache
block and served out of the cache store when the next request comes in.
-As an example, if you wanted to show all the orders placed on your website in
-real time and didn't want to cache that part of the page, but did want to
-cache the part of the page which lists all products available, you could use
-this piece of code:
+As an example, if you wanted to show all the orders placed on your website
+in real time and didn't want to cache that part of the page, but did want
+to cache the part of the page which lists all products available, you
+could use this piece of code:
[source, ruby]
-----------------------------------------------------
@@ -158,7 +164,7 @@ this piece of code:
The cache block in our example will bind to the action that called it and is
written out to the same place as the Action Cache, which means that if you
-want to cache multiple fragments per action, you should provide an action_path to the cache call:
+want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
[source, ruby]
-----------------------------------------------------
@@ -225,10 +231,10 @@ following:
[source, ruby]
-----------------------------------------------------
-class ProductController < ActionController
+class ProductsController < ActionController
before_filter :authenticate, :only => [ :edit, :create ]
- cache_page :list
+ caches_page :list
caches_action :edit
cache_sweeper :store_sweeper, :only => [ :create ]
@@ -257,10 +263,10 @@ For example:
[source, ruby]
-----------------------------------------------------
-class ProductController < ActionController
+class ProductsController < ActionController
before_filter :authenticate, :only => [ :edit, :create ]
- cache_page :list
+ caches_page :list
caches_action :edit
cache_sweeper :store_sweeper, :only => [ :create ]
diff --git a/railties/doc/guides/source/command_line.txt b/railties/doc/guides/source/command_line.txt
new file mode 100644
index 0000000000..5f7c6ceff5
--- /dev/null
+++ b/railties/doc/guides/source/command_line.txt
@@ -0,0 +1,147 @@
+A Guide to The Rails Command Line
+=================================
+
+Rails comes with every command line tool you'll need to
+
+* Create a Rails application
+* Generate models, controllers, database migrations, and unit tests
+* Start a development server
+* Mess with objects through an interactive shell
+* Profile and benchmark your new creation
+
+... and much, much more! (Buy now!)
+
+This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
+
+== Command Line Basics ==
+
+There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
+
+* console
+* server
+* rake
+* generate
+* rails
+
+Let's create a simple Rails application to step through each of these commands in context.
+
+=== rails ===
+
+The first thing we'll want to do is create a new Rails application by running the `rails` command after installing Rails.
+
+NOTE: You know you need the rails gem installed by typing `gem install rails` first, right? Okay, okay, just making sure.
+
+[source,shell]
+------------------------------------------------------
+$ rails commandsapp
+
+ create
+ create app/controllers
+ create app/helpers
+ create app/models
+ ...
+ ...
+ create log/production.log
+ create log/development.log
+ create log/test.log
+------------------------------------------------------
+
+Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
+
+NOTE: This output will seem very familiar when we get to the `generate` command. Creepy foreshadowing!
+
+=== server ===
+
+Let's try it! The `server` command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.
+
+NOTE: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
+
+Here we'll flex our `server` command, which without any prodding of any kind will run our new shiny Rails app:
+
+[source,shell]
+------------------------------------------------------
+$ cd commandsapp
+$ ./script/server
+=> Booting WEBrick...
+=> Rails 2.2.0 application started on http://0.0.0.0:3000
+=> Ctrl-C to shutdown server; call with --help for options
+[2008-11-04 10:11:38] INFO WEBrick 1.3.1
+[2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux]
+[2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
+------------------------------------------------------
+
+WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait.
+
+See? Cool! It doesn't do much yet, but we'll change that.
+
+=== generate ===
+
+The `generate` command uses templates to create a whole lot of things. You can always find out what's available by running `generate` by itself. Let's do that:
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate
+Usage: ./script/generate generator [options] [args]
+
+...
+...
+
+Installed Generators
+ Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration
+
+...
+...
+------------------------------------------------------
+
+NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
+
+Using generators will save you a large amount of time by writing *boilerplate code* for you -- necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?
+
+Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
+
+NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller
+Usage: ./script/generate controller ControllerName [options]
+
+...
+...
+
+Example:
+ `./script/generate controller CreditCard open debit credit close`
+
+ Credit card controller with URLs like /credit_card/debit.
+ Controller: app/controllers/credit_card_controller.rb
+ Views: app/views/credit_card/debit.html.erb [...]
+ Helper: app/helpers/credit_card_helper.rb
+ Test: test/functional/credit_card_controller_test.rb
+
+Modules Example:
+ `./script/generate controller 'admin/credit_card' suspend late_fee`
+
+ Credit card admin controller with URLs /admin/credit_card/suspend.
+ Controller: app/controllers/admin/credit_card_controller.rb
+ Views: app/views/admin/credit_card/debit.html.erb [...]
+ Helper: app/helpers/admin/credit_card_helper.rb
+ Test: test/functional/admin/credit_card_controller_test.rb
+------------------------------------------------------
+
+Ah, the controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of *hello*, which will say something nice to us.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller Greeting hello
+ exists app/controllers/
+ exists app/helpers/
+ create app/views/greeting
+ exists test/functional/
+ create app/controllers/greetings_controller.rb
+ create test/functional/greetings_controller_test.rb
+ create app/helpers/greetings_helper.rb
+ create app/views/greetings/hello.html.erb
+------------------------------------------------------
+
+Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!
+
diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt
new file mode 100644
index 0000000000..07b630c59d
--- /dev/null
+++ b/railties/doc/guides/source/configuring.txt
@@ -0,0 +1,225 @@
+Configuring Rails Applications
+==============================
+
+This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to:
+
+* Adjust the behavior of your Rails applications
+* Add additional code to be run at application start time
+
+== Locations for Initialization Code
+
+preinitializers
+environment.rb first
+env-specific files
+initializers (load_application_initializers)
+after-initializer
+
+== Using a Preinitializer
+
+== Configuring Rails Components
+
+=== Configuring Active Record
+
+=== Configuring Action Controller
+
+=== Configuring Action View
+
+=== Configuring Action Mailer
+
+=== Configuring Active Resource
+
+=== Configuring Active Support
+
+== Using Initializers
+ organization, controlling load order
+
+== Using an After-Initializer
+
+== Changelog ==
+
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket]
+
+* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy]
+
+
+actionmailer/lib/action_mailer/base.rb
+257: cattr_accessor :logger
+267: cattr_accessor :smtp_settings
+273: cattr_accessor :sendmail_settings
+276: cattr_accessor :raise_delivery_errors
+282: cattr_accessor :perform_deliveries
+285: cattr_accessor :deliveries
+288: cattr_accessor :default_charset
+291: cattr_accessor :default_content_type
+294: cattr_accessor :default_mime_version
+297: cattr_accessor :default_implicit_parts_order
+299: cattr_reader :protected_instance_variables
+
+actionmailer/Rakefile
+36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+actionpack/lib/action_controller/base.rb
+263: cattr_reader :protected_instance_variables
+273: cattr_accessor :asset_host
+279: cattr_accessor :consider_all_requests_local
+285: cattr_accessor :allow_concurrency
+317: cattr_accessor :param_parsers
+321: cattr_accessor :default_charset
+325: cattr_accessor :logger
+329: cattr_accessor :resource_action_separator
+333: cattr_accessor :resources_path_names
+337: cattr_accessor :request_forgery_protection_token
+341: cattr_accessor :optimise_named_routes
+351: cattr_accessor :use_accept_header
+361: cattr_accessor :relative_url_root
+
+actionpack/lib/action_controller/caching/pages.rb
+55: cattr_accessor :page_cache_directory
+58: cattr_accessor :page_cache_extension
+
+actionpack/lib/action_controller/caching.rb
+37: cattr_reader :cache_store
+48: cattr_accessor :perform_caching
+
+actionpack/lib/action_controller/dispatcher.rb
+98: cattr_accessor :error_file_path
+
+actionpack/lib/action_controller/mime_type.rb
+24: cattr_reader :html_types, :unverifiable_types
+
+actionpack/lib/action_controller/rescue.rb
+36: base.cattr_accessor :rescue_responses
+40: base.cattr_accessor :rescue_templates
+
+actionpack/lib/action_controller/session/active_record_store.rb
+60: cattr_accessor :data_column_name
+170: cattr_accessor :connection
+173: cattr_accessor :table_name
+177: cattr_accessor :session_id_column
+181: cattr_accessor :data_column
+282: cattr_accessor :session_class
+
+actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+44: cattr_accessor :included_tags, :instance_writer => false
+
+actionpack/lib/action_view/base.rb
+189: cattr_accessor :debug_rjs
+193: cattr_accessor :warn_cache_misses
+
+actionpack/lib/action_view/helpers/active_record_helper.rb
+7: cattr_accessor :field_error_proc
+
+actionpack/lib/action_view/helpers/form_helper.rb
+805: cattr_accessor :default_form_builder
+
+actionpack/lib/action_view/template_handlers/erb.rb
+47: cattr_accessor :erb_trim_mode
+
+actionpack/test/active_record_unit.rb
+5: cattr_accessor :able_to_connect
+6: cattr_accessor :connected
+
+actionpack/test/controller/filters_test.rb
+286: cattr_accessor :execution_log
+
+actionpack/test/template/form_options_helper_test.rb
+3:TZInfo::Timezone.cattr_reader :loaded_zones
+
+activemodel/lib/active_model/errors.rb
+28: cattr_accessor :default_error_messages
+
+activemodel/Rakefile
+19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+activerecord/lib/active_record/attribute_methods.rb
+9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
+11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false
+
+activerecord/lib/active_record/base.rb
+394: cattr_accessor :logger, :instance_writer => false
+443: cattr_accessor :configurations, :instance_writer => false
+450: cattr_accessor :primary_key_prefix_type, :instance_writer => false
+456: cattr_accessor :table_name_prefix, :instance_writer => false
+461: cattr_accessor :table_name_suffix, :instance_writer => false
+467: cattr_accessor :pluralize_table_names, :instance_writer => false
+473: cattr_accessor :colorize_logging, :instance_writer => false
+478: cattr_accessor :default_timezone, :instance_writer => false
+487: cattr_accessor :schema_format , :instance_writer => false
+491: cattr_accessor :timestamped_migrations , :instance_writer => false
+
+activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
+11: cattr_accessor :connection_handler, :instance_writer => false
+
+activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+166: cattr_accessor :emulate_booleans
+
+activerecord/lib/active_record/fixtures.rb
+498: cattr_accessor :all_loaded_fixtures
+
+activerecord/lib/active_record/locking/optimistic.rb
+38: base.cattr_accessor :lock_optimistically, :instance_writer => false
+
+activerecord/lib/active_record/migration.rb
+259: cattr_accessor :verbose
+
+activerecord/lib/active_record/schema_dumper.rb
+13: cattr_accessor :ignore_tables
+
+activerecord/lib/active_record/serializers/json_serializer.rb
+4: base.cattr_accessor :include_root_in_json, :instance_writer => false
+
+activerecord/Rakefile
+142: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+activerecord/test/cases/lifecycle_test.rb
+61: cattr_reader :last_inherited
+
+activerecord/test/cases/mixin_test.rb
+9: cattr_accessor :forced_now_time
+
+activeresource/lib/active_resource/base.rb
+206: cattr_accessor :logger
+
+activeresource/Rakefile
+43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+activesupport/lib/active_support/buffered_logger.rb
+17: cattr_accessor :silencer
+
+activesupport/lib/active_support/cache.rb
+81: cattr_accessor :logger
+
+activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
+5:# cattr_accessor :hair_colors
+10: def cattr_reader(*syms)
+29: def cattr_writer(*syms)
+50: def cattr_accessor(*syms)
+51: cattr_reader(*syms)
+52: cattr_writer(*syms)
+
+activesupport/lib/active_support/core_ext/logger.rb
+34: cattr_accessor :silencer
+
+activesupport/test/core_ext/class/attribute_accessor_test.rb
+6: cattr_accessor :foo
+7: cattr_accessor :bar, :instance_writer => false
+
+activesupport/test/core_ext/module/synchronization_test.rb
+6: @target.cattr_accessor :mutex, :instance_writer => false
+
+railties/doc/guides/html/creating_plugins.html
+786: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
+860: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
+
+railties/lib/rails_generator/base.rb
+93: cattr_accessor :logger
+
+railties/Rakefile
+265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object'
+
+railties/test/rails_info_controller_test.rb
+12: cattr_accessor :local_request
+
+Rakefile
+32: rdoc.options << '-A cattr_accessor=object'
+
diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
index 12d40deb18..de116af7db 100644
--- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
+++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
@@ -1,32 +1,40 @@
-== Add an `acts_as_yaffle` method to ActiveRecord ==
+== Add an `acts_as_yaffle` method to Active Record ==
-A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a `squawk` method to your models.
+A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
-To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper.
+To begin, set up your files so that you have:
+
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
require File.dirname(__FILE__) + '/test_helper.rb'
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle
-end
-
class ActsAsYaffleTest < Test::Unit::TestCase
end
------------------------------------------------------
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/lib/acts_as_yaffle.rb
+require 'yaffle/acts_as_yaffle'
+------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+[source, ruby]
+------------------------------------------------------
module Yaffle
+ # your code will go here
end
------------------------------------------------------
-One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
+Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.
+
+One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so:
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
@@ -50,52 +58,45 @@ end
With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`).
-Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
+=== Add a class method ===
-Back in your `acts_as_yaffle` file, update ClassMethods like so:
+This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
-[source, ruby]
-------------------------------------------------------
-module ClassMethods
- def acts_as_yaffle(options = {})
- send :include, InstanceMethods
- end
-end
-------------------------------------------------------
+To start out, write a failing test that shows the behavior you'd like:
-Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
require File.dirname(__FILE__) + '/test_helper.rb'
+class Hickwall < ActiveRecord::Base
+ acts_as_yaffle
+end
+
+class Wickwall < ActiveRecord::Base
+ acts_as_yaffle :yaffle_text_field => :last_tweet
+end
+
class ActsAsYaffleTest < Test::Unit::TestCase
+ load_schema
+
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
-
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
-
- def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
end
------------------------------------------------------
To make these tests pass, you could modify your `acts_as_yaffle` file like so:
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
@@ -103,70 +104,66 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
+ cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
- send :include, InstanceMethods
end
end
-
- module InstanceMethods
- end
end
+
+ActiveRecord::Base.send :include, Yaffle
------------------------------------------------------
-Now you can add tests for the instance methods, and the instance method itself:
+=== Add an instance method ===
+
+This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
+
+To start out, write a failing test that shows the behavior you'd like:
+
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
require File.dirname(__FILE__) + '/test_helper.rb'
+class Hickwall < ActiveRecord::Base
+ acts_as_yaffle
+end
+
+class Wickwall < ActiveRecord::Base
+ acts_as_yaffle :yaffle_text_field => :last_tweet
+end
+
class ActsAsYaffleTest < Test::Unit::TestCase
+ load_schema
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
- def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
- def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
-
+
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
- end
- def test_hickwalls_squawk_should_populate_last_squawked_at
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal Date.today, hickwall.last_squawked_at
- end
-
- def test_wickwalls_squawk_should_populate_last_tweet
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", wickwall.last_tweet
- end
+ end
+
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
- assert_equal Date.today, wickwall.last_tweeted_at
- end
+ assert_equal "squawk! Hello World", wickwall.last_tweet
+ end
end
------------------------------------------------------
+Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this:
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
@@ -174,9 +171,8 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
+ cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
@@ -184,10 +180,12 @@ module Yaffle
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
- write_attribute(self.class.yaffle_date_field, Date.today)
end
end
end
+
+ActiveRecord::Base.send :include, Yaffle
------------------------------------------------------
-Note the use of `write_attribute` to write to the field in model.
+.Editor's note:
+NOTE: The use of `write_attribute` to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use `send("#{self.class.yaffle_text_field}=", string.to_squawk)`.
diff --git a/railties/doc/guides/source/creating_plugins/basics.markdown b/railties/doc/guides/source/creating_plugins/basics.markdown
deleted file mode 100644
index f59e8728d7..0000000000
--- a/railties/doc/guides/source/creating_plugins/basics.markdown
+++ /dev/null
@@ -1,861 +0,0 @@
-Creating Plugin Basics
-====================
-
-Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness.
-
-In this tutorial you will learn how to create a plugin that includes:
-
-Core Extensions - extending String:
-
- # Anywhere
- "hello".squawk # => "squawk! hello! squawk!"
-
-An `acts_as_yaffle` method for Active Record models that adds a "squawk" method:
-
- class Hickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_sang_at
- end
-
- Hickwall.new.squawk("Hello World")
-
-A view helper that will print out squawking info:
-
- squawk_info_for(@hickwall)
-
-A generator that creates a migration to add squawk columns to a model:
-
- script/generate yaffle hickwall
-
-A custom generator command:
-
- class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
- end
- end
-
-A custom route method:
-
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- end
-
-In addition you'll learn how to:
-
-* test your plugins
-* work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins
-* create documentation for your plugin.
-* write custom rake tasks in your plugin
-
-Create the basic app
----------------------
-
-In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:
-
-> The following instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
-
- rails plugin_demo
- cd plugin_demo
- script/generate scaffold bird name:string
- rake db:migrate
- script/server
-
-Then navigate to [http://localhost:3000/birds](http://localhost:3000/birds). Make sure you have a functioning rails app before continuing.
-
-Create the plugin
------------------------
-
-The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also.
-
-This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories.
-
-Examples:
-
- ./script/generate plugin BrowserFilters
- ./script/generate plugin BrowserFilters --with-generator
-
-Later in the plugin we will create a generator, so go ahead and add the --with-generator option now:
-
- script/generate plugin yaffle --with-generator
-
-You should see the following output:
-
- create vendor/plugins/yaffle/lib
- create vendor/plugins/yaffle/tasks
- create vendor/plugins/yaffle/test
- create vendor/plugins/yaffle/README
- create vendor/plugins/yaffle/MIT-LICENSE
- create vendor/plugins/yaffle/Rakefile
- create vendor/plugins/yaffle/init.rb
- create vendor/plugins/yaffle/install.rb
- create vendor/plugins/yaffle/uninstall.rb
- create vendor/plugins/yaffle/lib/yaffle.rb
- create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
- create vendor/plugins/yaffle/test/core_ext_test.rb
- create vendor/plugins/yaffle/generators
- create vendor/plugins/yaffle/generators/yaffle
- create vendor/plugins/yaffle/generators/yaffle/templates
- create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
- create vendor/plugins/yaffle/generators/yaffle/USAGE
-
-For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that.
-
- rm vendor/plugins/yaffle/lib/yaffle.rb
-
-> Editor's note: many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`
-> If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean
-
-Setup the plugin for testing
-------------------------
-
-Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.
-
-To setup your plugin to allow for easy testing you'll need to add 3 files:
-
-* A database.yml file with all of your connection strings
-* A schema.rb file with your table definitions
-* A test helper that sets up the database before your tests
-
-For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
-
- # File: vendor/plugins/yaffle/test/database.yml
-
- sqlite:
- :adapter: sqlite
- :dbfile: yaffle_plugin.sqlite.db
- sqlite3:
- :adapter: sqlite3
- :dbfile: yaffle_plugin.sqlite3.db
- postgresql:
- :adapter: postgresql
- :username: postgres
- :password: postgres
- :database: yaffle_plugin_test
- :min_messages: ERROR
- mysql:
- :adapter: mysql
- :host: localhost
- :username: rails
- :password:
- :database: yaffle_plugin_test
-
- # File: vendor/plugins/yaffle/test/test_helper.rb
-
- ActiveRecord::Schema.define(:version => 0) do
- create_table :hickwalls, :force => true do |t|
- t.string :name
- t.string :last_squawk
- t.datetime :last_squawked_at
- end
- create_table :wickwalls, :force => true do |t|
- t.string :name
- t.string :last_tweet
- t.datetime :last_tweeted_at
- end
- end
-
- # File: vendor/plugins/yaffle/test/test_helper.rb
-
- ENV['RAILS_ENV'] = 'test'
- ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
-
- require 'test/unit'
- require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
-
- config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
- ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
-
- db_adapter = ENV['DB']
-
- # no db passed, try one of these fine config-free DBs before bombing.
- db_adapter ||=
- begin
- require 'rubygems'
- require 'sqlite'
- 'sqlite'
- rescue MissingSourceFile
- begin
- require 'sqlite3'
- 'sqlite3'
- rescue MissingSourceFile
- end
- end
-
- if db_adapter.nil?
- raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
- end
-
- ActiveRecord::Base.establish_connection(config[db_adapter])
-
- load(File.dirname(__FILE__) + "/schema.rb")
-
- require File.dirname(__FILE__) + '/../init.rb'
-
- class Hickwall < ActiveRecord::Base
- acts_as_yaffle
- end
-
- class Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
- end
-
-Add a `to_squawk` method to String
------------------------
-
-To update a core class you will have to:
-
-* Write tests for the desired functionality
-* Create a file for the code you wish to use
-* Require that file from your init.rb
-
-Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is `lib/core_ext.rb`
-
-First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
-
- # File: vendor/plugins/yaffle/test/core_ext_test.rb
-
- require 'test/unit'
-
- class CoreExtTest < Test::Unit::TestCase
- # Replace this with your real tests.
- def test_this_plugin
- flunk
- end
- end
-
-Start off by removing the default test, and adding a require statement for your test helper.
-
- # File: vendor/plugins/yaffle/test/core_ext_test.rb
-
- require 'test/unit'
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class CoreExtTest < Test::Unit::TestCase
- end
-
-Navigate to your plugin directory and run `rake test`
-
- cd vendor/plugins/yaffle
- rake test
-
-Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file `lib/core_ext.rb` and re-run the tests. You should see a different error message:
-
- 1.) Failure ...
- No tests were specified
-
-Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word "squawk! ". The test will look something like this:
-
- # File: vendor/plugins/yaffle/init.rb
-
- class CoreExtTest < Test::Unit::TestCase
- def test_string_should_respond_to_squawk
- assert_equal true, "".respond_to?(:to_squawk)
- end
- def test_string_prepend_empty_strings_with_the_word_squawk
- assert_equal "squawk!", "".to_squawk
- end
- def test_string_prepend_non_empty_strings_with_the_word_squawk
- assert_equal "squawk! Hello World", "Hello World".to_squawk
- end
- end
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "core_ext"
-
- # File: vendor/plugins/yaffle/lib/core_ext.rb
-
- String.class_eval do
- def to_squawk
- "squawk! #{self}".strip
- end
- end
-
-When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly.
-
-To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:
-
- script/console
- >> "Hello World".to_squawk
- => "squawk! Hello World"
-
-If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.
-
-Add an `acts_as_yaffle` method to ActiveRecord
------------------------
-
-A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a squawk method to your models.
-
-To keep things clean, create a new test file called `acts_as_yaffle_test.rb` in your plugin's test directory and require your test helper.
-
- # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class Hickwall < ActiveRecord::Base
- acts_as_yaffle
- end
-
- class ActsAsYaffleTest < Test::Unit::TestCase
- end
-
- # File: vendor/plugins/lib/acts_as_yaffle.rb
-
- module Yaffle
- end
-
-One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
-
- module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
-
- module ClassMethods
- # any method placed here will apply to classes, like Hickwall
- def acts_as_something
- send :include, InstanceMethods
- end
- end
-
- module InstanceMethods
- # any method placed here will apply to instaces, like @hickwall
- end
- end
-
-With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`).
-
-Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
-
-Back in your `acts_as_yaffle` file, update ClassMethods like so:
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- send :include, InstanceMethods
- end
- end
-
-Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
-
- # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class ActsAsYaffleTest < Test::Unit::TestCase
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_squawk", Hickwall.yaffle_text_field
- end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
- def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
- assert_equal "last_tweet", Wickwall.yaffle_text_field
- end
- def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
- end
-
-To make these tests pass, you could modify your `acts_as_yaffle` file like so:
-
- # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
- module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
- send :include, InstanceMethods
- end
- end
-
- module InstanceMethods
- end
- end
-
-Now you can add tests for the instance methods, and the instance method itself:
-
- # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class ActsAsYaffleTest < Test::Unit::TestCase
-
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_squawk", Hickwall.yaffle_text_field
- end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
-
- def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_tweet", Wickwall.yaffle_text_field
- end
- def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
-
- def test_hickwalls_squawk_should_populate_last_squawk
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", hickwall.last_squawk
- end
- def test_hickwalls_squawk_should_populate_last_squawked_at
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal Date.today, hickwall.last_squawked_at
- end
-
- def test_wickwalls_squawk_should_populate_last_tweet
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", wickwall.last_tweet
- end
- def test_wickwalls_squawk_should_populate_last_tweeted_at
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal Date.today, wickwall.last_tweeted_at
- end
- end
-
- # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
- module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
- send :include, InstanceMethods
- end
- end
-
- module InstanceMethods
- def squawk(string)
- write_attribute(self.class.yaffle_text_field, string.to_squawk)
- write_attribute(self.class.yaffle_date_field, Date.today)
- end
- end
- end
-
-Note the use of write_attribute to write to the field in model.
-
-Create a view helper
------------------------
-
-Creating a view helper is a 3-step process:
-
-* Add an appropriately named file to the lib directory
-* Require the file and hooks in init.rb
-* Write the tests
-
-First, create the test to define the functionality you want:
-
- # File: vendor/plugins/yaffle/test/view_helpers_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
- include YaffleViewHelper
-
- class ViewHelpersTest < Test::Unit::TestCase
- def test_squawk_info_for_should_return_the_text_and_date
- time = Time.now
- hickwall = Hickwall.new
- hickwall.last_squawk = "Hello World"
- hickwall.last_squawked_at = time
- assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
- end
- end
-
-Then add the following statements to init.rb:
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "view_helpers"
- ActionView::Base.send :include, YaffleViewHelper
-
-Then add the view helpers file and
-
- # File: vendor/plugins/yaffle/lib/view_helpers.rb
-
- module YaffleViewHelper
- def squawk_info_for(yaffle)
- returning "" do |result|
- result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
- result << ", "
- result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s
- end
- end
- end
-
-You can also test this in script/console by using the "helper" method:
-
- script/console
- >> helper.squawk_info_for(@some_yaffle_instance)
-
-Create a migration generator
------------------------
-
-When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin.
-
-We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.
-
-Type:
-
- script/generate
-
-You should see the line:
-
- Plugins (vendor/plugins): yaffle
-
-When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
-
- Description:
- Creates a migration that adds yaffle squawk fields to the given model
-
- Example:
- ./script/generate yaffle hickwall
-
- This will create:
- db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
-
-Now you can add code to your generator:
-
- # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
- class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- record do |m|
- m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
- :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
- }
- end
- end
-
- private
- def custom_file_name
- custom_name = class_name.underscore.downcase
- custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
- end
-
- def yaffle_local_assigns
- returning(assigns = {}) do
- assigns[:migration_action] = "add"
- assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
- assigns[:table_name] = custom_file_name
- assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
- assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
- end
- end
- end
-
-Note that you need to be aware of whether or not table names are pluralized.
-
-This does a few things:
-
-* Reuses the built in rails migration_template method
-* Reuses the built-in rails migration template
-
-When you run the generator like
-
- script/generate yaffle bird
-
-You will see a new file:
-
- # File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
-
- class AddYaffleFieldsToBirds < ActiveRecord::Migration
- def self.up
- add_column :birds, :last_squawk, :string
- add_column :birds, :last_squawked_at, :datetime
- end
-
- def self.down
- remove_column :birds, :last_squawked_at
- remove_column :birds, :last_squawk
- end
- end
-
-Add a custom generator command
-------------------------
-
-You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps:
-
-1. Add the require and hook statements to init.rb
-2. Create the commands - creating 3 sets, Create, Destroy, List
-3. Add the method to your generator
-
-Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "commands"
- Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
- Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
- Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
-
- # File: vendor/plugins/yaffle/lib/commands.rb
-
- require 'rails_generator'
- require 'rails_generator/commands'
-
- module Yaffle #:nodoc:
- module Generator #:nodoc:
- module Commands #:nodoc:
- module Create
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module Destroy
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module List
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
- end
- end
- end
-
- # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
-
- Yaffle is a bird
-
- # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
- class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
- end
- end
-
-This example just uses the built-in "file" method, but you could do anything that ruby allows.
-
-Add a Custom Route
-------------------------
-
-Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in [http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2](http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2)
-
- # File: vendor/plugins/yaffle/test/routing_test.rb
-
- require "#{File.dirname(__FILE__)}/test_helper"
-
- class RoutingTest < Test::Unit::TestCase
-
- def setup
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- end
- end
-
- def test_yaffles_route
- assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
- end
-
- private
-
- # yes, I know about assert_recognizes, but it has proven problematic to
- # use in these tests, since it uses RouteSet#recognize (which actually
- # tries to instantiate the controller) and because it uses an awkward
- # parameter order.
- def assert_recognition(method, path, options)
- result = ActionController::Routing::Routes.recognize_path(path, :method => method)
- assert_equal options, result
- end
- end
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "routing"
- ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
-
- # File: vendor/plugins/yaffle/lib/routing.rb
-
- module Yaffle #:nodoc:
- module Routing #:nodoc:
- module MapperExtensions
- def yaffles
- @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
- end
- end
- end
- end
-
- # File: config/routes.rb
-
- ActionController::Routing::Routes.draw do |map|
- ...
- map.yaffles
- end
-
-You can also see if your routes work by running `rake routes` from your app directory.
-
-Generate RDoc Documentation
------------------------
-
-Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
-
-The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
-
-* Your name
-* How to install
-* How to add the functionality to the app (several examples of common use cases)
-* Warning, gotchas or tips that might help save users time
-
-Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.
-
-Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.
-
-Once your comments are good to go, navigate to your plugin directory and run
-
- rake rdoc
-
-Work with init.rb
-------------------------
-
-The plugin initializer script init.rb is invoked via `eval` (not require) so it has slightly different behavior.
-
-If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:
-
-The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash
-
- # File: vendor/plugins/yaffle/init.rb
-
- class ::Hash
- def is_a_special_hash?
- true
- end
- end
-
-OR you can use `module_eval` or `class_eval`
-
- # File: vendor/plugins/yaffle/init.rb
-
- Hash.class_eval do
- def is_a_special_hash?
- true
- end
- end
-
-Store models, views, helpers, and controllers in your plugins
-------------------------
-
-You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:
-
- # File: vendor/plugins/yaffle/init.rb
-
- %w{ models controllers helpers }.each do |dir|
- path = File.join(directory, 'lib', dir)
- $LOAD_PATH << path
- Dependencies.load_paths << path
- Dependencies.load_once_paths.delete(path)
- end
-
-Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser.
-
-Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.
-
-Write custom rake tasks in your plugin
--------------------------
-
-When you created the plugin with the built-in rails generator, it generated a rake file for you in `vendor/plugins/yaffle/tasks/yaffle.rake`. Any rake task you add here will be available to the app.
-
-Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
-
- # File: vendor/plugins/yaffle/tasks/yaffle.rake
-
- namespace :yaffle do
- desc "Prints out the word 'Yaffle'"
- task :squawk => :environment do
- puts "squawk!"
- end
- end
-
-When you run `rake -T` from your plugin you will see
-
- yaffle:squawk "Prints out..."
-
-You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
-
-Store plugins in alternate locations
--------------------------
-
-You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb
-
-Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.
-
-You can even store plugins inside of other plugins for complete plugin madness!
-
- config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
-
-Create your own Plugin Loaders and Plugin Locators
-------------------------
-
-If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.
-
-Use Custom Plugin Generators
-------------------------
-
-If you are an RSpec fan, you can install the `rspec_plugin_generator`, which will generate the spec folder and database for you.
-
-[http://github.com/pat-maddox/rspec-plugin-generator/tree/master](http://github.com/pat-maddox/rspec-plugin-generator/tree/master)
-
-References
-------------------------
-
-* [http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i](http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i)
-* [http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii](http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii)
-* [http://github.com/technoweenie/attachment_fu/tree/master](http://github.com/technoweenie/attachment_fu/tree/master)
-* [http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html](http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html)
-
-Appendices
-------------------------
-
-The final plugin should have a directory structure that looks something like this:
-
- |-- MIT-LICENSE
- |-- README
- |-- Rakefile
- |-- generators
- | `-- yaffle
- | |-- USAGE
- | |-- templates
- | | `-- definition.txt
- | `-- yaffle_generator.rb
- |-- init.rb
- |-- install.rb
- |-- lib
- | |-- acts_as_yaffle.rb
- | |-- commands.rb
- | |-- core_ext.rb
- | |-- routing.rb
- | `-- view_helpers.rb
- |-- tasks
- | `-- yaffle_tasks.rake
- |-- test
- | |-- acts_as_yaffle_test.rb
- | |-- core_ext_test.rb
- | |-- database.yml
- | |-- debug.log
- | |-- routing_test.rb
- | |-- schema.rb
- | |-- test_helper.rb
- | `-- view_helpers_test.rb
- |-- uninstall.rb
- `-- yaffle_plugin.sqlite3.db
diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt
new file mode 100644
index 0000000000..ee408adb1d
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/controllers.txt
@@ -0,0 +1,59 @@
+== Add a controller ==
+
+This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
+
+You can test your plugin's controller as you would test any other controller:
+
+*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'woodpeckers_controller'
+require 'action_controller/test_process'
+
+class WoodpeckersController; def rescue_action(e) raise e end; end
+
+class WoodpeckersControllerTest < Test::Unit::TestCase
+ def setup
+ @controller = WoodpeckersController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_index
+ get :index
+ assert_response :success
+ end
+end
+----------------------------------------------
+
+This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models controllers }.each do |dir|
+ path = File.join(File.dirname(__FILE__), 'app', dir)
+ $LOAD_PATH << path
+ ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_once_paths.delete(path)
+end
+----------------------------------------------
+
+
+*vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:*
+
+[source, ruby]
+----------------------------------------------
+class WoodpeckersController < ActionController::Base
+
+ def index
+ render :text => "Squawk!"
+ end
+
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt
new file mode 100644
index 0000000000..ca8efc3df1
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/core_ext.txt
@@ -0,0 +1,123 @@
+== Extending core classes ==
+
+This section will explain how to add a method to String that will be available anywhere in your rails app by:
+
+ * Writing tests for the desired behavior
+ * Creating and requiring the correct files
+
+=== Creating the test ===
+
+In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions:
+
+*vendor/plugins/yaffle/test/core_ext_test.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class CoreExtTest < Test::Unit::TestCase
+ def test_to_squawk_prepends_the_word_squawk
+ assert_equal "squawk! Hello World", "Hello World".to_squawk
+ end
+end
+--------------------------------------------------------
+
+Navigate to your plugin directory and run `rake test`:
+
+--------------------------------------------------------
+cd vendor/plugins/yaffle
+rake test
+--------------------------------------------------------
+
+The test above should fail with the message:
+
+--------------------------------------------------------
+ 1) Error:
+test_to_squawk_prepends_the_word_squawk(CoreExtTest):
+NoMethodError: undefined method `to_squawk' for "Hello World":String
+ ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
+--------------------------------------------------------
+
+Great - now you are ready to start development.
+
+=== Organize your files ===
+
+A common pattern in rails plugins is to set up the file structure like this:
+
+--------------------------------------------------------
+|-- lib
+| |-- yaffle
+| | `-- core_ext.rb
+| `-- yaffle.rb
+--------------------------------------------------------
+
+The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb':
+
+*vendor/plugins/yaffle/rails/init.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require 'yaffle'
+--------------------------------------------------------
+
+Then in 'lib/yaffle.rb' require 'lib/core_ext.rb':
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require "yaffle/core_ext"
+--------------------------------------------------------
+
+Finally, create the 'core_ext.rb' file and add the 'to_squawk' method:
+
+*vendor/plugins/yaffle/lib/yaffle/core_ext.rb*
+
+[source, ruby]
+--------------------------------------------------------
+String.class_eval do
+ def to_squawk
+ "squawk! #{self}".strip
+ end
+end
+--------------------------------------------------------
+
+To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory. To see this in action, fire up a console and start squawking:
+
+--------------------------------------------------------
+$ ./script/console
+>> "Hello World".to_squawk
+=> "squawk! Hello World"
+--------------------------------------------------------
+
+=== Working with init.rb ===
+
+When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
+
+Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above.
+
+If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues:
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+Hash.class_eval do
+ def is_a_special_hash?
+ true
+ end
+end
+---------------------------------------------------
+
+Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+class ::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+---------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/custom_route.txt
index 7e399247ee..1fce902a4e 100644
--- a/railties/doc/guides/source/creating_plugins/custom_route.txt
+++ b/railties/doc/guides/source/creating_plugins/custom_route.txt
@@ -2,10 +2,10 @@
Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
+*vendor/plugins/yaffle/test/routing_test.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/test/routing_test.rb
-
require "#{File.dirname(__FILE__)}/test_helper"
class RoutingTest < Test::Unit::TestCase
@@ -33,18 +33,18 @@ class RoutingTest < Test::Unit::TestCase
end
--------------------------------------------------------
+*vendor/plugins/yaffle/init.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
require "routing"
ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
--------------------------------------------------------
+*vendor/plugins/yaffle/lib/routing.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/routing.rb
-
module Yaffle #:nodoc:
module Routing #:nodoc:
module MapperExtensions
@@ -56,10 +56,10 @@ module Yaffle #:nodoc:
end
--------------------------------------------------------
+*config/routes.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: config/routes.rb
-
ActionController::Routing::Routes.draw do |map|
...
map.yaffles
diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt
new file mode 100644
index 0000000000..93f5e0ee89
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/gem.txt
@@ -0,0 +1 @@
+http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins \ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/custom_generator.txt b/railties/doc/guides/source/creating_plugins/generator_method.txt
index 6d9613ea01..126692f2c4 100644
--- a/railties/doc/guides/source/creating_plugins/custom_generator.txt
+++ b/railties/doc/guides/source/creating_plugins/generator_method.txt
@@ -1,26 +1,41 @@
== Add a custom generator command ==
-You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps:
+You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
- 1. Add the require and hook statements to init.rb.
- 2. Create the commands - creating 3 sets, Create, Destroy, List.
- 3. Add the method to your generator.
+This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
-Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
+To start, add the following test method:
+
+*vendor/plugins/yaffle/test/generator_test.rb*
[source, ruby]
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-require "commands"
-Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
-Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
-Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
+def test_generates_definition
+ Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
+ definition = File.read(File.join(fake_rails_root, "definition.txt"))
+ assert_match /Yaffle\:/, definition
+end
+-----------------------------------------------------------
+
+Run `rake` to watch the test fail, then make the test pass add the following:
+
+*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
+
-----------------------------------------------------------
+Yaffle: A bird
+-----------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
[source, ruby]
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/commands.rb
+require "yaffle/commands"
+-----------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/commands.rb*
+[source, ruby]
+-----------------------------------------------------------
require 'rails_generator'
require 'rails_generator/commands'
@@ -44,26 +59,31 @@ module Yaffle #:nodoc:
file("definition.txt", "definition.txt")
end
end
+
+ module Update
+ def yaffle_definition
+ file("definition.txt", "definition.txt")
+ end
+ end
end
end
end
------------------------------------------------------------
+Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
+Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
+Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
+Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
-Yaffle is a bird
------------------------------------------------------------
+Finally, call your new method in the manifest:
+
+*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
[source, ruby]
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
end
end
-----------------------------------------------------------
-
-This example just uses the built-in "file" method, but you could do anything that Ruby allows.
diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt
new file mode 100644
index 0000000000..51b4cebb01
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/helpers.txt
@@ -0,0 +1,51 @@
+== Add a helper ==
+
+This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
+
+You can test your plugin's helper as you would test any other helper:
+
+*vendor/plugins/yaffle/test/woodpeckers_helper_test.rb*
+
+[source, ruby]
+---------------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+include WoodpeckersHelper
+
+class WoodpeckersHelperTest < Test::Unit::TestCase
+ def test_tweet
+ assert_equal "Tweet! Hello", tweet("Hello")
+ end
+end
+---------------------------------------------------------------
+
+This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models controllers helpers }.each do |dir|
+ path = File.join(File.dirname(__FILE__), 'app', dir)
+ $LOAD_PATH << path
+ ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_once_paths.delete(path)
+end
+
+ActionView::Base.send :include, WoodpeckersHelper
+----------------------------------------------
+
+
+*vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:*
+
+[source, ruby]
+----------------------------------------------
+module WoodpeckersHelper
+
+ def tweet(text)
+ "Tweet! #{text}"
+ end
+
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index f2ed6ed8bb..19484e2830 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -1,81 +1,49 @@
The Basics of Creating Rails Plugins
====================================
-Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness.
-
-In this tutorial you will learn how to create a plugin that includes:
-
- * Core Extensions - extending String with a `to_squawk` method:
-+
-[source, ruby]
--------------------------------------------
-# Anywhere
-"hello!".to_squawk # => "squawk! hello!"
--------------------------------------------
-
-* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method:
-+
-[source, ruby]
--------------------------------------------
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_sang_at
-end
-
-Hickwall.new.squawk("Hello World")
--------------------------------------------
-
-* A view helper that will print out squawking info:
-+
-[source, ruby]
--------------------------------------------
-squawk_info_for(@hickwall)
--------------------------------------------
-
-* A generator that creates a migration to add squawk columns to a model:
-+
--------------------------------------------
-script/generate yaffle hickwall
--------------------------------------------
-
-* A custom generator command:
-+
-[source, ruby]
--------------------------------------------
-class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
--------------------------------------------
-
-* A custom route method:
-+
-[source, ruby]
--------------------------------------------
-ActionController::Routing::Routes.draw do |map|
- map.yaffles
-end
--------------------------------------------
-
-In addition you'll learn how to:
-
- * test your plugins.
- * work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins.
- * create documentation for your plugin.
- * write custom Rake tasks in your plugin.
-
-
-include::preparation.txt[]
-
-include::string_to_squawk.txt[]
+A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
+
+ * a way for developers to share bleeding-edge ideas without hurting the stable code base
+ * a segmented architecture so that units of code can be fixed or updated on their own release schedule
+ * an outlet for the core developers so that they don’t have to include every cool new feature under the sun
+
+After reading this guide you should be familiar with:
+
+ * Creating a plugin from scratch
+ * Writing and running tests for the plugin
+ * Storing models, views, controllers, helpers and even other plugins in your plugins
+ * Writing generators
+ * Writing custom Rake tasks in your plugin
+ * Generating RDoc documentation for your plugin
+ * Avoiding common pitfalls with 'init.rb'
+
+This guide describes how to build a test-driven plugin that will:
+
+ * Extend core ruby classes like Hash and String
+ * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
+ * Add a view helper that can be used in erb templates
+ * Add a new generator that will generate a migration
+ * Add a custom generator command
+ * A custom route method that can be used in routes.rb
+
+For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
-include::acts_as_yaffle.txt[]
-include::view_helper.txt[]
+include::test_setup.txt[]
+
+include::core_ext.txt[]
+
+include::acts_as_yaffle.txt[]
include::migration_generator.txt[]
-include::custom_generator.txt[]
+include::generator_method.txt[]
+
+include::models.txt[]
+
+include::controllers.txt[]
+
+include::helpers.txt[]
include::custom_route.txt[]
diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt
index 598a0c8437..f4fc32481c 100644
--- a/railties/doc/guides/source/creating_plugins/migration_generator.txt
+++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt
@@ -1,42 +1,79 @@
-== Create a migration generator ==
+== Create a generator ==
-When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin.
+Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
-We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.
+Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.
-Type:
+To create a generator you must:
- script/generate
+ * Add your instructions to the 'manifest' method of the generator
+ * Add any necessary template files to the templates directory
+ * Test the generator manually by running various combinations of `script/generate` and `script/destroy`
+ * Update the USAGE file to add helpful documentation for your generator
-You should see the line:
+=== Testing generators ===
- Plugins (vendor/plugins): yaffle
+Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
-When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
+ * Creates a new fake rails root directory that will serve as destination
+ * Runs the generator forward and backward, making whatever assertions are necessary
+ * Removes the fake rails root
+For the generator in this section, the test could look something like this:
+
+*vendor/plugins/yaffle/test/yaffle_generator_test.rb*
+
+[source, ruby]
------------------------------------------------------------------
-Description:
- Creates a migration that adds yaffle squawk fields to the given model
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+require 'rails_generator/scripts/destroy'
-Example:
- ./script/generate yaffle hickwall
+class GeneratorTest < Test::Unit::TestCase
- This will create:
- db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
+ def fake_rails_root
+ File.join(File.dirname(__FILE__), 'rails_root')
+ end
+
+ def file_list
+ Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
+ end
+
+ def setup
+ FileUtils.mkdir_p(fake_rails_root)
+ @original_files = file_list
+ end
+
+ def teardown
+ FileUtils.rm_r(fake_rails_root)
+ end
+
+ def test_generates_correct_file_name
+ Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
+ new_file = (file_list - @original_files).first
+ assert_match /add_yaffle_fields_to_bird/, new_file
+ end
+
+end
------------------------------------------------------------------
-Now you can add code to your generator:
+You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
+
+=== Adding to the manifest ===
+
+This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this:
+
+*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
[source, ruby]
------------------------------------------------------------------
-# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
:migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
- }
+ }
end
end
@@ -52,38 +89,68 @@ class YaffleGenerator < Rails::Generator::NamedBase
assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
assigns[:table_name] = custom_file_name
assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
- assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
end
end
end
------------------------------------------------------------------
-Note that you need to be aware of whether or not table names are pluralized.
+The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template.
-This does a few things:
+It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
- * Reuses the built in rails `migration_template` method.
- * Reuses the built-in rails migration template.
+=== Manually test the generator ===
-When you run the generator like
+To run the generator, type the following at the command line:
+
+------------------------------------------------------------------
+./script/generate yaffle bird
+------------------------------------------------------------------
- script/generate yaffle bird
+and you will see a new file:
-You will see a new file:
+*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
[source, ruby]
------------------------------------------------------------------
-# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
-
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
- add_column :birds, :last_squawked_at, :datetime
end
def self.down
- remove_column :birds, :last_squawked_at
remove_column :birds, :last_squawk
end
end
------------------------------------------------------------------
+
+
+=== The USAGE file ===
+
+Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
+
+------------------------------------------------------------------
+script/generate
+------------------------------------------------------------------
+
+You should see something like this:
+
+------------------------------------------------------------------
+Installed Generators
+ Plugins (vendor/plugins): yaffle
+ Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
+------------------------------------------------------------------
+
+When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file.
+
+For this plugin, update the USAGE file looks like this:
+
+------------------------------------------------------------------
+Description:
+ Creates a migration that adds yaffle squawk fields to the given model
+
+Example:
+ ./script/generate yaffle hickwall
+
+ This will create:
+ db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
+------------------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt
new file mode 100644
index 0000000000..458edec80a
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/models.txt
@@ -0,0 +1,76 @@
+== Add a model ==
+
+This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
+
+---------------------------------------------------------
+vendor/plugins/yaffle/
+|-- lib
+| |-- app
+| | |-- controllers
+| | |-- helpers
+| | |-- models
+| | | `-- woodpecker.rb
+| | `-- views
+| |-- yaffle
+| | |-- acts_as_yaffle.rb
+| | |-- commands.rb
+| | `-- core_ext.rb
+| `-- yaffle.rb
+---------------------------------------------------------
+
+As always, start with a test:
+
+*vendor/plugins/yaffle/yaffle/woodpecker_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class WoodpeckerTest < Test::Unit::TestCase
+ load_schema
+
+ def test_woodpecker
+ assert_kind_of Woodpecker, Woodpecker.new
+ end
+end
+----------------------------------------------
+
+This is just a simple test to make sure the class is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models }.each do |dir|
+ path = File.join(File.dirname(__FILE__), 'app', dir)
+ $LOAD_PATH << path
+ ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_once_paths.delete(path)
+end
+----------------------------------------------
+
+Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
+
+
+*vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
+
+[source, ruby]
+----------------------------------------------
+class Woodpecker < ActiveRecord::Base
+end
+----------------------------------------------
+
+Finally, add the following to your plugin's 'schema.rb':
+
+*vendor/plugins/yaffle/test/schema.rb:*
+
+[source, ruby]
+----------------------------------------------
+ActiveRecord::Schema.define(:version => 0) do
+ create_table :woodpeckers, :force => true do |t|
+ t.string :name
+ end
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode. \ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
index eb127f73ca..e328c04a79 100644
--- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
+++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
@@ -1,36 +1,5 @@
== Odds and ends ==
-=== Work with init.rb ===
-
-The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
-
-If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:
-
-The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
-
-[source, ruby]
----------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-class ::Hash
- def is_a_special_hash?
- true
- end
-end
----------------------------------------------------
-
-OR you can use `module_eval` or `class_eval`:
-
----------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-Hash.class_eval do
- def is_a_special_hash?
- true
- end
-end
----------------------------------------------------
-
=== Generate RDoc Documentation ===
Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
@@ -50,38 +19,16 @@ Once your comments are good to go, navigate to your plugin directory and run:
rake rdoc
-
-=== Store models, views, helpers, and controllers in your plugins ===
-
-You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:
-
-[source, ruby]
----------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-%w{ models controllers helpers }.each do |dir|
- path = File.join(directory, 'lib', dir)
- $LOAD_PATH << path
- Dependencies.load_paths << path
- Dependencies.load_once_paths.delete(path)
-end
----------------------------------------------------------
-
-Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser.
-
-Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.
-
-
=== Write custom Rake tasks in your plugin ===
When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app.
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
+*vendor/plugins/yaffle/tasks/yaffle.rake*
+
[source, ruby]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/tasks/yaffle.rake
-
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk => :environment do
diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt
deleted file mode 100644
index 77e3a3561f..0000000000
--- a/railties/doc/guides/source/creating_plugins/preparation.txt
+++ /dev/null
@@ -1,169 +0,0 @@
-== Preparation ==
-
-=== Create the basic app ===
-
-In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:
-
-------------------------------------------------
-rails plugin_demo
-cd plugin_demo
-script/generate scaffold bird name:string
-rake db:migrate
-script/server
-------------------------------------------------
-
-Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
-
-NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
-
-
-=== Create the plugin ===
-
-The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
-
-This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories.
-
-Examples:
-----------------------------------------------
-./script/generate plugin BrowserFilters
-./script/generate plugin BrowserFilters --with-generator
-----------------------------------------------
-
-Later in the plugin we will create a generator, so go ahead and add the `\--with-generator` option now:
-
-----------------------------------------------
-script/generate plugin yaffle --with-generator
-----------------------------------------------
-
-You should see the following output:
-
-----------------------------------------------
-create vendor/plugins/yaffle/lib
-create vendor/plugins/yaffle/tasks
-create vendor/plugins/yaffle/test
-create vendor/plugins/yaffle/README
-create vendor/plugins/yaffle/MIT-LICENSE
-create vendor/plugins/yaffle/Rakefile
-create vendor/plugins/yaffle/init.rb
-create vendor/plugins/yaffle/install.rb
-create vendor/plugins/yaffle/uninstall.rb
-create vendor/plugins/yaffle/lib/yaffle.rb
-create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
-create vendor/plugins/yaffle/test/core_ext_test.rb
-create vendor/plugins/yaffle/generators
-create vendor/plugins/yaffle/generators/yaffle
-create vendor/plugins/yaffle/generators/yaffle/templates
-create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-create vendor/plugins/yaffle/generators/yaffle/USAGE
-----------------------------------------------
-
-For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that.
-
-----------------------------------------------
-rm vendor/plugins/yaffle/lib/yaffle.rb
-----------------------------------------------
-
-.Editor's note:
-NOTE: Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean
-
-
-=== Setup the plugin for testing ===
-
-Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.
-
-To setup your plugin to allow for easy testing you'll need to add 3 files:
-
- * A 'database.yml' file with all of your connection strings.
- * A 'schema.rb' file with your table definitions.
- * A test helper that sets up the database before your tests.
-
-For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
-
-*vendor/plugins/yaffle/test/database.yml:*
-
-----------------------------------------------
-sqlite:
- :adapter: sqlite
- :dbfile: yaffle_plugin.sqlite.db
-
-sqlite3:
- :adapter: sqlite3
- :dbfile: yaffle_plugin.sqlite3.db
-
-postgresql:
- :adapter: postgresql
- :username: postgres
- :password: postgres
- :database: yaffle_plugin_test
- :min_messages: ERROR
-
-mysql:
- :adapter: mysql
- :host: localhost
- :username: rails
- :password:
- :database: yaffle_plugin_test
-----------------------------------------------
-
-*vendor/plugins/yaffle/test/test_helper.rb:*
-
-[source, ruby]
-----------------------------------------------
-ActiveRecord::Schema.define(:version => 0) do
- create_table :hickwalls, :force => true do |t|
- t.string :name
- t.string :last_squawk
- t.datetime :last_squawked_at
- end
- create_table :wickwalls, :force => true do |t|
- t.string :name
- t.string :last_tweet
- t.datetime :last_tweeted_at
- end
-end
-
-# File: vendor/plugins/yaffle/test/test_helper.rb
-
-ENV['RAILS_ENV'] = 'test'
-ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
-
-require 'test/unit'
-require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
-
-config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
-ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
-
-db_adapter = ENV['DB']
-
-# no db passed, try one of these fine config-free DBs before bombing.
-db_adapter ||=
- begin
- require 'rubygems'
- require 'sqlite'
- 'sqlite'
- rescue MissingSourceFile
- begin
- require 'sqlite3'
- 'sqlite3'
- rescue MissingSourceFile
- end
- end
-
-if db_adapter.nil?
- raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
-end
-
-ActiveRecord::Base.establish_connection(config[db_adapter])
-
-load(File.dirname(__FILE__) + "/schema.rb")
-
-require File.dirname(__FILE__) + '/../init.rb'
-
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle
-end
-
-class Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
-end
-----------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
deleted file mode 100644
index 50516cef69..0000000000
--- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
+++ /dev/null
@@ -1,103 +0,0 @@
-== Add a `to_squawk` method to String ==
-
-To update a core class you will have to:
-
- * Write tests for the desired functionality.
- * Create a file for the code you wish to use.
- * Require that file from your 'init.rb'.
-
-Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'.
-
-First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
-
-[source, ruby]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/test/core_ext_test.rb
-
-require 'test/unit'
-
-class CoreExtTest < Test::Unit::TestCase
- # Replace this with your real tests.
- def test_this_plugin
- flunk
- end
-end
---------------------------------------------------------
-
-Start off by removing the default test, and adding a require statement for your test helper.
-
-[source, ruby]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/test/core_ext_test.rb
-
-require 'test/unit'
-require File.dirname(__FILE__) + '/test_helper.rb'
-
-class CoreExtTest < Test::Unit::TestCase
-end
---------------------------------------------------------
-
-Navigate to your plugin directory and run `rake test`:
-
---------------------------------------------------------
-cd vendor/plugins/yaffle
-rake test
---------------------------------------------------------
-
-Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message:
-
---------------------------------------------------------
-1.) Failure ...
-No tests were specified
---------------------------------------------------------
-
-Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this:
-
-[source, ruby]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-class CoreExtTest < Test::Unit::TestCase
- def test_string_should_respond_to_squawk
- assert_equal true, "".respond_to?(:to_squawk)
- end
-
- def test_string_prepend_empty_strings_with_the_word_squawk
- assert_equal "squawk!", "".to_squawk
- end
-
- def test_string_prepend_non_empty_strings_with_the_word_squawk
- assert_equal "squawk! Hello World", "Hello World".to_squawk
- end
-end
---------------------------------------------------------
-
-[source, ruby]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-require "core_ext"
---------------------------------------------------------
-
-[source, ruby]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/core_ext.rb
-
-String.class_eval do
- def to_squawk
- "squawk! #{self}".strip
- end
-end
---------------------------------------------------------
-
-When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly.
-
-To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:
-
---------------------------------------------------------
-$ ./script/console
->> "Hello World".to_squawk
-=> "squawk! Hello World"
---------------------------------------------------------
-
-If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.
diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt
new file mode 100644
index 0000000000..64236ff110
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/test_setup.txt
@@ -0,0 +1,230 @@
+== Preparation ==
+
+=== Create the basic app ===
+
+The examples in this guide require that you have a working rails application. To create a simple rails app execute:
+
+------------------------------------------------
+gem install rails
+rails yaffle_guide
+cd yaffle_guide
+script/generate scaffold bird name:string
+rake db:migrate
+script/server
+------------------------------------------------
+
+Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
+
+.Editor's note:
+NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
+
+
+=== Generate the plugin skeleton ===
+
+Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
+
+This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories.
+
+Examples:
+----------------------------------------------
+./script/generate plugin yaffle
+./script/generate plugin yaffle --with-generator
+----------------------------------------------
+
+To get more detailed help on the plugin generator, type `./script/generate plugin`.
+
+Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now:
+
+----------------------------------------------
+./script/generate plugin yaffle --with-generator
+----------------------------------------------
+
+You should see the following output:
+
+----------------------------------------------
+create vendor/plugins/yaffle/lib
+create vendor/plugins/yaffle/tasks
+create vendor/plugins/yaffle/test
+create vendor/plugins/yaffle/README
+create vendor/plugins/yaffle/MIT-LICENSE
+create vendor/plugins/yaffle/Rakefile
+create vendor/plugins/yaffle/init.rb
+create vendor/plugins/yaffle/install.rb
+create vendor/plugins/yaffle/uninstall.rb
+create vendor/plugins/yaffle/lib/yaffle.rb
+create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
+create vendor/plugins/yaffle/test/core_ext_test.rb
+create vendor/plugins/yaffle/generators
+create vendor/plugins/yaffle/generators/yaffle
+create vendor/plugins/yaffle/generators/yaffle/templates
+create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
+create vendor/plugins/yaffle/generators/yaffle/USAGE
+----------------------------------------------
+
+To begin just change one thing - move 'init.rb' to 'rails/init.rb'.
+
+=== Setup the plugin for testing ===
+
+If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.
+
+To setup your plugin to allow for easy testing you'll need to add 3 files:
+
+ * A 'database.yml' file with all of your connection strings
+ * A 'schema.rb' file with your table definitions
+ * A test helper method that sets up the database
+
+*vendor/plugins/yaffle/test/database.yml:*
+
+----------------------------------------------
+sqlite:
+ :adapter: sqlite
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
+
+sqlite3:
+ :adapter: sqlite3
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
+
+postgresql:
+ :adapter: postgresql
+ :username: postgres
+ :password: postgres
+ :database: yaffle_plugin_test
+ :min_messages: ERROR
+
+mysql:
+ :adapter: mysql
+ :host: localhost
+ :username: root
+ :password: password
+ :database: yaffle_plugin_test
+----------------------------------------------
+
+For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
+
+*vendor/plugins/yaffle/test/schema.rb:*
+
+[source, ruby]
+----------------------------------------------
+ActiveRecord::Schema.define(:version => 0) do
+ create_table :hickwalls, :force => true do |t|
+ t.string :name
+ t.string :last_squawk
+ t.datetime :last_squawked_at
+ end
+ create_table :wickwalls, :force => true do |t|
+ t.string :name
+ t.string :last_tweet
+ t.datetime :last_tweeted_at
+ end
+ create_table :woodpeckers, :force => true do |t|
+ t.string :name
+ end
+end
+----------------------------------------------
+
+*vendor/plugins/yaffle/test/test_helper.rb:*
+
+[source, ruby]
+----------------------------------------------
+ENV['RAILS_ENV'] = 'test'
+ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
+
+require 'test/unit'
+require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
+
+def load_schema
+ config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
+ ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
+
+ db_adapter = ENV['DB']
+
+ # no db passed, try one of these fine config-free DBs before bombing.
+ db_adapter ||=
+ begin
+ require 'rubygems'
+ require 'sqlite'
+ 'sqlite'
+ rescue MissingSourceFile
+ begin
+ require 'sqlite3'
+ 'sqlite3'
+ rescue MissingSourceFile
+ end
+ end
+
+ if db_adapter.nil?
+ raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
+ end
+
+ ActiveRecord::Base.establish_connection(config[db_adapter])
+ load(File.dirname(__FILE__) + "/schema.rb")
+ require File.dirname(__FILE__) + '/../rails/init.rb'
+end
+----------------------------------------------
+
+Now whenever you write a test that requires the database, you can call 'load_schema'.
+
+=== Run the plugin tests ===
+
+Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with:
+
+*vendor/plugins/yaffle/test/yaffle_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class YaffleTest < Test::Unit::TestCase
+ load_schema
+
+ class Hickwall < ActiveRecord::Base
+ end
+
+ class Wickwall < ActiveRecord::Base
+ end
+
+ def test_schema_has_loaded_correctly
+ assert_equal [], Hickwall.all
+ assert_equal [], Wickwall.all
+ end
+
+end
+----------------------------------------------
+
+To run this, go to the plugin directory and run `rake`:
+
+----------------------------------------------
+cd vendor/plugins/yaffle
+rake
+----------------------------------------------
+
+You should see output like:
+
+----------------------------------------------
+/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
+-- create_table(:hickwalls, {:force=>true})
+ -> 0.0220s
+-- create_table(:wickwalls, {:force=>true})
+ -> 0.0077s
+-- initialize_schema_migrations_table()
+ -> 0.0007s
+-- assume_migrated_upto_version(0)
+ -> 0.0007s
+Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
+Started
+.
+Finished in 0.002236 seconds.
+
+1 test, 1 assertion, 0 failures, 0 errors
+----------------------------------------------
+
+By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:
+
+----------------------------------------------
+rake DB=sqlite
+rake DB=sqlite3
+rake DB=mysql
+rake DB=postgresql
+----------------------------------------------
+
+Now you are ready to test-drive your plugin!
diff --git a/railties/doc/guides/source/creating_plugins/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt
deleted file mode 100644
index b03a190e1a..0000000000
--- a/railties/doc/guides/source/creating_plugins/view_helper.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-== Create a `squawk_info_for` view helper ==
-
-Creating a view helper is a 3-step process:
-
- * Add an appropriately named file to the 'lib' directory.
- * Require the file and hooks in 'init.rb'.
- * Write the tests.
-
-First, create the test to define the functionality you want:
-
-[source, ruby]
----------------------------------------------------------------
-# File: vendor/plugins/yaffle/test/view_helpers_test.rb
-
-require File.dirname(__FILE__) + '/test_helper.rb'
-include YaffleViewHelper
-
-class ViewHelpersTest < Test::Unit::TestCase
- def test_squawk_info_for_should_return_the_text_and_date
- time = Time.now
- hickwall = Hickwall.new
- hickwall.last_squawk = "Hello World"
- hickwall.last_squawked_at = time
- assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
- end
-end
----------------------------------------------------------------
-
-Then add the following statements to init.rb:
-
-[source, ruby]
----------------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-require "view_helpers"
-ActionView::Base.send :include, YaffleViewHelper
----------------------------------------------------------------
-
-Then add the view helpers file and
-
-[source, ruby]
----------------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/view_helpers.rb
-
-module YaffleViewHelper
- def squawk_info_for(yaffle)
- returning "" do |result|
- result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
- result << ", "
- result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s
- end
- end
-end
----------------------------------------------------------------
-
-You can also test this in script/console by using the `helper` method:
-
----------------------------------------------------------------
-$ ./script/console
->> helper.squawk_info_for(@some_yaffle_instance)
----------------------------------------------------------------
diff --git a/railties/doc/guides/source/debugging_rails_applications.txt b/railties/doc/guides/source/debugging_rails_applications.txt
index 24eb0c0431..4425d9240b 100644
--- a/railties/doc/guides/source/debugging_rails_applications.txt
+++ b/railties/doc/guides/source/debugging_rails_applications.txt
@@ -31,7 +31,6 @@ The `debug` helper will return a <pre>-tag that renders the object using the YAM
You'll see something like this:
-[source, log]
----------------------------------------------------------------------------
--- !ruby/object:Post
attributes:
@@ -64,7 +63,6 @@ The `to_yaml` method converts the method to YAML format leaving it more readable
As a result of this, you will have something like this in your view:
-[source, log]
----------------------------------------------------------------------------
--- !ruby/object:Post
attributes:
@@ -94,13 +92,33 @@ Another useful method for displaying object values is `inspect`, especially when
Will be rendered as follows:
-[source, log]
----------------------------------------------------------------------------
[1, 2, 3, 4, 5]
Title: Rails debugging guide
----------------------------------------------------------------------------
+=== Debugging Javascript
+
+Rails has built-in support to debug RJS, to active it, set `ActionView::Base.debug_rjs` to _true_, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).
+
+To enable it, add the following in the `Rails::Initializer do |config|` block inside +environment.rb+:
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.action_view[:debug_rjs] = true
+----------------------------------------------------------------------------
+
+Or, at any time, setting `ActionView::Base.debug_rjs` to _true_:
+
+[source, ruby]
+----------------------------------------------------------------------------
+ActionView::Base.debug_rjs = true
+----------------------------------------------------------------------------
+
+[TIP]
+For more information on debugging javascript refer to link:http://getfirebug.com/[Firebug], the popular debugger for Firefox.
+
== The Logger
It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.
@@ -183,7 +201,6 @@ end
Here's an example of the log generated by this method:
-[source, log]
----------------------------------------------------------------------------
Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
@@ -237,7 +254,6 @@ end
If you see the message in the console or logs:
-[source, log]
----------------------------------------------------------------------------
***** Debugger requested, but was not available: Start server with --debugger to enable *****
----------------------------------------------------------------------------
@@ -271,7 +287,7 @@ For example:
(rdb:7)
----------------------------------------------------------------------------
-Now it's time to play and dig into your application. A good place to start is by asking the debugger for help... so type: `help` (You didn't see that coming, right?)
+Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help... so type: `help` (You didn't see that coming, right?)
----------------------------------------------------------------------------
(rdb:7) help
@@ -579,7 +595,7 @@ To list all active catchpoints use `catch`.
There are two ways to resume execution of an application that is stopped in the debugger:
* `continue` [line-specification] (or `c`): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached.
-* `finish` [frame-number] (or `fin`): execute until the selected stack frame returns. If no frame number is given, the application run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
+* `finish` [frame-number] (or `fin`): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
=== Editing
@@ -610,13 +626,91 @@ You can include any number of these configuration lines inside a `.rdebugrc` fil
Here's a good start for an `.rdebugrc`:
-[source, log]
----------------------------------------------------------------------------
set autolist
set forcestep
set listsize 25
----------------------------------------------------------------------------
+== Debugging Memory Leaks
+
+A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.
+
+In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.
+
+=== BleakHouse
+
+link:http://github.com/fauna/bleak_house/tree/master[BleakHouse] is a library for finding memory leaks.
+
+If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.
+
+To install it run:
+
+----------------------------------------------------------------------------
+sudo gem install bleak_house
+----------------------------------------------------------------------------
+
+Then setup you application for profiling. Then add the following at the bottom of config/environment.rb:
+
+[source, ruby]
+----------------------------------------------------------------------------
+require 'bleak_house' if ENV['BLEAK_HOUSE']
+----------------------------------------------------------------------------
+
+Start a server instance with BleakHouse integration:
+
+----------------------------------------------------------------------------
+RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house ./script/server
+----------------------------------------------------------------------------
+
+Make sure to run a couple hundred requests to get better data samples, then press `CTRL-C`. The server will stop and Bleak House will produce a dumpfile in `/tmp`:
+
+----------------------------------------------------------------------------
+** BleakHouse: working...
+** BleakHouse: complete
+** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.
+----------------------------------------------------------------------------
+
+To analyze it, just run the listed command. The top 20 leakiest lines will be listed:
+
+----------------------------------------------------------------------------
+ 191691 total objects
+ Final heap size 191691 filled, 220961 free
+ Displaying top 20 most common line/class pairs
+ 89513 __null__:__null__:__node__
+ 41438 __null__:__null__:String
+ 2348 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:Array
+ 1508 /opt/local//lib/ruby/gems/1.8/specifications/gettext-1.90.0.gemspec:14:String
+ 1021 /opt/local//lib/ruby/gems/1.8/specifications/heel-0.2.0.gemspec:14:String
+ 951 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:111:String
+ 935 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:String
+ 834 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:146:Array
+ ...
+----------------------------------------------------------------------------
+
+This way you can find where your application is leaking memory and fix it.
+
+If link:http://github.com/fauna/bleak_house/tree/master[BleakHouse] doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
+
+=== Valgrind
+
+link:http://valgrind.org/[Valgrind] is a Linux-only application for detecting C-based memory leaks and race conditions.
+
+There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls `malloc()` but is doesn't properly call `free()`, this memory won't be available until the app terminates.
+
+For further information on how to install Valgrind and use with Ruby, refer to link:http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/[Valgrind and Ruby] by Evan Weaver.
+
+== Plugins for Debugging
+
+There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
+
+* link:http://github.com/drnic/rails-footnotes/tree/master[Footnotes]: Every Rails page has footnotes that give request information and link back to your source via TextMate.
+* link:http://github.com/ntalbott/query_trace/tree/master[Query Trace]: Adds query origin tracing to your logs.
+* link:http://github.com/dan-manges/query_stats/tree/master[Query Stats]: A Rails plugin to track database queries.
+* link:http://code.google.com/p/query-reviewer/[Query Reviewer]: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
+* link:http://github.com/rails/exception_notification/tree/master[Exception Notifier]: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
+* link:http://github.com/defunkt/exception_logger/tree/master[Exception Logger]: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
+
== References
* link:http://www.datanoise.com/ruby-debug[ruby-debug Homepage]
@@ -628,10 +722,12 @@ set listsize 25
* link:http://bashdb.sourceforge.net/ruby-debug.html[Debugging with ruby-debug]
* link:http://cheat.errtheblog.com/s/rdebug/[ruby-debug cheat sheet]
* link:http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging[Ruby on Rails Wiki: How to Configure Logging]
+* link:http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html[Bleak House Documentation]
== Changelog ==
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5[Lighthouse ticket]
+* November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by link:../authors.html#miloops[Emilio Tagua]
* October 19, 2008: Copy editing pass by link:../authors.html#mgunderloy[Mike Gunderloy]
* September 16, 2008: initial version by link:../authors.html#miloops[Emilio Tagua]
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index 945b527e1d..e5d94cffb0 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -1,21 +1,17 @@
Rails Finders
=============
-This guide is all about the +find+ method defined in +ActiveRecord::Base+, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master.
+This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:
-== In the beginning...
+* Find records using a variety of methods and conditions
+* Specify the order, retrieved attributes, grouping, and other properties of the found records
+* Use eager loading to cut down on the number of database queries in your application
+* Use dynamic finders
+* Create named scopes to add custom finding behavior to your models
+* Check for the existence of particular records
+* Perform aggregate calculations on Active Record models
-In the beginning there was SQL. SQL looked like this:
-
-[source,sql]
--------------------------------------------------------
-SELECT * FROM clients
-SELECT * FROM clients WHERE id = '1'
-SELECT * FROM clients LIMIT 0,1
-SELECT * FROM clients ORDER BY id DESC LIMIT 0,1
--------------------------------------------------------
-
-In Rails (unlike some other frameworks) you don't usually have to type SQL because Active Record is there to help you find your records.
+If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
== The Sample Models
@@ -68,7 +64,6 @@ If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +
SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
-------------------------------------------------------
-[source,txt]
-------------------------------------------------------
>> Client.find(1,2)
=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
@@ -79,9 +74,10 @@ SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
Note that if you pass in a list of numbers that the result will be returned as an array, not as a single +Client+ object.
+NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
+
If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table:
-[source,txt]
-------------------------------------------------------
>> Client.first
=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
@@ -99,7 +95,6 @@ Indicating the query that Rails has performed on your database.
To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
-[source,txt]
-------------------------------------------------------
>> Client.find(:last)
=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
@@ -113,7 +108,6 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table:
-[source,txt]
-------------------------------------------------------
>> Client.all
=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
@@ -128,13 +122,17 @@ Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.fin
== Conditions
+The +find+ method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
+
=== Pure String Conditions ===
If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
+WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
+
=== Array Conditions ===
- Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
+Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
The reason for doing code like:
@@ -192,7 +190,6 @@ SELECT * FROM +users+ WHERE (created_at IN
This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
-[source, txt]
-------------------------------------------------------
Got a packet bigger than 'max_allowed_packet' bytes: _query_
-------------------------------------------------------
@@ -239,7 +236,7 @@ To select certain fields, you can use the select option like this: +Client.first
== Limit & Offset
-If you want to limit the amount of records to a certain subset of all the records retreived you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retreived from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:
+If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:
[source, ruby]
-------------------------------------------------------
@@ -285,14 +282,14 @@ SELECT * FROM +orders+ GROUP BY date(created_at)
== Read Only
-Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an +Active Record::ReadOnlyRecord+ error. To set this option, specify it like this:
+Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this:
[source, ruby]
-------------------------------------------------------
Client.first(:readonly => true)
-------------------------------------------------------
-If you assign this record to a variable +client+, calling the following code will raise an ActiveRecord::ReadOnlyRecord:
+If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
[source, ruby]
-------------------------------------------------------
@@ -315,11 +312,11 @@ end
== Making It All Work Together
-You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.
+You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.
== Eager Loading
-Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all), :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
+Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
[source, sql]
-------------------------------------------------------
@@ -391,11 +388,11 @@ If you'd like to use your own SQL to find records a table you can use +find_by_s
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
-------------------------------------------------------
-+find_by_sql+ provides you with a simple way of making custom calls to the database and retreiving instantiated objects.
++find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
== +select_all+ ==
-+find_by_sql+ has a close relative called +select_all+. +select_all+ will retreive objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
++find_by_sql+ has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
[source, ruby]
-------------------------------------------------------
@@ -404,11 +401,15 @@ Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
== Working with Associations
-When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers.
+When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers.
== Named Scopes
-Named scopes are another way to add custom finding behavior to the models in the application. Suppose want to find all clients who are male. Yould use this code:
+Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.
+
+=== Simple Named Scopes
+
+Suppose want to find all clients who are male. You could use this code:
[source, ruby]
-------------------------------------------------------
@@ -417,7 +418,7 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
-And you could call it like +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end.
+Then you could call +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end.
If you wanted to find all the clients who are active, you could use this:
@@ -428,7 +429,9 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
-You can call this new named_scope by doing +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+.
+You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+.
+
+=== Combining Named Scopes
If you wanted to find all the clients who are active and male you can stack the named scopes like this:
@@ -444,6 +447,8 @@ If you would then like to do a +all+ on that scope, you can. Just like an associ
Client.males.active.all(:conditions => ["age > ?", params[:age]])
-------------------------------------------------------
+=== Runtime Evaluation of Named Scope Conditions
+
Consider the following code:
[source, ruby]
@@ -464,6 +469,8 @@ end
And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
+=== Named Scopes with Multiple Models
+
In a named scope you can use +:include+ and +:joins+ options just like in find.
[source, ruby]
@@ -476,6 +483,8 @@ end
This method, called as +Client.active_within_2_weeks.all+, will return all clients who have placed orders in the past 2 weeks.
+=== Arguments to Named Scopes
+
If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:
[source, ruby]
@@ -498,7 +507,9 @@ This will work with +Client.recent(2.weeks.ago).all+ and +Client.recent.all+, wi
Remember that named scopes are stackable, so you will be able to do +Client.recent(2.weeks.ago).unlocked.all+ to find all clients created between right now and 2 weeks ago and have their locked field set to false.
-Finally, if you wish to define named scopes on the fly you can use the scoped method:
+=== Anonymous Scopes
+
+All Active Record models come with a named scope named +scoped+, which allows you to create anonymous scopes. For example:
[source, ruby]
-------------------------------------------------------
@@ -509,6 +520,15 @@ class Client < ActiveRecord::Base
end
-------------------------------------------------------
+Anonymous scopes are most useful to create scopes "on the fly":
+
+[source, ruby]
+-------------------------------------------------------
+Client.scoped(:conditions => { :gender => "male" })
+-------------------------------------------------------
+
+Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
+
== Existence of Objects
If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.
@@ -518,7 +538,7 @@ If you simply want to check for the existence of the object there's a method cal
Client.exists?(1)
-------------------------------------------------------
-The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.
+The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.
[source, ruby]
-------------------------------------------------------
@@ -635,8 +655,9 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
-* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section.
-* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point.
+* November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
+* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
+* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg
* October 26, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
* October 22, 2008: Calculations complete, first complete draft by Ryan Bigg
* October 21, 2008: Extended named scope section by Ryan Bigg
diff --git a/railties/doc/guides/source/form_helpers.txt b/railties/doc/guides/source/form_helpers.txt
index 7b0aeb0ed9..88ca74a557 100644
--- a/railties/doc/guides/source/form_helpers.txt
+++ b/railties/doc/guides/source/form_helpers.txt
@@ -2,7 +2,7 @@ Rails form helpers
==================
Mislav Marohnić <mislav.marohnic@gmail.com>
-Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
+Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
In this guide we will:
@@ -112,7 +112,7 @@ form_tag({:controller => "people", :action => "search"}, :method => "get")
This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.
-WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly `expecting tASSOC` syntax error.
+WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an `expecting tASSOC` syntax error.
Checkboxes, radio buttons and other controls
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -149,7 +149,7 @@ output:
<label for="age_adult">I'm over 21</label>
----------------------------------------------------------------------------
-IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region.
+IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.
Other form controls we might mention are the text area, password input and hidden input:
@@ -174,7 +174,7 @@ How do forms with PUT or DELETE methods work?
Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?
-Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the _real_ method:
+Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the wanted method:
----------------------------------------------------------------------------
form_tag(search_path, :method => "put")
@@ -267,4 +267,79 @@ form_for(@article)
Notice how the short-style `form_for` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`.
-WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url` and `:method` explicitly. \ No newline at end of file
+WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url` and `:method` explicitly.
+
+
+Making select boxes with ease
+-----------------------------
+
+Select boxes in HTML require a significant amount of markup (one `OPTION` element for each option to choose from), therefore it makes the most sense for them to be dynamically generated from data stored in arrays or hashes.
+
+Here is what our wanted markup might look like:
+
+----------------------------------------------------------------------------
+<select name="city_id" id="city_id">
+ <option value="1">Lisabon</option>
+ <option value="2">Madrid</option>
+ ...
+ <option value="12">Berlin</option>
+</select>
+----------------------------------------------------------------------------
+
+Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.
+
+The select tag and options
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates the options:
+
+----------------------------------------------------------------------------
+<%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %>
+----------------------------------------------------------------------------
+
+This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.
+
+We can generate option tags with the `options_for_select` helper:
+
+----------------------------------------------------------------------------
+<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
+
+output:
+
+<option value="1">Lisabon</option>
+<option value="2">Madrid</option>
+...
+----------------------------------------------------------------------------
+
+For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).
+
+Now you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
+
+----------------------------------------------------------------------------
+<%= select_tag(:city_id, options_for_select(...)) %>
+----------------------------------------------------------------------------
+
+Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The `options_for_select` helper supports this with an optional second argument:
+
+----------------------------------------------------------------------------
+<%= options_for_select(cities_array, 2) %>
+
+output:
+
+<option value="1">Lisabon</option>
+<option value="2" selected="selected">Madrid</option>
+...
+----------------------------------------------------------------------------
+
+So whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
+
+Select boxes for dealing with models
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a `city_id` attribute.
+
+----------------------------------------------------------------------------
+...
+----------------------------------------------------------------------------
+
+... \ No newline at end of file
diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt
index c5bbc9e814..bae8f9a4fd 100644
--- a/railties/doc/guides/source/getting_started_with_rails.txt
+++ b/railties/doc/guides/source/getting_started_with_rails.txt
@@ -186,7 +186,7 @@ If you open this file in a new Rails application, you'll see a default database
==== Configuring a SQLite Database
-Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
+Rails comes with built-in support for link:http://www.sqlite.org/[SQLite], which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
Here's the section of the default configuration file with connection information for the development environment:
@@ -480,7 +480,7 @@ This code sets the +@posts+ instance variable to an array of all posts in the da
TIP: For more information on finding records with Active Record, see link:../finders.html[Active Record Finders].
-The +respond_to+ block handles both HTML and XML calls to this action. If you borwse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/view/posts/index.html.erb+:
+The +respond_to+ block handles both HTML and XML calls to this action. If you browse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/view/posts/index.html.erb+:
[source, ruby]
-------------------------------------------------------
@@ -751,6 +751,7 @@ At this point, it’s worth looking at some of the tools that Rails provides to
As you saw earlier, the scaffold-generated views for the +new+ and +edit+ actions are largely identical. You can pull the shared code out into a +partial+ template. This requires editing the new and edit views, and adding a new template:
+new.html.erb+:
+
[source, ruby]
-------------------------------------------------------
<h1>New post</h1>
@@ -761,6 +762,7 @@ As you saw earlier, the scaffold-generated views for the +new+ and +edit+ action
-------------------------------------------------------
+edit.html.erb+:
+
[source, ruby]
-------------------------------------------------------
<h1>Editing post</h1>
@@ -772,6 +774,7 @@ As you saw earlier, the scaffold-generated views for the +new+ and +edit+ action
-------------------------------------------------------
+_form.html.erb+:
+
[source, ruby]
-------------------------------------------------------
<% form_for(@post) do |f| %>
@@ -979,12 +982,12 @@ $ script/generate controller Comments index show new edit
This creates seven files:
* +app/controllers/comments_controller.rb+ - The controller
-* +app/helpers/comments_helper.rb - A view helper file
-* +app/views/comments/index.html.erb - The view for the index action
-* +app/views/comments/show.html.erb - The view for the show action
-* +app/views/comments/new.html.erb - The view for the new action
-* +app/views/comments/edit.html.erb - The view for the edit action
-* +test/functional/comments_controller_test.rb - The functional tests for the controller
+* +app/helpers/comments_helper.rb+ - A view helper file
+* +app/views/comments/index.html.erb+ - The view for the index action
+* +app/views/comments/show.html.erb+ - The view for the show action
+* +app/views/comments/new.html.erb+ - The view for the new action
+* +app/views/comments/edit.html.erb+ - The view for the edit action
+* +test/functional/comments_controller_test.rb+ - The functional tests for the controller
The controller will be generated with empty methods for each action that you specified in the call to +script/generate controller+:
@@ -1216,15 +1219,21 @@ Note that each post has its own individual comments collection, accessible as +@
Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources:
-* The [http://manuals.rubyonrails.org/]Ruby On Rails guides
+* The link:http://manuals.rubyonrails.org/[Ruby On Rails guides]
* The link:http://groups.google.com/group/rubyonrails-talk[Ruby on Rails mailing list]
* The #rubyonrails channel on irc.freenode.net
* The link:http://wiki.rubyonrails.org/rails[Rails wiki]
+Rails also comes with built-in help that you can generate using the rake command-line utility:
+
+* Running +rake doc:guides+ will put a full copy of the Rails Guides in the +/doc/guides+ folder of your application. Open +/doc/guides/index.html+ in your web browser to explore the Guides.
+* Running +rake doc:rails+ will put a full copy of the API documentation for Rails in the +/doc/api+ folder of your application. Open +/doc/api/index.html+ in your web browser to explore the API documentation.
+
== Changelog ==
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2[Lighthouse ticket]
+* November 3, 2008: Formatting patch from Dave Rothlisberger
* November 1, 2008: First approved version by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 16, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
* October 13, 2008: First complete draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
diff --git a/railties/doc/guides/source/index.txt b/railties/doc/guides/source/index.txt
index 05d7deee6a..8828e1d313 100644
--- a/railties/doc/guides/source/index.txt
+++ b/railties/doc/guides/source/index.txt
@@ -42,7 +42,7 @@ This guide covers the find method defined in ActiveRecord::Base, as well as name
.link:layouts_and_rendering.html[Layouts and Rendering in Rails]
***********************************************************
This guide covers the basic layout features of Action Controller and Action View,
-including rendering and redirecting, using +content_for_ blocks, and working
+including rendering and redirecting, using +content_for+ blocks, and working
with partials.
***********************************************************
@@ -65,8 +65,6 @@ understand how to use routing in your own Rails applications, start here.
.link:actioncontroller_basics.html[Basics of Action Controller]
***********************************************************
-CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/17[Lighthouse Ticket]
-
This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.
***********************************************************
@@ -92,14 +90,12 @@ Enjoy.
.link:security.html[Securing Rails Applications]
***********************************************************
-This manual describes common security problems in web applications and how to
+This guide describes common security problems in web applications and how to
avoid them with Rails.
***********************************************************
.link:debugging_rails_applications.html[Debugging Rails Applications]
***********************************************************
-CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/5[Lighthouse Ticket]
-
This guide describes how to debug Rails applications. It covers the different
ways of achieving this and how to understand what is happening "behind the scenes"
of your code.
diff --git a/railties/doc/guides/source/layouts_and_rendering.txt b/railties/doc/guides/source/layouts_and_rendering.txt
index 2f39c70e8c..8f1fae5007 100644
--- a/railties/doc/guides/source/layouts_and_rendering.txt
+++ b/railties/doc/guides/source/layouts_and_rendering.txt
@@ -313,7 +313,7 @@ With those declarations, the +inventory+ layout would be used only for the +inde
Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:
-+application.rb+:
++application_controller.rb+:
[source, ruby]
-------------------------------------------------------
@@ -877,6 +877,8 @@ When a partial is called with a pluralized collection, then the individual insta
With this change, you can access an instance of the +@products+ collection as the +item+ local variable within the partial.
+TIP: Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by +_counter+. For example, if you're rendering +@products+, within the partial you can refer to +product_counter+ to tell you how many times the partial has been rendered.
+
You can also specify a second partial to be rendered between instances of the main partial by using the +:spacer_template+ option:
[source, html]
@@ -933,6 +935,7 @@ In this case, Rails will use the customer or employee partials as appropriate fo
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket]
+* November 9, 2008: Added partial collection counter by link:../authors.html#mgunderloy[Mike Gunderloy]
* November 1, 2008: Added +:js+ option for +render+ by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
diff --git a/railties/doc/guides/source/migrations/foreign_keys.txt b/railties/doc/guides/source/migrations/foreign_keys.txt
index 8f796843b2..792c41ccdc 100644
--- a/railties/doc/guides/source/migrations/foreign_keys.txt
+++ b/railties/doc/guides/source/migrations/foreign_keys.txt
@@ -1,6 +1,6 @@
[[foreign_key]]
== Active Record and Referential Integrity ==
-The Active Record way is that intelligence belongs in your models, not in the database. As such features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.
+The Active Record way is that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.
Validations such as `validates_uniqueness_of` are one way in which models can enforce data integrity. The `:dependent` option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
diff --git a/railties/doc/guides/source/migrations/rakeing_around.txt b/railties/doc/guides/source/migrations/rakeing_around.txt
index 1fcca0cf24..6d8c43d7a3 100644
--- a/railties/doc/guides/source/migrations/rakeing_around.txt
+++ b/railties/doc/guides/source/migrations/rakeing_around.txt
@@ -25,7 +25,7 @@ This will run the `down` method from the latest migration. If you need to undo s
rake db:rollback STEP=3
------------------
-will run the `down` method fron the last 3 migrations.
+will run the `down` method from the last 3 migrations.
The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating back up again. As with the `db:rollback` task you can use the `STEP` parameter if you need to go more than one version back, for example
diff --git a/railties/doc/guides/source/migrations/scheming.txt b/railties/doc/guides/source/migrations/scheming.txt
index ba4fea8fe3..7acd3f9190 100644
--- a/railties/doc/guides/source/migrations/scheming.txt
+++ b/railties/doc/guides/source/migrations/scheming.txt
@@ -7,7 +7,7 @@ There is no need (and it is error prone) to deploy a new instance of an app by r
For example, this is how the test database is created: the current development database is dumped (either to `schema.rb` or `development.sql`) and then loaded into the test database.
-Schema files are also useful if want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.
+Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.
=== Types of schema dumps ===
There are two ways to dump the schema. This is set in `config/environment.rb` by the `config.active_record.schema_format` setting, which may be either `:sql` or `:ruby`.
diff --git a/railties/doc/guides/source/routing_outside_in.txt b/railties/doc/guides/source/routing_outside_in.txt
index 6d127973b0..0f6cd358e2 100644
--- a/railties/doc/guides/source/routing_outside_in.txt
+++ b/railties/doc/guides/source/routing_outside_in.txt
@@ -229,6 +229,8 @@ Although the conventions of RESTful routing are likely to be sufficient for many
* +:path_names+
* +:path_prefix+
* +:name_prefix+
+* +:only+
+* +:except+
You can also add additional routes via the +:member+ and +:collection+ options, which are discussed later in this guide.
@@ -400,6 +402,30 @@ This combination will give you route helpers such as +photographer_photos_path+
NOTE: You can also use +:name_prefix+ with non-RESTful routes.
+==== Using :only and :except
+
+By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option specifies that only certain routes should be generated:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :only => [:index, :show]
+-------------------------------------------------------
+
+With this declaration, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the create action) will fail.
+
+The +:except+ option specifies a route or list of routes that should _not_ be generated:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :except => :destroy
+-------------------------------------------------------
+
+In this case, all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/_id_+) will be generated.
+
+In addition to an action or a list of actions, you can also supply the special symbols +:all+ or +:none+ to the +:only+ and +:except+ options.
+
+TIP: If your application has many RESTful routes, using +:only+ and +:accept+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
+
=== Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
@@ -535,17 +561,7 @@ This will enable recognition of (among others) these routes:
/photos/3 ==> photo_path(3)
-------------------------------------------------------
-With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you _can_ supply more information. All of the nested routes continue to work, just as they would without shallow nesting, but less-deeply nested routes (even direct routes) work as well. So, with the declaration above, all of these routes refer to the same resource:
-
--------------------------------------------------------
-/publishers/1/magazines/2/photos/3 ==> publisher_magazine_photo_path(1,2,3)
-/magazines/2/photos/3 ==> magazine_photo_path(2,3)
-/photos/3 ==> photo_path(3)
--------------------------------------------------------
-
-Shallow nesting gives you the flexibility to use the shorter direct routes when you like, while still preserving the longer nested routes for times when they add code clarity.
-
-If you like, you can combine shallow nesting with the +:has_one+ and +:has_many+ options:
+With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. If you like, you can combine shallow nesting with the +:has_one+ and +:has_many+ options:
[source, ruby]
-------------------------------------------------------
diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt
index dc7635eff9..6cced2fdd1 100644
--- a/railties/doc/guides/source/testing_rails_applications.txt
+++ b/railties/doc/guides/source/testing_rails_applications.txt
@@ -11,18 +11,17 @@ This guide won't teach you to write a Rails application; it assumes basic famili
== Why Write Tests for your Rails Applications? ==
- * Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
- * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
- * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
* Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
+ * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
+ * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
-== Before you Start Writing Tests ==
+== Introduction to Testing ==
-Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
=== The 3 Environments ===
-Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
+Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
@@ -55,11 +54,11 @@ For good tests, you'll need to give some thought to setting up test data. In Rai
==== What Are Fixtures? ====
-_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
+_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. In this guide we will use *YAML* which is the preferred format.
You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
-==== YAML the Camel is a Mammal with Enamel ====
+==== YAML ====
YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
@@ -69,13 +68,11 @@ Here's a sample YAML fixture file:
---------------------------------------------
# low & behold! I am a YAML comment!
david:
- id: 1
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
steve:
- id: 2
name: Steve Ross Kellock
birthday: 1974-09-27
profession: guy with keyboard
@@ -83,56 +80,24 @@ steve:
Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
-==== Comma Seperated ====
-
-Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the 'test/fixtures' directory, but these end with the +.csv+ file extension (as in +celebrity_holiday_figures.csv+).
-
-A CSV fixture looks like this:
-
-[source, log]
---------------------------------------------------------------
-id, username, password, stretchable, comments
-1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
-2, ebunny, ihateeggs, true, Hoppity hop y'all
-3, tfairy, ilovecavities, true, "Pull your teeth, I will"
---------------------------------------------------------------
-
-The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:
-
- * Leading and trailing spaces are trimmed from each value when it is imported
- * If you use a comma as data, the cell must be encased in quotes
- * If you use a quote as data, you must escape it with a 2nd quote
- * Don't use blank lines
- * Nulls can be defined by including no data between a pair of commas
-
-Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:
-
-* +celebrity-holiday-figures-1+
-* +celebrity-holiday-figures-2+
-* +celebrity-holiday-figures-3+
-
-The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.
-
==== ERb'in It Up ====
ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
-I'll demonstrate with a YAML file:
-
[source, ruby]
--------------------------------------------------------------
<% earth_size = 20 -%>
mercury:
- id: 1
size: <%= earth_size / 50 %>
+ brightest_on: <%= 113.days.ago.to_s(:db) %>
venus:
- id: 2
size: <%= earth_size / 2 %>
+ brightest_on: <%= 67.days.ago.to_s(:db) %>
mars:
- id: 3
size: <%= earth_size - 69 %>
+ brightest_on: <%= 13.days.from_now.to_s(:db) %>
--------------------------------------------------------------
Anything encased within the
@@ -142,7 +107,7 @@ Anything encased within the
<% %>
------------------------
-tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.
+tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
==== Fixtures in Action ====
@@ -165,9 +130,7 @@ users(:david)
users(:david).id
--------------------------------------------------------------
-But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!
-
-Now you can get at the methods only available to that class.
+Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
[source, ruby]
--------------------------------------------------------------
@@ -178,15 +141,18 @@ david = users(:david).find
email(david.girlfriend.email, david.location_tonight)
--------------------------------------------------------------
-== Unit Testing Your Models ==
+== Unit Testing your Models ==
In Rails, unit tests are what you write to test your models.
-When you create a model using +script/generate+, among other things it creates a test stub in the +test/unit+ folder, as well as a fixture for the model:
+For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.
+
+NOTE: For more information on Rails _scaffolding_, refer to link:../getting_started_with_rails.html[Getting Started with Rails]
+
+When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
-[source, log]
-------------------------------------------------------
-$ script/generate model Post
+$ script/generate scaffold post title:string body:text
...
create app/models/post.rb
create test/unit/post_test.rb
@@ -245,6 +211,36 @@ This line of code is called an _assertion_. An assertion is a line of code that
Every test contains one or more assertions. Only when all the assertions are successful the test passes.
+=== Preparing you Application for Testing ===
+
+Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:
+
+[source, shell]
+-------------------------------------------------------
+$ rake db:migrate
+...
+$ rake db:test:load
+-------------------------------------------------------
+
+Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
+
+NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
+
+==== Rake Tasks for Preparing you Application for Testing ==
+
+[grid="all"]
+--------------------------------`----------------------------------------------------
+Tasks Description
+------------------------------------------------------------------------------------
++rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.
+------------------------------------------------------------------------------------
+
+TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
+
=== Running Tests ===
Running a test is as simple as invoking the file containing the test cases through Ruby:
@@ -266,7 +262,6 @@ This will run all the test methods from the test case.
You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
-[source, log]
-------------------------------------------------------
$ ruby unit/post_test.rb -n test_truth
@@ -280,67 +275,90 @@ Finished in 0.023513 seconds.
The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
-To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case:
+To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
[source,ruby]
--------------------------------------------------
-def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post
+def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save
end
--------------------------------------------------
-If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:
+Let us run this newly added test.
-[source, log]
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.027274 seconds.
+F
+Finished in 0.197094 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-<nil> expected to not be nil.
+<false> is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 1 failures, 0 errors
-------------------------------------------------------
In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
[source,ruby]
--------------------------------------------------
-def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
+def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save, "Saved the post without a title"
end
--------------------------------------------------
Running this test shows the friendlier assertion message:
-[source, log]
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.024727 seconds.
+F
+Finished in 0.198093 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
+Saved the post without a title.
+<false> is not true.
+
+1 tests, 1 assertions, 1 failures, 0 errors
+-------------------------------------------------------
+
+Now to get this test to pass we can add a model level validation for the _title_ field.
+
+[source,ruby]
+--------------------------------------------------
+class Post < ActiveRecord::Base
+ validates_presence_of :title
+end
+--------------------------------------------------
+
+Now the test should pass. Let us verify by running the test again:
+
+-------------------------------------------------------
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+Loaded suite unit/post_test
+Started
+.
+Finished in 0.193608 seconds.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 0 failures, 0 errors
-------------------------------------------------------
+Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
+
+TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
+
To see how an error gets reported, here's a test containing an error:
[source,ruby]
@@ -354,31 +372,22 @@ end
Now you can see even more output in the console from running the tests:
-[source, log]
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
-FE.
-Finished in 0.108389 seconds.
-
- 1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
+E
+Finished in 0.195757 seconds.
- 2) Error:
+ 1) Error:
test_should_report_error(PostTest):
-NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x304a7b0>
+NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
- unit/post_test.rb:15:in `test_should_report_error'
+ unit/post_test.rb:16:in `test_should_report_error'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
-3 tests, 2 assertions, 1 failures, 1 errors
+1 tests, 0 assertions, 0 failures, 1 errors
-------------------------------------------------------
Notice the 'E' in the output. It denotes a test with error.
@@ -389,8 +398,6 @@ NOTE: The execution of each test method stops as soon as any error or a assertio
Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
-TIP: Many Rails developers practice _test-driven development_ (TDD), in which the tests are written _before_ the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
-
=== Assertions Available ===
By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
@@ -460,32 +467,9 @@ You should test for things such as:
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view
-When you use +script/generate+ to create a controller, it automatically creates a functional test for that controller in +test/functional+. For example, if you create a post controller:
-
-[source, shell]
--------------------------------------------------------
-$ script/generate controller post
-...
- create app/controllers/post_controller.rb
- create test/functional/post_controller_test.rb
-...
--------------------------------------------------------
-
-Now if you take a look at the file +posts_controller_test.rb+ in the +test/functional+ directory, you should see:
-
-[source,ruby]
---------------------------------------------------
-require 'test_helper'
-
-class PostsControllerTest < ActionController::TestCase
- # Replace this with your real tests.
- def test_truth
- assert true
- end
-end
---------------------------------------------------
+Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
-Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:
+Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
[source,ruby]
--------------------------------------------------
@@ -519,7 +503,24 @@ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +param
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
--------------------------------------------------
-=== Available Request Types for Functional Tests===
+NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
+
+Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
+
+[source,ruby]
+--------------------------------------------------
+def test_should_create_post
+ assert_difference('Post.count') do
+ post :create, :post => { :title => 'Some title'}
+ end
+
+ assert_redirected_to post_path(assigns(:post))
+end
+--------------------------------------------------
+
+Now you can try running all the tests and they should pass.
+
+=== Available Request Types for Functional Tests ===
If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
@@ -762,6 +763,130 @@ class UserFlowsTest < ActionController::IntegrationTest
end
--------------------------------------------------
+== Rake Tasks for Running your Tests ==
+
+You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+
+[grid="all"]
+--------------------------------`----------------------------------------------------
+Tasks Description
+------------------------------------------------------------------------------------
++rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
+------------------------------------------------------------------------------------
+
+
+== Brief Note About Test::Unit ==
+
+Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests.
+
+NOTE: For more information on +Test::Unit+, refer to link:http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/[test/unit Documentation]
+
+== Setup and Teardown ==
+
+If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in +Posts+ controller:
+
+[source,ruby]
+--------------------------------------------------
+require 'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ def setup
+ @post = posts(:one)
+ end
+
+ # called after every single test
+ def teardown
+ # as we are re-initializing @post before every test
+ # setting it to nil here is not essential but I hope
+ # you understand how you can use the teardown method
+ @post = nil
+ end
+
+ def test_should_show_post
+ get :show, :id => @post.id
+ assert_response :success
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count', -1) do
+ delete :destroy, :id => @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+end
+--------------------------------------------------
+
+Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as ActiveSupport::Callbacks. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using:
+
+ * a block
+ * a method (like in the earlier example)
+ * a method name as a symbol
+ * a lambda
+
+Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
+
+[source,ruby]
+--------------------------------------------------
+require '../test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ setup :initialize_post
+
+ # called after every single test
+ def teardown
+ @post = nil
+ end
+
+ def test_should_show_post
+ get :show, :id => @post.id
+ assert_response :success
+ end
+
+ def test_should_update_post
+ put :update, :id => @post.id, :post => { }
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count', -1) do
+ delete :destroy, :id => @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+ private
+
+ def initialize_post
+ @post = posts(:one)
+ end
+
+end
+--------------------------------------------------
+
+== Testing Routes ==
+
+Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
+
+[source,ruby]
+--------------------------------------------------
+def test_should_route_to_post
+ assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
+end
+--------------------------------------------------
+
== Testing Your Mailers ==
Testing mailer classes requires some specific tools to do a thorough job.
@@ -817,7 +942,6 @@ In this test, +@expected+ is an instance of +TMail::Mail+ that you can use in yo
Here's the content of the +invite+ fixture:
-[source, log]
-------------------------------------------------
Hi friend@example.com,
@@ -852,30 +976,6 @@ class UserControllerTest < ActionController::TestCase
end
----------------------------------------------------------------
-== Rake Tasks for Testing
-
-You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
-
-[grid="all"]
---------------------------------`----------------------------------------------------
-Tasks Description
-------------------------------------------------------------------------------------
-+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
-+rake test:units+ Runs all the unit tests from +test/unit+
-+rake test:functionals+ Runs all the functional tests from +test/functional+
-+rake test:integration+ Runs all the integration tests from +test/integration+
-+rake test:recent+ Tests recent changes
-+rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
-+rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
-+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.
-------------------------------------------------------------------------------------
-
-TIP: You can see all these rake task and their descriptions by running +rake --tasks --describe+
-
== Other Testing Approaches
The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
@@ -889,6 +989,7 @@ The built-in +test/unit+ based testing is not the only way to test Rails applica
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket]
+* November 13, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
* October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
-* October 12, 2008: First draft by link:../authors.html#asurve[Akashay Surve] (not yet approved for publication)
+* October 12, 2008: First draft by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
diff --git a/railties/environments/boot.rb b/railties/environments/boot.rb
index 6a30b54973..0a516880ca 100644
--- a/railties/environments/boot.rb
+++ b/railties/environments/boot.rb
@@ -67,7 +67,7 @@ module Rails
class << self
def rubygems_version
- Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
+ Gem::RubyGemsVersion rescue nil
end
def gem_version
@@ -82,7 +82,7 @@ module Rails
def load_rubygems
require 'rubygems'
- min_version = '1.1.1'
+ min_version = '1.3.1'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb
index f27ccc6bb8..4a2df36307 100644
--- a/railties/environments/environment.rb
+++ b/railties/environments/environment.rb
@@ -1,9 +1,5 @@
# Be sure to restart your server when you modify this file
-# Uncomment below to force Rails into production mode when
-# you don't control web/app server and can't set it the proper way
-# ENV['RAILS_ENV'] ||= 'production'
-
# Specifies gem version of Rails to use when vendor/rails is not present
<%= '# ' if freeze %>RAILS_GEM_VERSION = '<%= Rails::VERSION::STRING %>' unless defined? RAILS_GEM_VERSION
@@ -14,57 +10,32 @@ 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.
- # See Rails::Configuration for more options.
- # Skip frameworks you're not going to use. To use Rails without a database
- # you must remove the Active Record framework.
- # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
+ # Add additional load paths for your own custom dirs
+ # config.load_paths += %W( #{RAILS_ROOT}/extras )
- # Specify gems that this application depends on.
- # They can then be installed with "rake gems:install" on new installations.
- # You have to specify the <tt>:lib</tt> option for libraries, where the Gem name (<em>sqlite3-ruby</em>) differs from the file itself (_sqlite3_)
+ # Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
- # Only load the plugins named here, in the order given. By default, all plugins
- # in vendor/plugins are loaded in alphabetical order.
+ # 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 ]
- # Add additional load paths for your own custom dirs
- # config.load_paths += %W( #{RAILS_ROOT}/extras )
+ # Skip frameworks you're not going to use. To use Rails without a database,
+ # you must remove the Active Record framework.
+ # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
- # Force all environments to use the same logger level
- # (by default production uses :info, the others :debug)
- # config.log_level = :debug
+ # Activate observers that should always be running
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
- # Make Time.zone default to the specified zone, and make Active Record store time values
- # in the database in UTC, and return them converted to the specified local zone.
- # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time.
+ # 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'
- # Your secret key for verifying cookie session data integrity.
- # If you change this key, all old sessions 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.
- config.action_controller.session = {
- :session_key => '_<%= app_name %>_session',
- :secret => '<%= app_secret %>'
- }
-
- # Use the database for sessions instead of the cookie-based default,
- # which shouldn't be used to store highly confidential information
- # (create the session table with "rake db:sessions:create")
- # config.action_controller.session_store = :active_record_store
-
- # 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
-
- # Activate observers that should always be running
- # Please note that observers generated using script/generate observer need to have an _observer suffix
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-end
+ # 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
+end \ No newline at end of file
diff --git a/railties/environments/production.rb b/railties/environments/production.rb
index ec5b7bc865..1fc9f6b923 100644
--- a/railties/environments/production.rb
+++ b/railties/environments/production.rb
@@ -4,21 +4,24 @@
# Code is not reloaded between requests
config.cache_classes = true
-# Enable threaded mode
-# config.threadsafe!
-
-# Use a different logger for distributed setups
-# config.logger = SyslogLogger.new
-
# 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
# Enable serving of images, stylesheets, and javascripts from an asset server
-# config.action_controller.asset_host = "http://assets.example.com"
+# 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! \ No newline at end of file
diff --git a/railties/environments/test.rb b/railties/environments/test.rb
index 1e709e1d19..496eb9572b 100644
--- a/railties/environments/test.rb
+++ b/railties/environments/test.rb
@@ -20,3 +20,8 @@ config.action_controller.allow_forgery_protection = false
# 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/helpers/application.rb b/railties/helpers/application.rb
deleted file mode 100644
index 0a3ed822a4..0000000000
--- a/railties/helpers/application.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-# Filters added to this controller apply to all controllers in the application.
-# Likewise, all the methods added will be available for all controllers.
-
-class ApplicationController < ActionController::Base
- helper :all # include all helpers, all the time
-
- # See ActionController::RequestForgeryProtection for details
- # Uncomment the :secret if you're not using the cookie session store
- protect_from_forgery # :secret => '<%= app_secret %>'
-
- # See ActionController::Base for details
- # Uncomment this to filter the contents of submitted sensitive data parameters
- # from your application log (in this case, all fields with names like "password").
- # filter_parameter_logging :password
-end
diff --git a/railties/helpers/application_controller.rb b/railties/helpers/application_controller.rb
new file mode 100644
index 0000000000..6635a3f487
--- /dev/null
+++ b/railties/helpers/application_controller.rb
@@ -0,0 +1,10 @@
+# Filters added to this controller apply to all controllers in the application.
+# 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
+end
diff --git a/railties/helpers/test_helper.rb b/railties/helpers/test_helper.rb
index 9f1926950f..b9fe2517c8 100644
--- a/railties/helpers/test_helper.rb
+++ b/railties/helpers/test_helper.rb
@@ -2,7 +2,7 @@ ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
-class Test::Unit::TestCase
+class ActiveSupport::TestCase
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
diff --git a/railties/html/javascripts/controls.js b/railties/html/javascripts/controls.js
index 5aaf0bb2b7..ca29aefdd1 100644
--- a/railties/html/javascripts/controls.js
+++ b/railties/html/javascripts/controls.js
@@ -1,22 +1,22 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
-// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
+// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
-//
+//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
-// Autocompleter.Base handles all the autocompletion functionality
+// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
-// Specific autocompleters need to provide, at the very least,
+// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
-// the text inside the monitored textbox changes. This method
+// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
@@ -30,23 +30,23 @@
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
-// enables autocompletion on multiple tokens. This is most
-// useful when one of the tokens is \n (a newline), as it
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
-var Autocompleter = { }
+var Autocompleter = { };
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
- element = $(element)
- this.element = element;
- this.update = $(update);
- this.hasFocus = false;
- this.changed = false;
- this.active = false;
- this.index = 0;
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
this.entryCount = 0;
this.oldElementValue = this.element.value;
@@ -59,28 +59,28 @@ Autocompleter.Base = Class.create({
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
- this.options.onShow = this.options.onShow ||
- function(element, update){
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
- setHeight: false,
+ setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
- this.options.onHide = this.options.onHide ||
+ this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
- if(typeof(this.options.tokens) == 'string')
+ if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
// Force carriage returns as token delimiters anyway
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
-
+
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
@@ -91,10 +91,10 @@ Autocompleter.Base = Class.create({
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
- if(!this.iefix &&
+ if(!this.iefix &&
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
- new Insertion.After(this.update,
+ new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
@@ -102,7 +102,7 @@ Autocompleter.Base = Class.create({
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
-
+
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
@@ -150,15 +150,15 @@ Autocompleter.Base = Class.create({
Event.stop(event);
return;
}
- else
- if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
- this.observer =
+ this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
@@ -170,35 +170,35 @@ Autocompleter.Base = Class.create({
onHover: function(event) {
var element = Event.findElement(event, 'LI');
- if(this.index != element.autocompleteIndex)
+ if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
-
+
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
-
+
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
- this.active = false;
- },
-
+ this.active = false;
+ },
+
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
- this.index==i ?
- Element.addClassName(this.getEntry(i),"selected") :
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
- if(this.hasFocus) {
+ if(this.hasFocus) {
this.show();
this.active = true;
}
@@ -207,27 +207,27 @@ Autocompleter.Base = Class.create({
this.hide();
}
},
-
+
markPrevious: function() {
- if(this.index > 0) this.index--
+ if(this.index > 0) this.index--;
else this.index = this.entryCount-1;
this.getEntry(this.index).scrollIntoView(true);
},
-
+
markNext: function() {
- if(this.index < this.entryCount-1) this.index++
+ if(this.index < this.entryCount-1) this.index++;
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
-
+
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
-
+
getCurrentEntry: function() {
return this.getEntry(this.index);
},
-
+
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
@@ -244,7 +244,7 @@ Autocompleter.Base = Class.create({
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
-
+
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
@@ -257,7 +257,7 @@ Autocompleter.Base = Class.create({
}
this.oldElementValue = this.element.value;
this.element.focus();
-
+
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
@@ -269,20 +269,20 @@ Autocompleter.Base = Class.create({
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
- this.entryCount =
+ this.entryCount =
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
- } else {
+ } else {
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
-
+
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
@@ -298,7 +298,7 @@ Autocompleter.Base = Class.create({
},
onObserverEvent: function() {
- this.changed = false;
+ this.changed = false;
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
@@ -351,16 +351,16 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, {
getUpdatedChoices: function() {
this.startIndicator();
-
- var entry = encodeURIComponent(this.options.paramName) + '=' +
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
- if(this.options.defaultParams)
+ if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
-
+
new Ajax.Request(this.url, this.options);
},
@@ -382,7 +382,7 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, {
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
-// text only at the beginning of strings in the
+// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
@@ -399,7 +399,7 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, {
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
-// It's possible to pass in a custom function as the 'selector'
+// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
@@ -427,20 +427,20 @@ Autocompleter.Local = Class.create(Autocompleter.Base, {
var entry = instance.getToken();
var count = 0;
- for (var i = 0; i < instance.options.array.length &&
- ret.length < instance.options.choices ; i++) {
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
- var foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
- if (foundPos == 0 && elem.length != entry.length) {
- ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
+ if (foundPos == 0 && elem.length != entry.length) {
+ ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
- } else if (entry.length >= instance.options.partialChars &&
+ } else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
@@ -450,14 +450,14 @@ Autocompleter.Local = Class.create(Autocompleter.Base, {
}
}
- foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
+ foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
- ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
+ ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
@@ -474,7 +474,7 @@ Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
-}
+};
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
@@ -604,7 +604,7 @@ Ajax.InPlaceEditor = Class.create({
this.triggerCallback('onEnterHover');
},
getText: function() {
- return this.element.innerHTML;
+ return this.element.innerHTML.unescapeHTML();
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
@@ -780,7 +780,7 @@ Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
- throw 'Server returned an invalid collection representation.';
+ throw('Server returned an invalid collection representation.');
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
@@ -937,7 +937,7 @@ Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
-// Delayed observer, like Form.Element.Observer,
+// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
@@ -947,7 +947,7 @@ Form.Element.DelayedObserver = Class.create({
this.element = $(element);
this.callback = callback;
this.timer = null;
- this.lastValue = $F(this.element);
+ this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
@@ -960,4 +960,4 @@ Form.Element.DelayedObserver = Class.create({
this.timer = null;
this.callback(this.element, $F(this.element));
}
-});
+}); \ No newline at end of file
diff --git a/railties/html/javascripts/dragdrop.js b/railties/html/javascripts/dragdrop.js
index bf5cfea66c..07229f986f 100644
--- a/railties/html/javascripts/dragdrop.js
+++ b/railties/html/javascripts/dragdrop.js
@@ -1,6 +1,6 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
-//
+// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
+//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
@@ -32,7 +32,7 @@ var Droppables = {
options._containers.push($(containment));
}
}
-
+
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
@@ -40,34 +40,34 @@ var Droppables = {
this.drops.push(options);
},
-
+
findDeepestChild: function(drops) {
deepest = drops[0];
-
+
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
-
+
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
- containmentNode = element.treeNode;
+ containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
-
+
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
- (Element.classNames(element).detect(
+ (Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
@@ -87,12 +87,12 @@ var Droppables = {
show: function(point, element) {
if(!this.drops.length) return;
var drop, affected = [];
-
+
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
-
+
if(affected.length>0)
drop = Droppables.findDeepestChild(affected);
@@ -101,7 +101,7 @@ var Droppables = {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
-
+
if (drop != this.last_active) Droppables.activate(drop);
}
},
@@ -112,8 +112,8 @@ var Droppables = {
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
- this.last_active.onDrop(element, this.last_active.element, event);
- return true;
+ this.last_active.onDrop(element, this.last_active.element, event);
+ return true;
}
},
@@ -121,25 +121,25 @@ var Droppables = {
if(this.last_active)
this.deactivate(this.last_active);
}
-}
+};
var Draggables = {
drags: [],
observers: [],
-
+
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
-
+
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
-
+
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
@@ -148,24 +148,24 @@ var Draggables = {
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
-
+
activate: function(draggable) {
- if(draggable.options.delay) {
- this._timeout = setTimeout(function() {
- Draggables._timeout = null;
- window.focus();
- Draggables.activeDraggable = draggable;
- }.bind(this), draggable.options.delay);
+ if(draggable.options.delay) {
+ this._timeout = setTimeout(function() {
+ Draggables._timeout = null;
+ window.focus();
+ Draggables.activeDraggable = draggable;
+ }.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
-
+
deactivate: function() {
this.activeDraggable = null;
},
-
+
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
@@ -173,36 +173,36 @@ var Draggables = {
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
-
+
this.activeDraggable.updateDrag(event, pointer);
},
-
+
endDrag: function(event) {
- if(this._timeout) {
- clearTimeout(this._timeout);
- this._timeout = null;
+ if(this._timeout) {
+ clearTimeout(this._timeout);
+ this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
-
+
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
-
+
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
-
+
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
-
+
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
@@ -210,7 +210,7 @@ var Draggables = {
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
-
+
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
@@ -218,7 +218,7 @@ var Draggables = {
).length;
});
}
-}
+};
/*--------------------------------------------------------------------------*/
@@ -234,12 +234,12 @@ var Draggable = Class.create({
},
endeffect: function(element) {
var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
- new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
+ new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
- afterFinish: function(){
- Draggable._dragging[element] = false
+ afterFinish: function(){
+ Draggable._dragging[element] = false
}
- });
+ });
},
zindex: 1000,
revert: false,
@@ -250,57 +250,57 @@ var Draggable = Class.create({
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
-
+
if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
- new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
+ new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
-
+
var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element);
-
+
if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0);
-
+
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
-
+
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
- Element.makePositioned(this.element); // fix IE
+ Element.makePositioned(this.element); // fix IE
this.options = options;
- this.dragging = false;
+ this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
-
+
Draggables.register(this);
},
-
+
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
-
+
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
-
+
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
- if(Event.isLeftClick(event)) {
+ if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
@@ -309,34 +309,34 @@ var Draggable = Class.create({
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
-
+
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
-
+
Draggables.activate(this);
Event.stop(event);
}
},
-
+
startDrag: function(event) {
this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
-
+
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
-
+
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
- this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
- if (!this.element._originallyAbsolute)
+ this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
+ if (!this._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
-
+
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
@@ -347,28 +347,28 @@ var Draggable = Class.create({
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
-
+
Draggables.notify('onStart', this, event);
-
+
if(this.options.starteffect) this.options.starteffect(this.element);
},
-
+
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
-
+
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
-
+
Draggables.notify('onDrag', this, event);
-
+
this.draw(pointer);
if(this.options.change) this.options.change(this);
-
+
if(this.options.scroll) {
this.stopScrolling();
-
+
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
@@ -386,16 +386,16 @@ var Draggable = Class.create({
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
-
+
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
-
+
Event.stop(event);
},
-
+
finishDrag: function(event, success) {
this.dragging = false;
-
+
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
@@ -403,24 +403,24 @@ var Draggable = Class.create({
}
if(this.options.ghosting) {
- if (!this.element._originallyAbsolute)
+ if (!this._originallyAbsolute)
Position.relativize(this.element);
- delete this.element._originallyAbsolute;
+ delete this._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
- var dropped = false;
- if(success) {
- dropped = Droppables.fire(event, this.element);
- if (!dropped) dropped = false;
+ var dropped = false;
+ if(success) {
+ dropped = Droppables.fire(event, this.element);
+ if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && Object.isFunction(revert)) revert = revert(this.element);
-
+
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
@@ -433,67 +433,67 @@ var Draggable = Class.create({
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
- if(this.options.endeffect)
+ if(this.options.endeffect)
this.options.endeffect(this.element);
-
+
Draggables.deactivate(this);
Droppables.reset();
},
-
+
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
-
+
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
-
+
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
-
+
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
-
+
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
-
- var p = [0,1].map(function(i){
- return (point[i]-pos[i]-this.offset[i])
+
+ var p = [0,1].map(function(i){
+ return (point[i]-pos[i]-this.offset[i])
}.bind(this));
-
+
if(this.options.snap) {
if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this);
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
- return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
+ return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
} else {
p = p.map( function(v) {
- return (v/this.options.snap).round()*this.options.snap }.bind(this))
+ return (v/this.options.snap).round()*this.options.snap }.bind(this));
}
}}
-
+
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
-
+
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
-
+
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
@@ -501,14 +501,14 @@ var Draggable = Class.create({
Draggables._lastScrollPointer = null;
}
},
-
+
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
-
+
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
@@ -524,7 +524,7 @@ var Draggable = Class.create({
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
-
+
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
@@ -538,10 +538,10 @@ var Draggable = Class.create({
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
-
+
if(this.options.change) this.options.change(this);
},
-
+
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
@@ -560,7 +560,7 @@ var Draggable = Class.create({
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
- H = body.offsetHeight
+ H = body.offsetHeight;
}
}
return { top: T, left: L, width: W, height: H };
@@ -577,11 +577,11 @@ var SortableObserver = Class.create({
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
-
+
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
-
+
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
@@ -591,11 +591,11 @@ var SortableObserver = Class.create({
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
-
+
sortables: { },
-
+
_findRootElement: function(element) {
- while (element.tagName.toUpperCase() != "BODY") {
+ while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
@@ -606,22 +606,23 @@ var Sortable = {
if(!element) return;
return Sortable.sortables[element.id];
},
-
+
destroy: function(element){
- var s = Sortable.options(element);
-
+ element = $(element);
+ var s = Sortable.sortables[element.id];
+
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
-
+
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
- var options = Object.extend({
+ var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
@@ -635,17 +636,17 @@ var Sortable = {
delay: 0,
hoverclass: null,
ghosting: false,
- quiet: false,
+ quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
-
- // these take arrays of elements or ids and can be
+
+ // these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
-
+
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || { });
@@ -682,24 +683,24 @@ var Sortable = {
if(options.zindex)
options_for_draggable.zindex = options.zindex;
- // build options for the droppables
+ // build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
- }
-
+ };
+
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
- }
+ };
// fix for gecko engine
- Element.cleanWhitespace(element);
+ Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
@@ -712,14 +713,14 @@ var Sortable = {
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
- (options.handle ? $(e).select('.' + options.handle)[0] : e);
+ (options.handle ? $(e).select('.' + options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
- options.droppables.push(e);
+ options.droppables.push(e);
});
-
+
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
@@ -741,7 +742,7 @@ var Sortable = {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
-
+
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
@@ -758,7 +759,7 @@ var Sortable = {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
- if(dropon.parentNode!=oldParentNode)
+ if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
@@ -769,26 +770,26 @@ var Sortable = {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
- if(dropon.parentNode!=oldParentNode)
+ if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
-
+
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
-
+
if(!Element.isParent(dropon, element)) {
var index;
-
+
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
-
+
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
-
+
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
@@ -801,9 +802,9 @@ var Sortable = {
}
}
}
-
+
dropon.insertBefore(element, child);
-
+
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
@@ -816,34 +817,34 @@ var Sortable = {
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
- if(sortable && !sortable.ghosting) return;
+ if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
- Sortable._marker =
+ Sortable._marker =
($('dropmarker') || Element.extend(document.createElement('DIV'))).
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
- }
+ }
var offsets = Position.cumulativeOffset(dropon);
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
-
+
if(position=='after')
- if(sortable.overlap == 'horizontal')
+ if(sortable.overlap == 'horizontal')
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
-
+
Sortable._marker.show();
},
-
+
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
-
+
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
-
+
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
@@ -851,16 +852,16 @@ var Sortable = {
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
- }
-
+ };
+
/* Get the element containing the children and recurse over it */
if (child.container)
- this._tree(child.container, options, child)
-
+ this._tree(child.container, options, child);
+
parent.children.push (child);
}
- return parent;
+ return parent;
},
tree: function(element) {
@@ -873,15 +874,15 @@ var Sortable = {
name: element.id,
format: sortableOptions.format
}, arguments[1] || { });
-
+
var root = {
id: null,
parent: null,
children: [],
container: element,
position: 0
- }
-
+ };
+
return Sortable._tree(element, options, root);
},
@@ -897,7 +898,7 @@ var Sortable = {
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || { });
-
+
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
@@ -906,14 +907,14 @@ var Sortable = {
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || { });
-
+
var nodeMap = { };
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
-
+
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
@@ -922,16 +923,16 @@ var Sortable = {
}
});
},
-
+
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || { });
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
-
+
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
- return [name + Sortable._constructIndex(item) + "[id]=" +
+ return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
@@ -940,16 +941,16 @@ var Sortable = {
}).join('&');
}
}
-}
+};
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
-}
+};
-Element.findChildren = function(element, only, recursive, tagName) {
+Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
@@ -965,8 +966,8 @@ Element.findChildren = function(element, only, recursive, tagName) {
});
return (elements.length>0 ? elements.flatten() : []);
-}
+};
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
-}
+}; \ No newline at end of file
diff --git a/railties/html/javascripts/effects.js b/railties/html/javascripts/effects.js
index f030b5dbe9..5a639d2dea 100644
--- a/railties/html/javascripts/effects.js
+++ b/railties/html/javascripts/effects.js
@@ -3,46 +3,46 @@
// Justin Palmer (http://encytemedia.com/)
// Mark Pilgrim (http://diveintomark.org/)
// Martin Bialasinki
-//
+//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
-// For details, see the script.aculo.us web site: http://script.aculo.us/
+// For details, see the script.aculo.us web site: http://script.aculo.us/
-// converts rgb() and #xxx to #xxxxxx format,
-// returns self (or first argument) if not convertable
-String.prototype.parseColor = function() {
+// converts rgb() and #xxx to #xxxxxx format,
+// returns self (or first argument) if not convertable
+String.prototype.parseColor = function() {
var color = '#';
- if (this.slice(0,4) == 'rgb(') {
- var cols = this.slice(4,this.length-1).split(',');
- var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
- } else {
- if (this.slice(0,1) == '#') {
- if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
- if (this.length==7) color = this.toLowerCase();
- }
- }
- return (color.length==7 ? color : (arguments[0] || this));
+ if (this.slice(0,4) == 'rgb(') {
+ var cols = this.slice(4,this.length-1).split(',');
+ var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
+ } else {
+ if (this.slice(0,1) == '#') {
+ if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
+ if (this.length==7) color = this.toLowerCase();
+ }
+ }
+ return (color.length==7 ? color : (arguments[0] || this));
};
/*--------------------------------------------------------------------------*/
-Element.collectTextNodes = function(element) {
+Element.collectTextNodes = function(element) {
return $A($(element).childNodes).collect( function(node) {
- return (node.nodeType==3 ? node.nodeValue :
+ return (node.nodeType==3 ? node.nodeValue :
(node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
}).flatten().join('');
};
-Element.collectTextNodesIgnoreClass = function(element, className) {
+Element.collectTextNodesIgnoreClass = function(element, className) {
return $A($(element).childNodes).collect( function(node) {
- return (node.nodeType==3 ? node.nodeValue :
- ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
+ return (node.nodeType==3 ? node.nodeValue :
+ ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
Element.collectTextNodesIgnoreClass(node, className) : ''));
}).flatten().join('');
};
Element.setContentZoom = function(element, percent) {
- element = $(element);
- element.setStyle({fontSize: (percent/100) + 'em'});
+ element = $(element);
+ element.setStyle({fontSize: (percent/100) + 'em'});
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
return element;
};
@@ -70,28 +70,23 @@ var Effect = {
Transitions: {
linear: Prototype.K,
sinoidal: function(pos) {
- return (-Math.cos(pos*Math.PI)/2) + 0.5;
+ return (-Math.cos(pos*Math.PI)/2) + .5;
},
reverse: function(pos) {
return 1-pos;
},
flicker: function(pos) {
- var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
+ var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
return pos > 1 ? 1 : pos;
},
wobble: function(pos) {
- return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
+ return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
},
- pulse: function(pos, pulses) {
- pulses = pulses || 5;
- return (
- ((pos % (1/pulses)) * pulses).round() == 0 ?
- ((pos * pulses * 2) - (pos * pulses * 2).floor()) :
- 1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
- );
+ pulse: function(pos, pulses) {
+ return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
},
- spring: function(pos) {
- return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
+ spring: function(pos) {
+ return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
},
none: function(pos) {
return 0;
@@ -112,14 +107,14 @@ var Effect = {
tagifyText: function(element) {
var tagifyStyle = 'position:relative';
if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
-
+
element = $(element);
$A(element.childNodes).each( function(child) {
if (child.nodeType==3) {
child.nodeValue.toArray().each( function(character) {
element.insertBefore(
new Element('span', {style: tagifyStyle}).update(
- character == ' ' ? String.fromCharCode(160) : character),
+ character == ' ' ? String.fromCharCode(160) : character),
child);
});
Element.remove(child);
@@ -128,13 +123,13 @@ var Effect = {
},
multiple: function(element, effect) {
var elements;
- if (((typeof element == 'object') ||
- Object.isFunction(element)) &&
+ if (((typeof element == 'object') ||
+ Object.isFunction(element)) &&
(element.length))
elements = element;
else
elements = $(element).childNodes;
-
+
var options = Object.extend({
speed: 0.1,
delay: 0.0
@@ -156,7 +151,7 @@ var Effect = {
var options = Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
}, arguments[2] || { });
- Effect[element.visible() ?
+ Effect[element.visible() ?
Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
}
};
@@ -168,20 +163,20 @@ Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
Effect.ScopedQueue = Class.create(Enumerable, {
initialize: function() {
this.effects = [];
- this.interval = null;
+ this.interval = null;
},
_each: function(iterator) {
this.effects._each(iterator);
},
add: function(effect) {
var timestamp = new Date().getTime();
-
- var position = Object.isString(effect.options.queue) ?
+
+ var position = Object.isString(effect.options.queue) ?
effect.options.queue : effect.options.queue.position;
-
+
switch(position) {
case 'front':
- // move unstarted effects after this effect
+ // move unstarted effects after this effect
this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
e.startOn += effect.finishOn;
e.finishOn += effect.finishOn;
@@ -195,13 +190,13 @@ Effect.ScopedQueue = Class.create(Enumerable, {
timestamp = this.effects.pluck('finishOn').max() || timestamp;
break;
}
-
+
effect.startOn += timestamp;
effect.finishOn += timestamp;
if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
this.effects.push(effect);
-
+
if (!this.interval)
this.interval = setInterval(this.loop.bind(this), 15);
},
@@ -214,7 +209,7 @@ Effect.ScopedQueue = Class.create(Enumerable, {
},
loop: function() {
var timePos = new Date().getTime();
- for(var i=0, len=this.effects.length;i<len;i++)
+ for(var i=0, len=this.effects.length;i<len;i++)
this.effects[i] && this.effects[i].loop(timePos);
}
});
@@ -223,7 +218,7 @@ Effect.Queues = {
instances: $H(),
get: function(queueName) {
if (!Object.isString(queueName)) return queueName;
-
+
return this.instances.get(queueName) ||
this.instances.set(queueName, new Effect.ScopedQueue());
}
@@ -248,23 +243,35 @@ Effect.Base = Class.create({
this.fromToDelta = this.options.to-this.options.from;
this.totalTime = this.finishOn-this.startOn;
this.totalFrames = this.options.fps*this.options.duration;
-
- eval('this.render = function(pos){ '+
- 'if (this.state=="idle"){this.state="running";'+
- codeForEvent(this.options,'beforeSetup')+
- (this.setup ? 'this.setup();':'')+
- codeForEvent(this.options,'afterSetup')+
- '};if (this.state=="running"){'+
- 'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
- 'this.position=pos;'+
- codeForEvent(this.options,'beforeUpdate')+
- (this.update ? 'this.update(pos);':'')+
- codeForEvent(this.options,'afterUpdate')+
- '}}');
-
+
+ this.render = (function() {
+ function dispatch(effect, eventName) {
+ if (effect.options[eventName + 'Internal'])
+ effect.options[eventName + 'Internal'](effect);
+ if (effect.options[eventName])
+ effect.options[eventName](effect);
+ }
+
+ return function(pos) {
+ if (this.state === "idle") {
+ this.state = "running";
+ dispatch(this, 'beforeSetup');
+ if (this.setup) this.setup();
+ dispatch(this, 'afterSetup');
+ }
+ if (this.state === "running") {
+ pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
+ this.position = pos;
+ dispatch(this, 'beforeUpdate');
+ if (this.update) this.update(pos);
+ dispatch(this, 'afterUpdate');
+ }
+ };
+ })();
+
this.event('beforeStart');
if (!this.options.sync)
- Effect.Queues.get(Object.isString(this.options.queue) ?
+ Effect.Queues.get(Object.isString(this.options.queue) ?
'global' : this.options.queue.scope).add(this);
},
loop: function(timePos) {
@@ -273,9 +280,9 @@ Effect.Base = Class.create({
this.render(1.0);
this.cancel();
this.event('beforeFinish');
- if (this.finish) this.finish();
+ if (this.finish) this.finish();
this.event('afterFinish');
- return;
+ return;
}
var pos = (timePos - this.startOn) / this.totalTime,
frame = (pos * this.totalFrames).round();
@@ -287,7 +294,7 @@ Effect.Base = Class.create({
},
cancel: function() {
if (!this.options.sync)
- Effect.Queues.get(Object.isString(this.options.queue) ?
+ Effect.Queues.get(Object.isString(this.options.queue) ?
'global' : this.options.queue.scope).remove(this);
this.state = 'finished';
},
@@ -325,10 +332,10 @@ Effect.Parallel = Class.create(Effect.Base, {
Effect.Tween = Class.create(Effect.Base, {
initialize: function(object, from, to) {
object = Object.isString(object) ? $(object) : object;
- var args = $A(arguments), method = args.last(),
+ var args = $A(arguments), method = args.last(),
options = args.length == 5 ? args[3] : null;
this.method = Object.isFunction(method) ? method.bind(object) :
- Object.isFunction(object[method]) ? object[method].bind(object) :
+ Object.isFunction(object[method]) ? object[method].bind(object) :
function(value) { object[method] = value };
this.start(Object.extend({ from: from, to: to }, options || { }));
},
@@ -392,7 +399,7 @@ Effect.Move = Class.create(Effect.Base, {
// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
- return new Effect.Move(element,
+ return new Effect.Move(element,
Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
};
@@ -414,15 +421,15 @@ Effect.Scale = Class.create(Effect.Base, {
setup: function() {
this.restoreAfterFinish = this.options.restoreAfterFinish || false;
this.elementPositioning = this.element.getStyle('position');
-
+
this.originalStyle = { };
['top','left','width','height','fontSize'].each( function(k) {
this.originalStyle[k] = this.element.style[k];
}.bind(this));
-
+
this.originalTop = this.element.offsetTop;
this.originalLeft = this.element.offsetLeft;
-
+
var fontSize = this.element.getStyle('font-size') || '100%';
['em','px','%','pt'].each( function(fontSizeType) {
if (fontSize.indexOf(fontSizeType)>0) {
@@ -430,9 +437,9 @@ Effect.Scale = Class.create(Effect.Base, {
this.fontSizeType = fontSizeType;
}
}.bind(this));
-
+
this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
-
+
this.dims = null;
if (this.options.scaleMode=='box')
this.dims = [this.element.offsetHeight, this.element.offsetWidth];
@@ -507,17 +514,16 @@ Effect.Highlight = Class.create(Effect.Base, {
Effect.ScrollTo = function(element) {
var options = arguments[1] || { },
- scrollOffsets = document.viewport.getScrollOffsets(),
- elementOffsets = $(element).cumulativeOffset(),
- max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();
+ scrollOffsets = document.viewport.getScrollOffsets(),
+ elementOffsets = $(element).cumulativeOffset();
if (options.offset) elementOffsets[1] += options.offset;
return new Effect.Tween(null,
scrollOffsets.top,
- elementOffsets[1] > max ? max : elementOffsets[1],
+ elementOffsets[1],
options,
- function(p){ scrollTo(scrollOffsets.left, p.round()) }
+ function(p){ scrollTo(scrollOffsets.left, p.round()); }
);
};
@@ -529,9 +535,9 @@ Effect.Fade = function(element) {
var options = Object.extend({
from: element.getOpacity() || 1.0,
to: 0.0,
- afterFinishInternal: function(effect) {
+ afterFinishInternal: function(effect) {
if (effect.options.to!=0) return;
- effect.element.hide().setStyle({opacity: oldOpacity});
+ effect.element.hide().setStyle({opacity: oldOpacity});
}
}, arguments[1] || { });
return new Effect.Opacity(element,options);
@@ -547,15 +553,15 @@ Effect.Appear = function(element) {
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
- effect.element.setOpacity(effect.options.from).show();
+ effect.element.setOpacity(effect.options.from).show();
}}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
Effect.Puff = function(element) {
element = $(element);
- var oldStyle = {
- opacity: element.getInlineOpacity(),
+ var oldStyle = {
+ opacity: element.getInlineOpacity(),
position: element.getStyle('position'),
top: element.style.top,
left: element.style.left,
@@ -563,12 +569,12 @@ Effect.Puff = function(element) {
height: element.style.height
};
return new Effect.Parallel(
- [ new Effect.Scale(element, 200,
- { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
- new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
- Object.extend({ duration: 1.0,
+ [ new Effect.Scale(element, 200,
+ { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
+ new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
+ Object.extend({ duration: 1.0,
beforeSetupInternal: function(effect) {
- Position.absolutize(effect.effects[0].element)
+ Position.absolutize(effect.effects[0].element);
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().setStyle(oldStyle); }
@@ -580,12 +586,12 @@ Effect.BlindUp = function(element) {
element = $(element);
element.makeClipping();
return new Effect.Scale(element, 0,
- Object.extend({ scaleContent: false,
- scaleX: false,
+ Object.extend({ scaleContent: false,
+ scaleX: false,
restoreAfterFinish: true,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping();
- }
+ }
}, arguments[1] || { })
);
};
@@ -593,15 +599,15 @@ Effect.BlindUp = function(element) {
Effect.BlindDown = function(element) {
element = $(element);
var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, 100, Object.extend({
- scaleContent: false,
+ return new Effect.Scale(element, 100, Object.extend({
+ scaleContent: false,
scaleX: false,
scaleFrom: 0,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
- effect.element.makeClipping().setStyle({height: '0px'}).show();
- },
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
afterFinishInternal: function(effect) {
effect.element.undoClipping();
}
@@ -616,16 +622,16 @@ Effect.SwitchOff = function(element) {
from: 0,
transition: Effect.Transitions.flicker,
afterFinishInternal: function(effect) {
- new Effect.Scale(effect.element, 1, {
+ new Effect.Scale(effect.element, 1, {
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
- beforeSetup: function(effect) {
+ beforeSetup: function(effect) {
effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
- })
+ });
}
}, arguments[1] || { }));
};
@@ -637,16 +643,16 @@ Effect.DropOut = function(element) {
left: element.getStyle('left'),
opacity: element.getInlineOpacity() };
return new Effect.Parallel(
- [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
+ [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
Object.extend(
{ duration: 0.5,
beforeSetup: function(effect) {
- effect.effects[0].element.makePositioned();
+ effect.effects[0].element.makePositioned();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
- }
+ }
}, arguments[1] || { }));
};
@@ -674,7 +680,7 @@ Effect.Shake = function(element) {
new Effect.Move(effect.element,
{ x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
effect.element.undoPositioned().setStyle(oldStyle);
- }}) }}) }}) }}) }}) }});
+ }}); }}); }}); }}); }}); }});
};
Effect.SlideDown = function(element) {
@@ -682,9 +688,9 @@ Effect.SlideDown = function(element) {
// SlideDown need to have the content of the element wrapped in a container element with fixed height!
var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, 100, Object.extend({
- scaleContent: false,
- scaleX: false,
+ return new Effect.Scale(element, 100, Object.extend({
+ scaleContent: false,
+ scaleX: false,
scaleFrom: window.opera ? 0 : 1,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
@@ -692,11 +698,11 @@ Effect.SlideDown = function(element) {
effect.element.makePositioned();
effect.element.down().makePositioned();
if (window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping().setStyle({height: '0px'}).show();
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
},
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
- (effect.dims[0] - effect.element.clientHeight) + 'px' });
+ (effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
effect.element.undoClipping().undoPositioned();
@@ -710,8 +716,8 @@ Effect.SlideUp = function(element) {
var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, window.opera ? 0 : 1,
- Object.extend({ scaleContent: false,
- scaleX: false,
+ Object.extend({ scaleContent: false,
+ scaleX: false,
scaleMode: 'box',
scaleFrom: 100,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
@@ -721,7 +727,7 @@ Effect.SlideUp = function(element) {
effect.element.down().makePositioned();
if (window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping().show();
- },
+ },
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
@@ -734,15 +740,15 @@ Effect.SlideUp = function(element) {
);
};
-// Bug in opera makes the TD containing this element expand for a instance after finish
+// Bug in opera makes the TD containing this element expand for a instance after finish
Effect.Squish = function(element) {
- return new Effect.Scale(element, window.opera ? 1 : 0, {
+ return new Effect.Scale(element, window.opera ? 1 : 0, {
restoreAfterFinish: true,
beforeSetup: function(effect) {
- effect.element.makeClipping();
- },
+ effect.element.makeClipping();
+ },
afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping();
+ effect.element.hide().undoClipping();
}
});
};
@@ -762,13 +768,13 @@ Effect.Grow = function(element) {
width: element.style.width,
opacity: element.getInlineOpacity() };
- var dims = element.getDimensions();
+ var dims = element.getDimensions();
var initialMoveX, initialMoveY;
var moveX, moveY;
-
+
switch (options.direction) {
case 'top-left':
- initialMoveX = initialMoveY = moveX = moveY = 0;
+ initialMoveX = initialMoveY = moveX = moveY = 0;
break;
case 'top-right':
initialMoveX = dims.width;
@@ -793,11 +799,11 @@ Effect.Grow = function(element) {
moveY = -dims.height / 2;
break;
}
-
+
return new Effect.Move(element, {
x: initialMoveX,
y: initialMoveY,
- duration: 0.01,
+ duration: 0.01,
beforeSetup: function(effect) {
effect.element.hide().makeClipping().makePositioned();
},
@@ -806,17 +812,17 @@ Effect.Grow = function(element) {
[ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
new Effect.Scale(effect.element, 100, {
- scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
+ scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
], Object.extend({
beforeSetup: function(effect) {
- effect.effects[0].element.setStyle({height: '0px'}).show();
+ effect.effects[0].element.setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
- effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
+ effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
}
}, options)
- )
+ );
}
});
};
@@ -838,7 +844,7 @@ Effect.Shrink = function(element) {
var dims = element.getDimensions();
var moveX, moveY;
-
+
switch (options.direction) {
case 'top-left':
moveX = moveY = 0;
@@ -855,19 +861,19 @@ Effect.Shrink = function(element) {
moveX = dims.width;
moveY = dims.height;
break;
- case 'center':
+ case 'center':
moveX = dims.width / 2;
moveY = dims.height / 2;
break;
}
-
+
return new Effect.Parallel(
[ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
- ], Object.extend({
+ ], Object.extend({
beforeStartInternal: function(effect) {
- effect.effects[0].element.makePositioned().makeClipping();
+ effect.effects[0].element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
@@ -877,12 +883,14 @@ Effect.Shrink = function(element) {
Effect.Pulsate = function(element) {
element = $(element);
- var options = arguments[1] || { };
- var oldOpacity = element.getInlineOpacity();
- var transition = options.transition || Effect.Transitions.sinoidal;
- var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
- reverser.bind(transition);
- return new Effect.Opacity(element,
+ var options = arguments[1] || { },
+ oldOpacity = element.getInlineOpacity(),
+ transition = options.transition || Effect.Transitions.linear,
+ reverser = function(pos){
+ return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
+ };
+
+ return new Effect.Opacity(element,
Object.extend(Object.extend({ duration: 2.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
}, options), {transition: reverser}));
@@ -896,12 +904,12 @@ Effect.Fold = function(element) {
width: element.style.width,
height: element.style.height };
element.makeClipping();
- return new Effect.Scale(element, 5, Object.extend({
+ return new Effect.Scale(element, 5, Object.extend({
scaleContent: false,
scaleX: false,
afterFinishInternal: function(effect) {
- new Effect.Scale(element, 1, {
- scaleContent: false,
+ new Effect.Scale(element, 1, {
+ scaleContent: false,
scaleY: false,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().setStyle(oldStyle);
@@ -916,7 +924,7 @@ Effect.Morph = Class.create(Effect.Base, {
var options = Object.extend({
style: { }
}, arguments[1] || { });
-
+
if (!Object.isString(options.style)) this.style = $H(options.style);
else {
if (options.style.include(':'))
@@ -934,18 +942,18 @@ Effect.Morph = Class.create(Effect.Base, {
effect.transforms.each(function(transform) {
effect.element.style[transform.style] = '';
});
- }
+ };
}
}
this.start(options);
},
-
+
setup: function(){
function parseColor(color){
if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
color = color.parseColor();
return $R(0,2).map(function(i){
- return parseInt( color.slice(i*2+1,i*2+3), 16 )
+ return parseInt( color.slice(i*2+1,i*2+3), 16 );
});
}
this.transforms = this.style.map(function(pair){
@@ -965,9 +973,9 @@ Effect.Morph = Class.create(Effect.Base, {
}
var originalValue = this.element.getStyle(property);
- return {
- style: property.camelize(),
- originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
+ return {
+ style: property.camelize(),
+ originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
targetValue: unit=='color' ? parseColor(value) : value,
unit: unit
};
@@ -978,13 +986,13 @@ Effect.Morph = Class.create(Effect.Base, {
transform.unit != 'color' &&
(isNaN(transform.originalValue) || isNaN(transform.targetValue))
)
- )
+ );
});
},
update: function(position) {
var style = { }, transform, i = this.transforms.length;
while(i--)
- style[(transform = this.transforms[i]).style] =
+ style[(transform = this.transforms[i]).style] =
transform.unit=='color' ? '#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
@@ -993,7 +1001,7 @@ Effect.Morph = Class.create(Effect.Base, {
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
(transform.originalValue +
- (transform.targetValue - transform.originalValue) * position).toFixed(3) +
+ (transform.targetValue - transform.originalValue) * position).toFixed(3) +
(transform.unit === null ? '' : transform.unit);
this.element.setStyle(style, true);
}
@@ -1030,7 +1038,7 @@ Effect.Transform = Class.create({
});
Element.CSS_PROPERTIES = $w(
- 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
+ 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
@@ -1039,7 +1047,7 @@ Element.CSS_PROPERTIES = $w(
'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
'right textIndent top width wordSpacing zIndex');
-
+
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
String.__parseStyleElement = document.createElement('div');
@@ -1051,11 +1059,11 @@ String.prototype.parseStyle = function(){
String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
style = String.__parseStyleElement.childNodes[0].style;
}
-
+
Element.CSS_PROPERTIES.each(function(property){
- if (style[property]) styleRules.set(property, style[property]);
+ if (style[property]) styleRules.set(property, style[property]);
});
-
+
if (Prototype.Browser.IE && this.include('opacity'))
styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
@@ -1074,14 +1082,14 @@ if (document.defaultView && document.defaultView.getComputedStyle) {
Element.getStyles = function(element) {
element = $(element);
var css = element.currentStyle, styles;
- styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) {
- hash.set(property, css[property]);
- return hash;
+ styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
+ results[property] = css[property];
+ return results;
});
- if (!styles.opacity) styles.set('opacity', element.getOpacity());
+ if (!styles.opacity) styles.opacity = element.getOpacity();
return styles;
};
-};
+}
Effect.Methods = {
morph: function(element, style) {
@@ -1090,7 +1098,7 @@ Effect.Methods = {
return element;
},
visualEffect: function(element, effect, options) {
- element = $(element)
+ element = $(element);
var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
new Effect[klass](element, options);
return element;
@@ -1104,17 +1112,17 @@ Effect.Methods = {
$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
'pulsate shake puff squish switchOff dropOut').each(
- function(effect) {
+ function(effect) {
Effect.Methods[effect] = function(element, options){
element = $(element);
Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
return element;
- }
+ };
}
);
-$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
+$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
function(f) { Effect.Methods[f] = Element[f]; }
);
-Element.addMethods(Effect.Methods);
+Element.addMethods(Effect.Methods); \ No newline at end of file
diff --git a/railties/lib/commands/process/inspector.rb b/railties/lib/commands/process/inspector.rb
deleted file mode 100644
index 8a6437e715..0000000000
--- a/railties/lib/commands/process/inspector.rb
+++ /dev/null
@@ -1,68 +0,0 @@
-require 'optparse'
-
-if RUBY_PLATFORM =~ /(:?mswin|mingw)/ then abort("Inspector is only for Unix") end
-
-OPTIONS = {
- :pid_path => File.expand_path(RAILS_ROOT + '/tmp/pids'),
- :pattern => "dispatch.*.pid",
- :ps => "ps -o pid,state,user,start,time,pcpu,vsz,majflt,command -p %s"
-}
-
-class Inspector
- def self.inspect(pid_path, pattern)
- new(pid_path, pattern).inspect
- end
-
- def initialize(pid_path, pattern)
- @pid_path, @pattern = pid_path, pattern
- end
-
- def inspect
- header = `#{OPTIONS[:ps] % 1}`.split("\n")[0] + "\n"
- lines = pids.collect { |pid| `#{OPTIONS[:ps] % pid}`.split("\n")[1] }
-
- puts(header + lines.join("\n"))
- end
-
- private
- def pids
- pid_files.collect do |pid_file|
- File.read(pid_file).to_i
- end
- end
-
- def pid_files
- Dir.glob(@pid_path + "/" + @pattern)
- end
-end
-
-
-ARGV.options do |opts|
- opts.banner = "Usage: inspector [options]"
-
- opts.separator ""
-
- opts.on <<-EOF
- Description:
- Displays system information about Rails dispatchers (or other processes that use pid files) through
- the ps command.
-
- Examples:
- inspector # default ps on all tmp/pids/dispatch.*.pid files
- inspector -s 'ps -o user,start,majflt,pcpu,vsz -p %s' # custom ps, %s is where the pid is interleaved
- EOF
-
- opts.on(" Options:")
-
- opts.on("-s", "--ps=command", "default: #{OPTIONS[:ps]}", String) { |v| OPTIONS[:ps] = v }
- opts.on("-p", "--pidpath=path", "default: #{OPTIONS[:pid_path]}", String) { |v| OPTIONS[:pid_path] = v }
- opts.on("-r", "--pattern=pattern", "default: #{OPTIONS[:pattern]}", String) { |v| OPTIONS[:pattern] = v }
-
- opts.separator ""
-
- opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
-
- opts.parse!
-end
-
-Inspector.inspect(OPTIONS[:pid_path], OPTIONS[:pattern])
diff --git a/railties/lib/commands/process/reaper.rb b/railties/lib/commands/process/reaper.rb
deleted file mode 100644
index 95175d41e0..0000000000
--- a/railties/lib/commands/process/reaper.rb
+++ /dev/null
@@ -1,149 +0,0 @@
-require 'optparse'
-require 'net/http'
-require 'uri'
-
-if RUBY_PLATFORM =~ /(:?mswin|mingw)/ then abort("Reaper is only for Unix") end
-
-class Killer
- class << self
- # Searches for all processes matching the given keywords, and then invokes
- # a specific action on each of them. This is useful for (e.g.) reloading a
- # set of processes:
- #
- # Killer.process(:reload, "/tmp/pids", "dispatcher.*.pid")
- def process(action, pid_path, pattern, keyword)
- new(pid_path, pattern, keyword).process(action)
- end
-
- # Forces the (rails) application to reload by sending a +HUP+ signal to the
- # process.
- def reload(pid)
- `kill -s HUP #{pid}`
- end
-
- # Force the (rails) application to restart by sending a +USR2+ signal to the
- # process.
- def restart(pid)
- `kill -s USR2 #{pid}`
- end
-
- # Forces the (rails) application to gracefully terminate by sending a
- # +TERM+ signal to the process.
- def graceful(pid)
- `kill -s TERM #{pid}`
- end
-
- # Forces the (rails) application to terminate immediately by sending a -9
- # signal to the process.
- def kill(pid)
- `kill -9 #{pid}`
- end
-
- # Send a +USR1+ signal to the process.
- def usr1(pid)
- `kill -s USR1 #{pid}`
- end
- end
-
- def initialize(pid_path, pattern, keyword=nil)
- @pid_path, @pattern, @keyword = pid_path, pattern, keyword
- end
-
- def process(action)
- pids = find_processes
-
- if pids.empty?
- warn "Couldn't find any pid file in '#{@pid_path}' matching '#{@pattern}'"
- warn "(also looked for processes matching #{@keyword.inspect})" if @keyword
- else
- pids.each do |pid|
- puts "#{action.capitalize}ing #{pid}"
- self.class.send(action, pid)
- end
-
- delete_pid_files if terminating?(action)
- end
- end
-
- private
- def terminating?(action)
- [ "kill", "graceful" ].include?(action)
- end
-
- def find_processes
- files = pid_files
- if files.empty?
- find_processes_via_grep
- else
- files.collect { |pid_file| File.read(pid_file).to_i }
- end
- end
-
- def find_processes_via_grep
- lines = `ps axww -o 'pid command' | grep #{@keyword}`.split(/\n/).
- reject { |line| line =~ /inq|ps axww|grep|spawn-fcgi|spawner|reaper/ }
- lines.map { |line| line[/^\s*(\d+)/, 1].to_i }
- end
-
- def delete_pid_files
- pid_files.each { |pid_file| File.delete(pid_file) }
- end
-
- def pid_files
- Dir.glob(@pid_path + "/" + @pattern)
- end
-end
-
-
-OPTIONS = {
- :action => "restart",
- :pid_path => File.expand_path(RAILS_ROOT + '/tmp/pids'),
- :pattern => "dispatch.[0-9]*.pid",
- :dispatcher => File.expand_path("#{RAILS_ROOT}/public/dispatch.fcgi")
-}
-
-ARGV.options do |opts|
- opts.banner = "Usage: reaper [options]"
-
- opts.separator ""
-
- opts.on <<-EOF
- Description:
- The reaper is used to restart, reload, gracefully exit, and forcefully exit processes
- running a Rails Dispatcher (or any other process responding to the same signals). This
- is commonly done when a new version of the application is available, so the existing
- processes can be updated to use the latest code.
-
- It uses pid files to work on the processes and by default assume them to be located
- in RAILS_ROOT/tmp/pids.
-
- The reaper actions are:
-
- * restart : Restarts the application by reloading both application and framework code
- * reload : Only reloads the application, but not the framework (like the development environment)
- * graceful: Marks all of the processes for exit after the next request
- * kill : Forcefully exists all processes regardless of whether they're currently serving a request
-
- Restart is the most common and default action.
-
- Examples:
- reaper # restarts the default dispatchers
- reaper -a reload # reload the default dispatchers
- reaper -a kill -r *.pid # kill all processes that keep pids in tmp/pids
- EOF
-
- opts.on(" Options:")
-
- opts.on("-a", "--action=name", "reload|graceful|kill (default: #{OPTIONS[:action]})", String) { |v| OPTIONS[:action] = v }
- opts.on("-p", "--pidpath=path", "default: #{OPTIONS[:pid_path]}", String) { |v| OPTIONS[:pid_path] = v }
- opts.on("-r", "--pattern=pattern", "default: #{OPTIONS[:pattern]}", String) { |v| OPTIONS[:pattern] = v }
- opts.on("-d", "--dispatcher=path", "DEPRECATED. default: #{OPTIONS[:dispatcher]}", String) { |v| OPTIONS[:dispatcher] = v }
-
- opts.separator ""
-
- opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
-
- opts.parse!
-end
-
-Killer.process(OPTIONS[:action], OPTIONS[:pid_path], OPTIONS[:pattern], OPTIONS[:dispatcher])
diff --git a/railties/lib/commands/process/spawner.rb b/railties/lib/commands/process/spawner.rb
deleted file mode 100644
index 8bf47abb75..0000000000
--- a/railties/lib/commands/process/spawner.rb
+++ /dev/null
@@ -1,219 +0,0 @@
-require 'active_support'
-require 'optparse'
-require 'socket'
-require 'fileutils'
-
-def daemonize #:nodoc:
- exit if fork # Parent exits, child continues.
- Process.setsid # Become session leader.
- exit if fork # Zap session leader. See [1].
- Dir.chdir "/" # Release old working directory.
- File.umask 0000 # Ensure sensible umask. Adjust as needed.
- STDIN.reopen "/dev/null" # Free file descriptors and
- STDOUT.reopen "/dev/null", "a" # point them somewhere sensible.
- STDERR.reopen STDOUT # STDOUT/ERR should better go to a logfile.
-end
-
-class Spawner
- def self.record_pid(name = "#{OPTIONS[:process]}.spawner", id = Process.pid)
- FileUtils.mkdir_p(OPTIONS[:pids])
- File.open(File.expand_path(OPTIONS[:pids] + "/#{name}.pid"), "w+") { |f| f.write(id) }
- end
-
- def self.spawn_all
- OPTIONS[:instances].times do |i|
- port = OPTIONS[:port] + i
- print "Checking if something is already running on #{OPTIONS[:address]}:#{port}..."
-
- begin
- srv = TCPServer.new(OPTIONS[:address], port)
- srv.close
- srv = nil
-
- puts "NO"
- puts "Starting dispatcher on port: #{OPTIONS[:address]}:#{port}"
-
- FileUtils.mkdir_p(OPTIONS[:pids])
- spawn(port)
- rescue
- puts "YES"
- end
- end
- end
-end
-
-class FcgiSpawner < Spawner
- def self.spawn(port)
- cmd = "#{OPTIONS[:spawner]} -f #{OPTIONS[:dispatcher]} -p #{port} -P #{OPTIONS[:pids]}/#{OPTIONS[:process]}.#{port}.pid"
- cmd << " -a #{OPTIONS[:address]}" if can_bind_to_custom_address?
- system(cmd)
- end
-
- def self.can_bind_to_custom_address?
- @@can_bind_to_custom_address ||= /^\s-a\s/.match `#{OPTIONS[:spawner]} -h`
- end
-end
-
-class MongrelSpawner < Spawner
- def self.spawn(port)
- cmd =
- "mongrel_rails start -d " +
- "-a #{OPTIONS[:address]} " +
- "-p #{port} " +
- "-P #{OPTIONS[:pids]}/#{OPTIONS[:process]}.#{port}.pid " +
- "-e #{OPTIONS[:environment]} " +
- "-c #{OPTIONS[:rails_root]} " +
- "-l #{OPTIONS[:rails_root]}/log/mongrel.log"
-
- # Add prefix functionality to spawner's call to mongrel_rails
- # Digging through mongrel's project subversion server, the earliest
- # Tag that has prefix implemented in the bin/mongrel_rails file
- # is 0.3.15 which also happens to be the earliest tag listed.
- # References: http://mongrel.rubyforge.org/svn/tags
- if Mongrel::Const::MONGREL_VERSION.to_f >=0.3 && !OPTIONS[:prefix].nil?
- cmd = cmd + " --prefix #{OPTIONS[:prefix]}"
- end
- system(cmd)
- end
-
- def self.can_bind_to_custom_address?
- true
- end
-end
-
-
-begin
- require_library_or_gem 'fcgi'
-rescue Exception
- # FCGI not available
-end
-
-begin
- require_library_or_gem 'mongrel'
-rescue Exception
- # Mongrel not available
-end
-
-server = case ARGV.first
- when "fcgi", "mongrel"
- ARGV.shift
- else
- if defined?(Mongrel)
- "mongrel"
- elsif RUBY_PLATFORM !~ /(:?mswin|mingw)/ && !silence_stderr { `spawn-fcgi -version` }.blank? && defined?(FCGI)
- "fcgi"
- end
-end
-
-case server
- when "fcgi"
- puts "=> Starting FCGI dispatchers"
- spawner_class = FcgiSpawner
- when "mongrel"
- puts "=> Starting mongrel dispatchers"
- spawner_class = MongrelSpawner
- else
- puts "Neither FCGI (spawn-fcgi) nor Mongrel was installed and available!"
- exit(0)
-end
-
-
-
-OPTIONS = {
- :environment => "production",
- :spawner => '/usr/bin/env spawn-fcgi',
- :dispatcher => File.expand_path(RELATIVE_RAILS_ROOT + '/public/dispatch.fcgi'),
- :pids => File.expand_path(RELATIVE_RAILS_ROOT + "/tmp/pids"),
- :rails_root => File.expand_path(RELATIVE_RAILS_ROOT),
- :process => "dispatch",
- :port => 8000,
- :address => '0.0.0.0',
- :instances => 3,
- :repeat => nil,
- :prefix => nil
-}
-
-ARGV.options do |opts|
- opts.banner = "Usage: spawner [platform] [options]"
-
- opts.separator ""
-
- opts.on <<-EOF
- Description:
- The spawner is a wrapper for spawn-fcgi and mongrel that makes it
- easier to start multiple processes running the Rails dispatcher. The
- spawn-fcgi command is included with the lighttpd web server, but can
- be used with both Apache and lighttpd (and any other web server
- supporting externally managed FCGI processes). Mongrel automatically
- ships with with mongrel_rails for starting dispatchers.
-
- The first choice you need to make is whether to spawn the Rails
- dispatchers as FCGI or Mongrel. By default, this spawner will prefer
- Mongrel, so if that's installed, and no platform choice is made,
- Mongrel is used.
-
- Then decide a starting port (default is 8000) and the number of FCGI
- process instances you'd like to run. So if you pick 9100 and 3
- instances, you'll start processes on 9100, 9101, and 9102.
-
- By setting the repeat option, you get a protection loop, which will
- attempt to restart any FCGI processes that might have been exited or
- outright crashed.
-
- You can select bind address for started processes. By default these
- listen on every interface. For single machine installations you would
- probably want to use 127.0.0.1, hiding them form the outside world.
-
- Examples:
- spawner # starts instances on 8000, 8001, and 8002
- # using Mongrel if available.
- spawner fcgi # starts instances on 8000, 8001, and 8002
- # using FCGI.
- spawner mongrel -i 5 # starts instances on 8000, 8001, 8002,
- # 8003, and 8004 using Mongrel.
- spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to
- # 9109 using Mongrel if available.
- spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to
- # 9102 and attempts start them every 5
- # seconds.
- spawner -a 127.0.0.1 # starts 3 instances binding to localhost
- EOF
-
- opts.on(" Options:")
-
- opts.on("-p", "--port=number", Integer, "Starting port number (default: #{OPTIONS[:port]})") { |v| OPTIONS[:port] = v }
-
- if spawner_class.can_bind_to_custom_address?
- opts.on("-a", "--address=ip", String, "Bind to IP address (default: #{OPTIONS[:address]})") { |v| OPTIONS[:address] = v }
- end
-
- opts.on("-p", "--port=number", Integer, "Starting port number (default: #{OPTIONS[:port]})") { |v| OPTIONS[:port] = v }
- opts.on("-i", "--instances=number", Integer, "Number of instances (default: #{OPTIONS[:instances]})") { |v| OPTIONS[:instances] = v }
- opts.on("-r", "--repeat=seconds", Integer, "Repeat spawn attempts every n seconds (default: off)") { |v| OPTIONS[:repeat] = v }
- opts.on("-e", "--environment=name", String, "test|development|production (default: #{OPTIONS[:environment]})") { |v| OPTIONS[:environment] = v }
- opts.on("-P", "--prefix=path", String, "URL prefix for Rails app. [Used only with Mongrel > v0.3.15]: (default: #{OPTIONS[:prefix]})") { |v| OPTIONS[:prefix] = v }
- opts.on("-n", "--process=name", String, "default: #{OPTIONS[:process]}") { |v| OPTIONS[:process] = v }
- opts.on("-s", "--spawner=path", String, "default: #{OPTIONS[:spawner]}") { |v| OPTIONS[:spawner] = v }
- opts.on("-d", "--dispatcher=path", String, "default: #{OPTIONS[:dispatcher]}") { |dispatcher| OPTIONS[:dispatcher] = File.expand_path(dispatcher) }
-
- opts.separator ""
-
- opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
-
- opts.parse!
-end
-
-ENV["RAILS_ENV"] = OPTIONS[:environment]
-
-if OPTIONS[:repeat]
- daemonize
- trap("TERM") { exit }
- spawner_class.record_pid
-
- loop do
- spawner_class.spawn_all
- sleep(OPTIONS[:repeat])
- end
-else
- spawner_class.spawn_all
-end
diff --git a/railties/lib/commands/process/spinner.rb b/railties/lib/commands/process/spinner.rb
deleted file mode 100644
index c0b2f09a94..0000000000
--- a/railties/lib/commands/process/spinner.rb
+++ /dev/null
@@ -1,57 +0,0 @@
-require 'optparse'
-
-def daemonize #:nodoc:
- exit if fork # Parent exits, child continues.
- Process.setsid # Become session leader.
- exit if fork # Zap session leader. See [1].
- Dir.chdir "/" # Release old working directory.
- File.umask 0000 # Ensure sensible umask. Adjust as needed.
- STDIN.reopen "/dev/null" # Free file descriptors and
- STDOUT.reopen "/dev/null", "a" # point them somewhere sensible.
- STDERR.reopen STDOUT # STDOUT/ERR should better go to a logfile.
-end
-
-OPTIONS = {
- :interval => 5.0,
- :command => File.expand_path(RAILS_ROOT + '/script/process/spawner'),
- :daemon => false
-}
-
-ARGV.options do |opts|
- opts.banner = "Usage: spinner [options]"
-
- opts.separator ""
-
- opts.on <<-EOF
- Description:
- The spinner is a protection loop for the spawner, which will attempt to restart any FCGI processes
- that might have been exited or outright crashed. It's a brute-force attempt that'll just try
- to run the spawner every X number of seconds, so it does pose a light load on the server.
-
- Examples:
- spinner # attempts to run the spawner with default settings every second with output on the terminal
- spinner -i 3 -d # only run the spawner every 3 seconds and detach from the terminal to become a daemon
- spinner -c '/path/to/app/script/process/spawner -p 9000 -i 10' -d # using custom spawner
- EOF
-
- opts.on(" Options:")
-
- opts.on("-c", "--command=path", String) { |v| OPTIONS[:command] = v }
- opts.on("-i", "--interval=seconds", Float) { |v| OPTIONS[:interval] = v }
- opts.on("-d", "--daemon") { |v| OPTIONS[:daemon] = v }
-
- opts.separator ""
-
- opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
-
- opts.parse!
-end
-
-daemonize if OPTIONS[:daemon]
-
-trap(OPTIONS[:daemon] ? "TERM" : "INT") { exit }
-
-loop do
- system(OPTIONS[:command])
- sleep(OPTIONS[:interval])
-end \ No newline at end of file
diff --git a/railties/lib/commands/runner.rb b/railties/lib/commands/runner.rb
index 14159c3893..2411c3d270 100644
--- a/railties/lib/commands/runner.rb
+++ b/railties/lib/commands/runner.rb
@@ -38,11 +38,15 @@ RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV)
require RAILS_ROOT + '/config/environment'
-if code_or_file.nil?
- $stderr.puts "Run '#{$0} -h' for help."
- exit 1
-elsif File.exist?(code_or_file)
- eval(File.read(code_or_file), nil, code_or_file)
-else
- eval(code_or_file)
+begin
+ if code_or_file.nil?
+ $stderr.puts "Run '#{$0} -h' for help."
+ exit 1
+ elsif File.exist?(code_or_file)
+ eval(File.read(code_or_file), nil, code_or_file)
+ else
+ eval(code_or_file)
+ end
+ensure
+ RAILS_DEFAULT_LOGGER.flush if RAILS_DEFAULT_LOGGER
end
diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb
index 15f417b5be..7057fcc33f 100644
--- a/railties/lib/commands/server.rb
+++ b/railties/lib/commands/server.rb
@@ -1,49 +1,103 @@
require 'active_support'
+require 'action_controller'
+
require 'fileutils'
+require 'optparse'
+# TODO: Push Thin adapter upstream so we don't need worry about requiring it
begin
- require_library_or_gem 'fcgi'
+ require_library_or_gem 'thin'
rescue Exception
- # FCGI not available
+ # Thin not available
end
-begin
- require_library_or_gem 'mongrel'
-rescue Exception
- # Mongrel not available
+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: 3000") { |v| options[:Port] = v }
+ opts.on("-b", "--binding=ip", String,
+ "Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| options[:Host] = v }
+ opts.on("-c", "--config=file", String,
+ "Use custom rackup configuration file") { |v| options[:config] = v }
+ opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[: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: development") { |v| options[:environment] = v }
+
+ opts.separator ""
+
+ opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
+
+ opts.parse!
end
-begin
- require_library_or_gem 'thin'
-rescue Exception
- # Thin not available
+server = Rack::Handler.get(ARGV.first) rescue nil
+unless server
+ begin
+ server = Rack::Handler::Mongrel
+ rescue LoadError => e
+ server = Rack::Handler::WEBrick
+ end
end
-server = case ARGV.first
- when "lighttpd", "mongrel", "new_mongrel", "webrick", "thin"
- ARGV.shift
- else
- if defined?(Mongrel)
- "mongrel"
- elsif defined?(Thin)
- "thin"
- elsif RUBY_PLATFORM !~ /(:?mswin|mingw)/ && !silence_stderr { `lighttpd -version` }.blank? && defined?(FCGI)
- "lighttpd"
- else
- "webrick"
- end
+puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
+puts "=> Rails #{Rails.version} application starting on http://#{options[:Host]}:#{options[:Port]}"
+
+%w(cache pids sessions sockets).each do |dir_to_make|
+ FileUtils.mkdir_p(File.join(RAILS_ROOT, 'tmp', dir_to_make))
+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
-case server
- when "webrick"
- puts "=> Booting WEBrick..."
- when "lighttpd"
- puts "=> Booting lighttpd (use 'script/server webrick' to force WEBrick)"
- when "mongrel", "new_mongrel"
- puts "=> Booting Mongrel (use 'script/server webrick' to force WEBrick)"
- when "thin"
- puts "=> Booting Thin (use 'script/server webrick' to force WEBrick)"
+ENV["RAILS_ENV"] = options[:environment]
+RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV)
+
+if File.exist?(options[:config])
+ config = options[: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
+else
+ require RAILS_ROOT + "/config/environment"
+ inner_app = ActionController::Dispatcher.new
end
-%w(cache pids sessions sockets).each { |dir_to_make| FileUtils.mkdir_p(File.join(RAILS_ROOT, 'tmp', dir_to_make)) }
-require "commands/servers/#{server}"
+app = Rack::Builder.new {
+ use Rails::Rack::Logger
+ use Rails::Rack::Static
+ use Rails::Rack::Debugger if options[:debugger]
+ run inner_app
+}.to_app
+
+puts "=> Call with -d to detach"
+
+trap(:INT) { exit }
+
+puts "=> Ctrl-C to shutdown server"
+
+begin
+ server.run(app, options.merge(:AccessLog => []))
+ensure
+ puts 'Exiting'
+end
diff --git a/railties/lib/commands/servers/base.rb b/railties/lib/commands/servers/base.rb
deleted file mode 100644
index 23be169a8d..0000000000
--- a/railties/lib/commands/servers/base.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-def tail(log_file)
- cursor = File.size(log_file)
- last_checked = Time.now
- tail_thread = Thread.new do
- File.open(log_file, 'r') do |f|
- loop do
- f.seek cursor
- if f.mtime > last_checked
- last_checked = f.mtime
- contents = f.read
- cursor += contents.length
- print contents
- end
- sleep 1
- end
- end
- end
- tail_thread
-end
-
-def start_debugger
- begin
- require_library_or_gem 'ruby-debug'
- Debugger.start
- Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings)
- puts "=> Debugger enabled"
- rescue Exception
- puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'"
- exit
- end
-end \ No newline at end of file
diff --git a/railties/lib/commands/servers/lighttpd.rb b/railties/lib/commands/servers/lighttpd.rb
deleted file mode 100644
index c9d13e86f3..0000000000
--- a/railties/lib/commands/servers/lighttpd.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-require 'rbconfig'
-require 'commands/servers/base'
-
-unless RUBY_PLATFORM !~ /mswin/ && !silence_stderr { `lighttpd -version` }.blank?
- puts "PROBLEM: Lighttpd is not available on your system (or not in your path)"
- exit 1
-end
-
-unless defined?(FCGI)
- puts "PROBLEM: Lighttpd requires that the FCGI Ruby bindings are installed on the system"
- exit 1
-end
-
-require 'initializer'
-configuration = Rails::Initializer.run(:initialize_logger).configuration
-default_config_file = config_file = Pathname.new("#{RAILS_ROOT}/config/lighttpd.conf").cleanpath
-
-require 'optparse'
-
-detach = false
-command_line_port = nil
-
-ARGV.options do |opt|
- opt.on("-p", "--port=port", "Changes the server.port number in the config/lighttpd.conf") { |port| command_line_port = port }
- opt.on('-c', "--config=#{config_file}", 'Specify a different lighttpd config file.') { |path| config_file = path }
- opt.on('-h', '--help', 'Show this message.') { puts opt; exit 0 }
- opt.on('-d', '-d', 'Call with -d to detach') { detach = true; puts "=> Configuration in config/lighttpd.conf" }
- opt.parse!
-end
-
-unless File.exist?(config_file)
- if config_file != default_config_file
- puts "=> #{config_file} not found."
- exit 1
- end
-
- require 'fileutils'
-
- source = File.expand_path(File.join(File.dirname(__FILE__),
- "..", "..", "..", "configs", "lighttpd.conf"))
- puts "=> #{config_file} not found, copying from #{source}"
-
- FileUtils.cp(source, config_file)
-end
-
-# open the config/lighttpd.conf file and add the current user defined port setting to it
-if command_line_port
- File.open(config_file, 'r+') do |config|
- lines = config.readlines
-
- lines.each do |line|
- line.gsub!(/^\s*server.port\s*=\s*(\d+)/, "server.port = #{command_line_port}")
- end
-
- config.rewind
- config.print(lines)
- config.truncate(config.pos)
- end
-end
-
-config = IO.read(config_file)
-default_port, default_ip = 3000, '0.0.0.0'
-port = config.scan(/^\s*server.port\s*=\s*(\d+)/).first rescue default_port
-ip = config.scan(/^\s*server.bind\s*=\s*"([^"]+)"/).first rescue default_ip
-puts "=> Rails #{Rails.version} application starting on http://#{ip || default_ip}:#{port || default_port}"
-
-tail_thread = nil
-
-if !detach
- puts "=> Call with -d to detach"
- puts "=> Ctrl-C to shutdown server (see config/lighttpd.conf for options)"
- detach = false
- tail_thread = tail(configuration.log_path)
-end
-
-trap(:INT) { exit }
-
-begin
- `rake tmp:sockets:clear` # Needed if lighttpd crashes or otherwise leaves FCGI sockets around
- `lighttpd #{!detach ? "-D " : ""}-f #{config_file}`
-ensure
- unless detach
- tail_thread.kill if tail_thread
- puts 'Exiting'
-
- # Ensure FCGI processes are reaped
- silence_stream(STDOUT) do
- ARGV.replace ['-a', 'kill']
- require 'commands/process/reaper'
- end
-
- `rake tmp:sockets:clear` # Remove sockets on clean shutdown
- end
-end
diff --git a/railties/lib/commands/servers/mongrel.rb b/railties/lib/commands/servers/mongrel.rb
deleted file mode 100644
index 7bb110f63a..0000000000
--- a/railties/lib/commands/servers/mongrel.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-require 'rbconfig'
-require 'commands/servers/base'
-
-unless defined?(Mongrel)
- puts "PROBLEM: Mongrel is not available on your system (or not in your path)"
- exit 1
-end
-
-require 'optparse'
-
-OPTIONS = {
- :port => 3000,
- :ip => "0.0.0.0",
- :environment => (ENV['RAILS_ENV'] || "development").dup,
- :detach => false,
- :debugger => false
-}
-
-ARGV.clone.options do |opts|
- opts.on("-p", "--port=port", Integer, "Runs Rails on the specified port.", "Default: 3000") { |v| OPTIONS[:port] = v }
- opts.on("-b", "--binding=ip", String, "Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| OPTIONS[:ip] = 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: development") { |v| OPTIONS[:environment] = v }
-
- opts.separator ""
-
- opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
-
- opts.parse!
-end
-
-puts "=> Rails #{Rails.version} application starting on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
-
-parameters = [
- "start",
- "-p", OPTIONS[:port].to_s,
- "-a", OPTIONS[:ip].to_s,
- "-e", OPTIONS[:environment],
- "-P", "#{RAILS_ROOT}/tmp/pids/mongrel.pid"
-]
-
-if OPTIONS[:detach]
- `mongrel_rails #{parameters.join(" ")} -d`
-else
- ENV["RAILS_ENV"] = OPTIONS[:environment]
- RAILS_ENV.replace(OPTIONS[:environment]) if defined?(RAILS_ENV)
-
- start_debugger if OPTIONS[:debugger]
-
- puts "=> Call with -d to detach"
- puts "=> Ctrl-C to shutdown server"
-
- log = Pathname.new("#{File.expand_path(RAILS_ROOT)}/log/#{RAILS_ENV}.log").cleanpath
- open(log, (File::WRONLY | File::APPEND | File::CREAT)) unless File.exist? log
- tail_thread = tail(log)
-
- trap(:INT) { exit }
-
- begin
- silence_warnings { ARGV = parameters }
- load("mongrel_rails")
- ensure
- tail_thread.kill if tail_thread
- puts 'Exiting'
- end
-end \ No newline at end of file
diff --git a/railties/lib/commands/servers/new_mongrel.rb b/railties/lib/commands/servers/new_mongrel.rb
deleted file mode 100644
index 174dbf8a37..0000000000
--- a/railties/lib/commands/servers/new_mongrel.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-unless defined?(Mongrel)
- abort "PROBLEM: Mongrel is not available on your system (or not in your path)"
-end
-
-require 'rails/mongrel_server/commands'
-
-GemPlugin::Manager.instance.load "rails::mongrel" => GemPlugin::INCLUDE, "rails" => GemPlugin::EXCLUDE
-
-case ARGV[0] ||= 'start'
-when 'start', 'stop', 'restart'
- ARGV[0] = "rails::mongrelserver::#{ARGV[0]}"
-end
-
-if not Mongrel::Command::Registry.instance.run ARGV
- exit 1
-end
diff --git a/railties/lib/commands/servers/thin.rb b/railties/lib/commands/servers/thin.rb
deleted file mode 100644
index 833469cab1..0000000000
--- a/railties/lib/commands/servers/thin.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-require 'rbconfig'
-require 'commands/servers/base'
-require 'thin'
-
-
-options = ARGV.clone
-options.insert(0,'start') unless Thin::Runner.commands.include?(options[0])
-
-thin = Thin::Runner.new(options)
-
-puts "=> Rails #{Rails.version} application starting on http://#{thin.options[:address]}:#{thin.options[:port]}"
-puts "=> Ctrl-C to shutdown server"
-
-log = Pathname.new("#{File.expand_path(RAILS_ROOT)}/log/#{RAILS_ENV}.log").cleanpath
-open(log, (File::WRONLY | File::APPEND | File::CREAT)) unless File.exist? log
-tail_thread = tail(log)
-trap(:INT) { exit }
-
-begin
- thin.run!
-ensure
- tail_thread.kill if tail_thread
- puts 'Exiting'
-end
-
diff --git a/railties/lib/commands/servers/webrick.rb b/railties/lib/commands/servers/webrick.rb
deleted file mode 100644
index 18c8897cc8..0000000000
--- a/railties/lib/commands/servers/webrick.rb
+++ /dev/null
@@ -1,66 +0,0 @@
-require 'webrick'
-require 'optparse'
-require 'commands/servers/base'
-
-OPTIONS = {
- :port => 3000,
- :ip => "0.0.0.0",
- :environment => (ENV['RAILS_ENV'] || "development").dup,
- :server_root => File.expand_path(RAILS_ROOT + "/public/"),
- :server_type => WEBrick::SimpleServer,
- :charset => "UTF-8",
- :mime_types => WEBrick::HTTPUtils::DefaultMimeTypes,
- :debugger => false
-
-}
-
-ARGV.options do |opts|
- script_name = File.basename($0)
- opts.banner = "Usage: ruby #{script_name} [options]"
-
- opts.separator ""
-
- opts.on("-p", "--port=port", Integer,
- "Runs Rails on the specified port.",
- "Default: 3000") { |v| OPTIONS[:port] = v }
- opts.on("-b", "--binding=ip", String,
- "Binds Rails to the specified ip.",
- "Default: 0.0.0.0") { |v| OPTIONS[:ip] = v }
- opts.on("-e", "--environment=name", String,
- "Specifies the environment to run this server under (test/development/production).",
- "Default: development") { |v| OPTIONS[:environment] = v }
- opts.on("-m", "--mime-types=filename", String,
- "Specifies an Apache style mime.types configuration file to be used for mime types",
- "Default: none") { |mime_types_file| OPTIONS[:mime_types] = WEBrick::HTTPUtils::load_mime_types(mime_types_file) }
-
- opts.on("-d", "--daemon",
- "Make Rails run as a Daemon (only works if fork is available -- meaning on *nix)."
- ) { OPTIONS[:server_type] = WEBrick::Daemon }
-
- opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { OPTIONS[:debugger] = true }
-
- opts.on("-c", "--charset=charset", String,
- "Set default charset for output.",
- "Default: UTF-8") { |v| OPTIONS[:charset] = v }
-
- opts.separator ""
-
- opts.on("-h", "--help",
- "Show this help message.") { puts opts; exit }
-
- opts.parse!
-end
-
-start_debugger if OPTIONS[:debugger]
-
-ENV["RAILS_ENV"] = OPTIONS[:environment]
-RAILS_ENV.replace(OPTIONS[:environment]) if defined?(RAILS_ENV)
-
-require RAILS_ROOT + "/config/environment"
-require 'webrick_server'
-
-OPTIONS['working_directory'] = File.expand_path(RAILS_ROOT)
-
-puts "=> Rails #{Rails.version} application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
-puts "=> Ctrl-C to shutdown server; call with --help for options" if OPTIONS[:server_type] == WEBrick::SimpleServer
-DispatchServlet.dispatch(OPTIONS)
diff --git a/railties/lib/console_app.rb b/railties/lib/console_app.rb
index 88e7962b43..96bf3117c8 100644
--- a/railties/lib/console_app.rb
+++ b/railties/lib/console_app.rb
@@ -1,4 +1,5 @@
-require 'action_controller/integration'
+require 'active_support/test_case'
+require 'action_controller'
# work around the at_exit hook in test/unit, which kills IRB
Test::Unit.run = true if Test::Unit.respond_to?(:run=)
diff --git a/railties/lib/console_with_helpers.rb b/railties/lib/console_with_helpers.rb
index be453a6896..039db667c4 100644
--- a/railties/lib/console_with_helpers.rb
+++ b/railties/lib/console_with_helpers.rb
@@ -1,26 +1,5 @@
-class Module
- def include_all_modules_from(parent_module)
- parent_module.constants.each do |const|
- mod = parent_module.const_get(const)
- if mod.class == Module
- send(:include, mod)
- include_all_modules_from(mod)
- end
- end
- end
-end
-
-def helper(*helper_names)
- returning @helper_proxy ||= Object.new do |helper|
- helper_names.each { |h| helper.extend "#{h}_helper".classify.constantize }
- end
-end
-
-require_dependency 'application'
-
-class << helper
- include_all_modules_from ActionView
+def helper
+ @helper ||= ApplicationController.helpers
end
@controller = ApplicationController.new
-helper :application rescue nil
diff --git a/railties/lib/fcgi_handler.rb b/railties/lib/fcgi_handler.rb
index 1bb55b9275..1256ef2286 100644
--- a/railties/lib/fcgi_handler.rb
+++ b/railties/lib/fcgi_handler.rb
@@ -98,7 +98,7 @@ class RailsFCGIHandler
with_signal_handler 'USR1' do
begin
- Dispatcher.dispatch(cgi)
+ ::Rack::Handler::FastCGI.serve(cgi, Dispatcher.new)
rescue SignalException, SystemExit
raise
rescue Exception => error
diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb
index e3a0e3bad1..4bb1e480b7 100644
--- a/railties/lib/initializer.rb
+++ b/railties/lib/initializer.rb
@@ -39,20 +39,21 @@ module Rails
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
- if defined?(RAILS_ROOT)
- RAILS_ROOT
- else
- nil
- end
+ Pathname.new(RAILS_ROOT) if defined?(RAILS_ROOT)
end
def env
- @_env ||= begin
- require 'active_support/string_inquirer'
- ActiveSupport::StringInquirer.new(RAILS_ENV)
- end
+ @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
end
def cache
@@ -131,6 +132,7 @@ module Rails
add_gem_load_paths
require_frameworks
+ preload_frameworks
set_autoload_paths
add_plugin_load_paths
load_environment
@@ -147,7 +149,10 @@ module Rails
initialize_dependency_mechanism
initialize_whiny_nils
initialize_temporary_session_directory
+
initialize_time_zone
+ initialize_i18n
+
initialize_framework_settings
initialize_framework_views
@@ -252,10 +257,23 @@ module Rails
def require_frameworks
configuration.frameworks.each { |framework| require(framework.to_s) }
rescue LoadError => e
- # re-raise because Mongrel would swallow it
+ # Re-raise as RuntimeError because Mongrel would swallow LoadError.
raise e.to_s
end
+ # Preload all frameworks specified by the Configuration#frameworks.
+ # Used by Passenger to ensure everything's loaded before forking and
+ # to avoid autoload race conditions in JRuby.
+ def preload_frameworks
+ if configuration.preload_frameworks
+ configuration.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!
+ end
+ end
+ end
+
# Add the load paths used by support functions such as the info controller
def add_support_load_paths
end
@@ -350,9 +368,10 @@ Run `rake gems:install` to install the missing gems.
def load_view_paths
if configuration.frameworks.include?(:action_view)
- ActionView::PathSet::Path.eager_load_templates! if configuration.cache_classes
- ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller)
- ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer)
+ if configuration.cache_classes
+ ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller)
+ ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer)
+ end
end
end
@@ -464,8 +483,9 @@ Run `rake gems:install` to install the missing gems.
# loading module used to lazily load controllers (Configuration#controller_paths).
def initialize_routing
return unless configuration.frameworks.include?(:action_controller)
- ActionController::Routing.controller_paths = configuration.controller_paths
- ActionController::Routing::Routes.configuration_file = configuration.routes_configuration_file
+
+ ActionController::Routing.controller_paths += configuration.controller_paths
+ ActionController::Routing::Routes.add_configuration_file(configuration.routes_configuration_file)
ActionController::Routing::Routes.reload
end
@@ -493,10 +513,15 @@ Run `rake gems:install` to install the missing gems.
def initialize_time_zone
if configuration.time_zone
zone_default = Time.__send__(:get_zone, configuration.time_zone)
+
unless zone_default
- raise %{Value assigned to config.time_zone not recognized. Run "rake -D time" for a list of tasks for finding appropriate time zone names.}
+ raise \
+ 'Value assigned to config.time_zone not recognized.' +
+ 'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
end
+
Time.zone_default = zone_default
+
if configuration.frameworks.include?(:active_record)
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
@@ -504,6 +529,18 @@ Run `rake gems:install` to install the missing gems.
end
end
+ # Set the i18n configuration from config.i18n but special-case for the load_path which should be
+ # appended to what's already set instead of overwritten.
+ def initialize_i18n
+ configuration.i18n.each do |setting, value|
+ if setting == :load_path
+ I18n.load_path += value
+ else
+ I18n.send("#{setting}=", value)
+ end
+ 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.
@@ -532,7 +569,7 @@ Run `rake gems:install` to install the missing gems.
def load_application_initializers
if gems_dependencies_loaded
Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer|
- load(initializer)
+ load initializer.sub(/^#{Regexp.escape(configuration.root_path)}\//, '')
end
end
end
@@ -582,12 +619,15 @@ Run `rake gems:install` to install the missing gems.
# A stub for setting options on ActiveSupport.
attr_accessor :active_support
+ # Whether to preload all frameworks at startup.
+ attr_accessor :preload_frameworks
+
# Whether or not classes should be cached (set to false if you want
# application classes to be reloaded on each request)
attr_accessor :cache_classes
# The list of paths that should be searched for controllers. (Defaults
- # to <tt>app/controllers</tt> and <tt>components</tt>.)
+ # to <tt>app/controllers</tt>.)
attr_accessor :controller_paths
# The path to the database configuration file to use. (Defaults to
@@ -732,6 +772,9 @@ Run `rake gems:install` to install the missing gems.
# timezone to <tt>:utc</tt>.
attr_accessor :time_zone
+ # Accessor for i18n settings.
+ attr_accessor :i18n
+
# Create a new Configuration instance, initialized with the default
# values.
def initialize
@@ -745,6 +788,7 @@ Run `rake gems:install` to install the missing gems.
self.log_level = default_log_level
self.view_path = default_view_path
self.controller_paths = default_controller_paths
+ self.preload_frameworks = default_preload_frameworks
self.cache_classes = default_cache_classes
self.dependency_loading = default_dependency_loading
self.whiny_nils = default_whiny_nils
@@ -755,6 +799,7 @@ Run `rake gems:install` to install the missing gems.
self.database_configuration_file = default_database_configuration_file
self.routes_configuration_file = default_routes_configuration_file
self.gems = default_gems
+ self.i18n = default_i18n
for framework in default_frameworks
self.send("#{framework}=", Rails::OrderedOptions.new)
@@ -786,6 +831,7 @@ Run `rake gems:install` to install the missing gems.
# multiple database connections. Also disables automatic dependency loading
# after boot
def threadsafe!
+ self.preload_frameworks = true
self.cache_classes = true
self.dependency_loading = false
self.action_controller.allow_concurrency = true
@@ -835,6 +881,11 @@ Run `rake gems:install` to install the missing gems.
end
end
+ def middleware
+ require 'action_controller'
+ ActionController::Dispatcher.middleware
+ end
+
def builtin_directories
# Include builtins only in the development environment.
(environment == 'development') ? Dir["#{RAILTIES_PATH}/builtin/*/"] : []
@@ -842,10 +893,10 @@ Run `rake gems:install` to install the missing gems.
def framework_paths
paths = %w(railties railties/lib activesupport/lib)
- paths << 'actionpack/lib' if frameworks.include? :action_controller or frameworks.include? :action_view
+ 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
+ paths << "#{framework.to_s.gsub('_', '')}/lib" if frameworks.include?(framework)
end
paths.map { |dir| "#{framework_root_path}/#{dir}" }.select { |dir| File.directory?(dir) }
@@ -869,9 +920,6 @@ Run `rake gems:install` to install the missing gems.
# Add the app's controller directory
paths.concat(Dir["#{root_path}/app/controllers/"])
- # Then components subdirectories.
- paths.concat(Dir["#{root_path}/components/[_a-z]*"])
-
# Followed by the standard includes.
paths.concat %w(
app
@@ -879,9 +927,9 @@ Run `rake gems:install` to install the missing gems.
app/controllers
app/helpers
app/services
- components
config
lib
+ vendor
).map { |dir| "#{root_path}/#{dir}" }.select { |dir| File.directory?(dir) }
paths.concat builtin_directories
@@ -930,6 +978,10 @@ Run `rake gems:install` to install the missing gems.
true
end
+ def default_preload_frameworks
+ false
+ end
+
def default_cache_classes
true
end
@@ -967,6 +1019,18 @@ Run `rake gems:install` to install the missing gems.
def default_gems
[]
end
+
+ def default_i18n
+ i18n = Rails::OrderedOptions.new
+ i18n.load_path = []
+
+ if File.exist?(File.join(RAILS_ROOT, 'config', 'locales'))
+ i18n.load_path << Dir[File.join(RAILS_ROOT, 'config', 'locales', '*.{rb,yml}')]
+ i18n.load_path.flatten!
+ end
+
+ i18n
+ end
end
end
diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb
new file mode 100644
index 0000000000..d8626aaf14
--- /dev/null
+++ b/railties/lib/rails/backtrace_cleaner.rb
@@ -0,0 +1,33 @@
+module Rails
+ class BacktraceCleaner < ActiveSupport::BacktraceCleaner
+ ERB_METHOD_SIG = /:in `_run_erb_.*/
+
+ VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails )
+ SERVER_DIRS = %w( lib/mongrel bin/mongrel lib/rack )
+ RAILS_NOISE = %w( script/server )
+ RUBY_NOISE = %w( rubygems/custom_require benchmark.rb )
+
+ ALL_NOISE = VENDOR_DIRS + SERVER_DIRS + RAILS_NOISE + RUBY_NOISE
+
+ def initialize
+ super
+ add_filter { |line| line.sub(RAILS_ROOT, '') }
+ add_filter { |line| line.sub(ERB_METHOD_SIG, '') }
+ add_filter { |line| line.sub('./', '/') } # for tests
+ add_silencer { |line| ALL_NOISE.any? { |dir| line.include?(dir) } }
+ end
+ end
+
+ # For installing the BacktraceCleaner in the test/unit
+ module BacktraceFilterForTestUnit #:nodoc:
+ def self.included(klass)
+ klass.send :alias_method_chain, :filter_backtrace, :cleaning
+ end
+
+ def filter_backtrace_with_cleaning(backtrace, prefix=nil)
+ backtrace = filter_backtrace_without_cleaning(backtrace, prefix)
+ backtrace = backtrace.first.split("\n") if backtrace.size == 1
+ Rails.backtrace_cleaner.clean(backtrace)
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb
index cd280ac023..5a07841be8 100644
--- a/railties/lib/rails/gem_dependency.rb
+++ b/railties/lib/rails/gem_dependency.rb
@@ -74,6 +74,7 @@ module Rails
def dependencies
return [] if framework_gem?
+ return [] if specification.nil?
all_dependencies = specification.dependencies.map do |dependency|
GemDependency.new(dependency.name, :requirement => dependency.version_requirements)
end
diff --git a/railties/lib/rails/mongrel_server/commands.rb b/railties/lib/rails/mongrel_server/commands.rb
deleted file mode 100644
index d29b18712f..0000000000
--- a/railties/lib/rails/mongrel_server/commands.rb
+++ /dev/null
@@ -1,342 +0,0 @@
-# Copyright (c) 2005 Zed A. Shaw
-# You can redistribute it and/or modify it under the same terms as Ruby.
-#
-# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
-# for more information.
-
-require 'optparse'
-require 'yaml'
-require 'etc'
-
-require 'mongrel'
-require 'rails/mongrel_server/handler'
-
-module Rails
- module MongrelServer
- def self.send_signal(signal, pid_file)
- pid = open(pid_file).read.to_i
- print "Sending #{signal} to Mongrel at PID #{pid}..."
- begin
- Process.kill(signal, pid)
- rescue Errno::ESRCH
- puts "Process does not exist. Not running."
- end
-
- puts "Done."
- end
-
- class RailsConfigurator < Mongrel::Configurator
- def setup_mime_types
- mime = {}
-
- if defaults[:mime_map]
- Mongrel.log("Loading additional MIME types from #{defaults[:mime_map]}")
- mime = load_mime_map(defaults[:mime_map], mime)
- end
-
- mime.each {|k,v| Mongrel::DirHandler::add_mime_type(k,v) }
- end
-
- def mount_rails(prefix)
- ENV['RAILS_ENV'] = defaults[:environment]
- ::RAILS_ENV.replace(defaults[:environment]) if defined?(::RAILS_ENV)
-
- env_location = "#{defaults[:cwd]}/config/environment"
- require env_location
-
- ActionController::Base.relative_url_root = defaults[:prefix]
- uri prefix, :handler => Rails::MongrelServer::RailsHandler.new
- end
- end
-
- class Start < GemPlugin::Plugin "/commands"
- include Mongrel::Command::Base
-
- def configure
- options [
- ["-e", "--environment ENV", "Rails environment to run as", :@environment, ENV['RAILS_ENV'] || "development"],
- ["-d", "--daemonize", "Run daemonized in the background", :@daemon, false],
- ['-p', '--port PORT', "Which port to bind to", :@port, 3000],
- ['-a', '--address ADDR', "Address to bind to", :@address, "0.0.0.0"],
- ['-l', '--log FILE', "Where to write log messages", :@log_file, "log/mongrel.log"],
- ['-P', '--pid FILE', "Where to write the PID", :@pid_file, "tmp/pids/mongrel.pid"],
- ['-n', '--num-procs INT', "Number of processors active before clients denied", :@num_procs, 1024],
- ['-o', '--timeout TIME', "Time to wait (in seconds) before killing a stalled thread", :@timeout, 60],
- ['-t', '--throttle TIME', "Time to pause (in hundredths of a second) between accepting clients", :@throttle, 0],
- ['-m', '--mime PATH', "A YAML file that lists additional MIME types", :@mime_map, nil],
- ['-c', '--chdir PATH', "Change to dir before starting (will be expanded)", :@cwd, RAILS_ROOT],
- ['-r', '--root PATH', "Set the document root (default 'public')", :@docroot, "public"],
- ['-B', '--debug', "Enable debugging mode", :@debug, false],
- ['-C', '--config PATH', "Use a config file", :@config_file, nil],
- ['-S', '--script PATH', "Load the given file as an extra config script", :@config_script, nil],
- ['-G', '--generate PATH', "Generate a config file for use with -C", :@generate, nil],
- ['', '--user USER', "User to run as", :@user, nil],
- ['', '--group GROUP', "Group to run as", :@group, nil],
- ['', '--prefix PATH', "URL prefix for Rails app", :@prefix, nil],
-
- ['-b', '--binding ADDR', "Address to bind to (deprecated, use -a)", :@address, "0.0.0.0"],
- ['-u', '--debugger', "Enable debugging mode (deprecated, use -B)", :@debug, false]
- ]
- end
-
- def validate
- if @config_file
- valid_exists?(@config_file, "Config file not there: #@config_file")
- return false unless @valid
- @config_file = File.expand_path(@config_file)
- load_config
- return false unless @valid
- end
-
- @cwd = File.expand_path(@cwd)
- valid_dir? @cwd, "Invalid path to change to during daemon mode: #@cwd"
-
- # Change there to start, then we'll have to come back after daemonize
- Dir.chdir(@cwd)
-
- valid?(@prefix[0] == ?/ && @prefix[-1] != ?/, "Prefix must begin with / and not end in /") if @prefix
- valid_dir? File.dirname(@log_file), "Path to log file not valid: #@log_file"
- valid_dir? File.dirname(@pid_file), "Path to pid file not valid: #@pid_file"
- valid_dir? @docroot, "Path to docroot not valid: #@docroot"
- valid_exists? @mime_map, "MIME mapping file does not exist: #@mime_map" if @mime_map
- valid_exists? @config_file, "Config file not there: #@config_file" if @config_file
- valid_dir? File.dirname(@generate), "Problem accessing directory to #@generate" if @generate
- valid_user? @user if @user
- valid_group? @group if @group
-
- return @valid
- end
-
- def run
- if @generate
- @generate = File.expand_path(@generate)
- Mongrel.log(:error, "** Writing config to \"#@generate\".")
- open(@generate, "w") {|f| f.write(settings.to_yaml) }
- Mongrel.log(:error, "** Finished. Run \"mongrel_rails start -C #@generate\" to use the config file.")
- exit 0
- end
-
- config = RailsConfigurator.new(settings) do
- defaults[:log] = $stdout if defaults[:environment] == 'development'
-
- Mongrel.log("=> Rails #{Rails.version} application starting on http://#{defaults[:host]}:#{defaults[:port]}")
-
- unless defaults[:daemon]
- Mongrel.log("=> Call with -d to detach")
- Mongrel.log("=> Ctrl-C to shutdown server")
- start_debugger if defaults[:debug]
- end
-
- if defaults[:daemon]
- if File.exist? defaults[:pid_file]
- Mongrel.log(:error, "!!! PID file #{defaults[:pid_file]} already exists. Mongrel could be running already. Check your #{defaults[:log_file]} for errors.")
- Mongrel.log(:error, "!!! Exiting with error. You must stop mongrel and clear the .pid before I'll attempt a start.")
- exit 1
- end
-
- daemonize
-
- Mongrel.log("Daemonized, any open files are closed. Look at #{defaults[:pid_file]} and #{defaults[:log_file]} for info.")
- Mongrel.log("Settings loaded from #{@config_file} (they override command line).") if @config_file
- end
-
- Mongrel.log("Starting Mongrel listening at #{defaults[:host]}:#{defaults[:port]}, further information can be found in log/mongrel-#{defaults[:host]}-#{defaults[:port]}.log")
-
- listener do
- prefix = defaults[:prefix] || '/'
-
- if defaults[:debug]
- Mongrel.log("Installing debugging prefixed filters. Look in log/mongrel_debug for the files.")
- debug(prefix)
- end
-
- setup_mime_types
- dir_handler = Mongrel::DirHandler.new(defaults[:docroot], false)
- dir_handler.passthrough_missing_files = true
-
- unless defaults[:environment] == 'production'
- Mongrel.log("Mounting DirHandler at #{prefix}...")
- uri prefix, :handler => dir_handler
- end
-
-
- Mongrel.log("Starting Rails with #{defaults[:environment]} environment...")
- Mongrel.log("Mounting Rails at #{prefix}...")
- mount_rails(prefix)
- Mongrel.log("Rails loaded.")
-
-
- Mongrel.log("Loading any Rails specific GemPlugins" )
- load_plugins
-
- if defaults[:config_script]
- Mongrel.log("Loading #{defaults[:config_script]} external config script")
- run_config(defaults[:config_script])
- end
-
- setup_signals
- end
- end
-
- config.run
- Mongrel.log("Mongrel #{Mongrel::Const::MONGREL_VERSION} available at #{@address}:#{@port}")
-
- if config.defaults[:daemon]
- config.write_pid_file
- else
- Mongrel.log("Use CTRL-C to stop.")
- tail "log/#{config.defaults[:environment]}.log"
- end
-
- config.join
-
- if config.needs_restart
- unless RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw/
- cmd = "ruby #{__FILE__} start #{original_args.join(' ')}"
- Mongrel.log("Restarting with arguments: #{cmd}")
- config.stop(false, true)
- config.remove_pid_file
-
- if config.defaults[:daemon]
- system cmd
- else
- Mongrel.log(:error, "Can't restart unless in daemon mode.")
- exit 1
- end
- else
- Mongrel.log("Win32 does not support restarts. Exiting.")
- end
- end
- end
-
- def load_config
- settings = {}
- begin
- settings = YAML.load_file(@config_file)
- ensure
- Mongrel.log(:error, "** Loading settings from #{@config_file} (they override command line).") unless @daemon || settings[:daemon]
- end
-
- settings[:includes] ||= ["mongrel"]
-
- # Config file settings will override command line settings
- settings.each do |key, value|
- key = key.to_s
- if config_keys.include?(key)
- key = 'address' if key == 'host'
- self.instance_variable_set("@#{key}", value)
- else
- failure "Unknown configuration setting: #{key}"
- @valid = false
- end
- end
- end
-
- def config_keys
- @config_keys ||=
- %w(address host port cwd log_file pid_file environment docroot mime_map daemon debug includes config_script num_processors timeout throttle user group prefix)
- end
-
- def settings
- config_keys.inject({}) do |hash, key|
- value = self.instance_variable_get("@#{key}")
- key = 'host' if key == 'address'
- hash[key.to_sym] ||= value
- hash
- end
- end
-
- def start_debugger
- require_library_or_gem 'ruby-debug'
- Debugger.start
- Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings)
- Mongrel.log("=> Debugger enabled")
- rescue Exception
- Mongrel.log(:error, "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'")
- exit
- end
-
- def tail(log_file)
- cursor = File.size(log_file)
- last_checked = Time.now
- tail_thread = Thread.new do
- File.open(log_file, 'r') do |f|
- loop do
- f.seek cursor
- if f.mtime > last_checked
- last_checked = f.mtime
- contents = f.read
- cursor += contents.length
- print contents
- end
- sleep 1
- end
- end
- end
- tail_thread
- end
- end
-
- class Stop < GemPlugin::Plugin "/commands"
- include Mongrel::Command::Base
-
- def configure
- options [
- ['-c', '--chdir PATH', "Change to dir before starting (will be expanded).", :@cwd, "."],
- ['-f', '--force', "Force the shutdown (kill -9).", :@force, false],
- ['-w', '--wait SECONDS', "Wait SECONDS before forcing shutdown", :@wait, "0"],
- ['-P', '--pid FILE', "Where the PID file is located.", :@pid_file, "log/mongrel.pid"]
- ]
- end
-
- def validate
- @cwd = File.expand_path(@cwd)
- valid_dir? @cwd, "Invalid path to change to during daemon mode: #@cwd"
-
- Dir.chdir @cwd
-
- valid_exists? @pid_file, "PID file #@pid_file does not exist. Not running?"
- return @valid
- end
-
- def run
- if @force
- @wait.to_i.times do |waiting|
- exit(0) if not File.exist? @pid_file
- sleep 1
- end
-
- Mongrel::send_signal("KILL", @pid_file) if File.exist? @pid_file
- else
- Mongrel::send_signal("TERM", @pid_file)
- end
- end
- end
-
-
- class Restart < GemPlugin::Plugin "/commands"
- include Mongrel::Command::Base
-
- def configure
- options [
- ['-c', '--chdir PATH', "Change to dir before starting (will be expanded)", :@cwd, '.'],
- ['-P', '--pid FILE', "Where the PID file is located", :@pid_file, "log/mongrel.pid"]
- ]
- end
-
- def validate
- @cwd = File.expand_path(@cwd)
- valid_dir? @cwd, "Invalid path to change to during daemon mode: #@cwd"
-
- Dir.chdir @cwd
-
- valid_exists? @pid_file, "PID file #@pid_file does not exist. Not running?"
- return @valid
- end
-
- def run
- MongrelServer::send_signal("USR2", @pid_file)
- end
- end
- end
-end
diff --git a/railties/lib/rails/mongrel_server/handler.rb b/railties/lib/rails/mongrel_server/handler.rb
deleted file mode 100644
index a19eca7259..0000000000
--- a/railties/lib/rails/mongrel_server/handler.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-# Copyright (c) 2005 Zed A. Shaw
-# You can redistribute it and/or modify it under the same terms as Ruby.
-#
-# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
-# for more information.
-
-require 'mongrel'
-require 'cgi'
-require 'action_controller/dispatcher'
-
-
-module Rails
- module MongrelServer
- # Implements a handler that can run Rails and serve files out of the
- # Rails application's public directory. This lets you run your Rails
- # application with Mongrel during development and testing, then use it
- # also in production behind a server that's better at serving the
- # static files.
- #
- # The RailsHandler takes a mime_map parameter which is a simple suffix=mimetype
- # mapping that it should add to the list of valid mime types.
- #
- # It also supports page caching directly and will try to resolve a request
- # in the following order:
- #
- # * If the requested exact PATH_INFO exists as a file then serve it.
- # * If it exists at PATH_INFO+".html" exists then serve that.
- # * Finally, construct a Mongrel::CGIWrapper and run Dispatcher.dispatch to have Rails go.
- #
- # This means that if you are using page caching it will actually work with Mongrel
- # and you should see a decent speed boost (but not as fast as if you use a static
- # server like Apache or Litespeed).
- class RailsHandler < Mongrel::HttpHandler
- # Construct a Mongrel::CGIWrapper and dispatch.
- def process(request, response)
- return if response.socket.closed?
-
- cgi = Mongrel::CGIWrapper.new(request, response)
- cgi.handler = self
- # We don't want the output to be really final until we're out of the lock
- cgi.default_really_final = false
-
- ActionController::Dispatcher.dispatch(cgi, ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS, response.body)
-
- # This finalizes the output using the proper HttpResponse way
- cgi.out("text/html",true) {""}
- rescue Errno::EPIPE
- response.socket.close
- rescue Object => rails_error
- STDERR.puts "#{Time.now.httpdate}: Error dispatching #{rails_error.inspect}"
- STDERR.puts rails_error.backtrace.join("\n")
- end
- end
- end
-end
diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb
index 4d983843af..4901abe808 100644
--- a/railties/lib/rails/plugin.rb
+++ b/railties/lib/rails/plugin.rb
@@ -28,15 +28,19 @@ module Rails
end
def valid?
- File.directory?(directory) && (has_lib_directory? || has_init_file?)
+ File.directory?(directory) && (has_app_directory? || has_lib_directory? || has_init_file?)
end
# Returns a list of paths this plugin wishes to make available in <tt>$LOAD_PATH</tt>.
def load_paths
report_nonexistant_or_empty_plugin! unless valid?
- has_lib_directory? ? [lib_path] : []
+
+ returning [] do |load_paths|
+ load_paths << lib_path if has_lib_directory?
+ load_paths << app_paths if has_app_directory?
+ end.flatten
end
-
+
# Evaluates a plugin's init.rb file.
def load(initializer)
return if loaded?
@@ -56,7 +60,31 @@ module Rails
def about
@about ||= load_about_information
end
+
+ # Engines are plugins with an app/ directory.
+ def engine?
+ has_app_directory?
+ end
+
+ # Returns true if the engine ships with a routing file
+ def routed?
+ File.exist?(routing_file)
+ end
+
+
+ def view_path
+ File.join(directory, 'app', 'views')
+ end
+
+ def controller_path
+ File.join(directory, 'app', 'controllers')
+ end
+
+ def routing_file
+ File.join(directory, 'config', 'routes.rb')
+ end
+
private
def load_about_information
about_yml_path = File.join(@directory, "about.yml")
@@ -68,8 +96,13 @@ module Rails
def report_nonexistant_or_empty_plugin!
raise LoadError, "Can not find the plugin named: #{name}"
- end
-
+ end
+
+
+ def app_paths
+ [ File.join(directory, 'app', 'models'), File.join(directory, 'app', 'helpers'), controller_path ]
+ end
+
def lib_path
File.join(directory, 'lib')
end
@@ -86,6 +119,11 @@ module Rails
File.file?(gem_init_path) ? gem_init_path : classic_init_path
end
+
+ def has_app_directory?
+ File.directory?(File.join(directory, 'app'))
+ end
+
def has_lib_directory?
File.directory?(lib_path)
end
@@ -94,6 +132,7 @@ module Rails
File.file?(init_path)
end
+
def evaluate_init_rb(initializer)
if has_init_file?
silence_warnings do
diff --git a/railties/lib/rails/plugin/loader.rb b/railties/lib/rails/plugin/loader.rb
index 948d497007..be81bdf4fa 100644
--- a/railties/lib/rails/plugin/loader.rb
+++ b/railties/lib/rails/plugin/loader.rb
@@ -22,6 +22,11 @@ module Rails
@plugins ||= all_plugins.select { |plugin| should_load?(plugin) }.sort { |p1, p2| order_plugins(p1, p2) }
end
+ # Returns the plugins that are in engine-form (have an app/ directory)
+ def engines
+ @engines ||= plugins.select(&:engine?)
+ end
+
# Returns all the plugins that could be found by the current locators.
def all_plugins
@all_plugins ||= locate_plugins
@@ -33,6 +38,9 @@ module Rails
plugin.load(initializer)
register_plugin_as_loaded(plugin)
end
+
+ configure_engines
+
ensure_all_registered_plugins_are_loaded!
end
@@ -45,23 +53,49 @@ module Rails
plugins.each do |plugin|
plugin.load_paths.each do |path|
$LOAD_PATH.insert(application_lib_index + 1, path)
- ActiveSupport::Dependencies.load_paths << path
+
+ ActiveSupport::Dependencies.load_paths << path
+
unless Rails.configuration.reload_plugins?
ActiveSupport::Dependencies.load_once_paths << path
end
end
end
+
$LOAD_PATH.uniq!
- end
+ end
+
protected
+ def configure_engines
+ if engines.any?
+ add_engine_routing_configurations
+ add_engine_controller_paths
+ add_engine_view_paths
+ end
+ end
+ def add_engine_routing_configurations
+ engines.select(&:routed?).collect(&:routing_file).each do |routing_file|
+ ActionController::Routing::Routes.add_configuration_file(routing_file)
+ end
+ end
+
+ def add_engine_controller_paths
+ ActionController::Routing.controller_paths += engines.collect(&:controller_path)
+ end
+
+ def add_engine_view_paths
+ # reverse it such that the last engine can overwrite view paths from the first, like with routes
+ ActionController::Base.view_paths += ActionView::PathSet.new(engines.collect(&:view_path).reverse)
+ end
+
# The locate_plugins method uses each class in config.plugin_locators to
# find the set of all plugins available to this Rails application.
def locate_plugins
- configuration.plugin_locators.map { |locator|
+ configuration.plugin_locators.map do |locator|
locator.new(initializer).plugins
- }.flatten
+ end.flatten
# TODO: sorting based on config.plugins
end
diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb
index b4f32c2d95..90535674e9 100644
--- a/railties/lib/rails/rack.rb
+++ b/railties/lib/rails/rack.rb
@@ -1,5 +1,6 @@
module Rails
module Rack
+ autoload :Debugger, "rails/rack/debugger"
autoload :Logger, "rails/rack/logger"
autoload :Static, "rails/rack/static"
end
diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb
new file mode 100644
index 0000000000..aa2711c616
--- /dev/null
+++ b/railties/lib/rails/rack/debugger.rb
@@ -0,0 +1,21 @@
+module Rails
+ module Rack
+ class Debugger
+ def initialize(app)
+ @app = app
+
+ require_library_or_gem 'ruby-debug'
+ ::Debugger.start
+ ::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings)
+ puts "=> Debugger enabled"
+ rescue Exception
+ puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'"
+ exit
+ end
+
+ def call(env)
+ @app.call(env)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/rack/static.rb b/railties/lib/rails/rack/static.rb
index 45eb0e5921..ef4e2642e2 100644
--- a/railties/lib/rails/rack/static.rb
+++ b/railties/lib/rails/rack/static.rb
@@ -1,3 +1,5 @@
+require 'rack/utils'
+
module Rails
module Rack
class Static
diff --git a/railties/lib/rails/vendor_gem_source_index.rb b/railties/lib/rails/vendor_gem_source_index.rb
index dc821693ac..5b7721f303 100644
--- a/railties/lib/rails/vendor_gem_source_index.rb
+++ b/railties/lib/rails/vendor_gem_source_index.rb
@@ -81,7 +81,7 @@ module Rails
spec.files = files
else
$stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems not in a versioned directory."+
- " Giving up.") unless @silence_spec_warnings
+ " Giving up.") unless @@silence_spec_warnings
next
end
end
@@ -137,4 +137,4 @@ module Rails
end
end
-end \ No newline at end of file
+end
diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb
index a0986a2e05..9bb4b2a96d 100644
--- a/railties/lib/rails/version.rb
+++ b/railties/lib/rails/version.rb
@@ -1,7 +1,7 @@
module Rails
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 2
+ MINOR = 3
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
diff --git a/railties/lib/rails_generator/base.rb b/railties/lib/rails_generator/base.rb
index b5cfe79867..aa7081f8da 100644
--- a/railties/lib/rails_generator/base.rb
+++ b/railties/lib/rails_generator/base.rb
@@ -154,6 +154,9 @@ module Rails
File.join(destination_root, relative_destination)
end
+ def after_generate
+ end
+
protected
# Convenience method for generator subclasses to record a manifest.
def record
diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb
index 6b9a636847..cacb3807d6 100644
--- a/railties/lib/rails_generator/commands.rb
+++ b/railties/lib/rails_generator/commands.rb
@@ -40,6 +40,7 @@ module Rails
# Replay action manifest. RewindBase subclass rewinds manifest.
def invoke!
manifest.replay(self)
+ after_generate
end
def dependency(generator_name, args, runtime_options = {})
diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb
index 32c320385d..4a191578cf 100644
--- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb
+++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb
@@ -1,109 +1,46 @@
require 'rbconfig'
+require File.dirname(__FILE__) + '/template_runner'
require 'digest/md5'
+require 'active_support/secure_random'
class AppGenerator < Rails::Generator::Base
- DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'],
- Config::CONFIG['ruby_install_name'])
+ DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
- DATABASES = %w(mysql oracle postgresql sqlite2 sqlite3 frontbase ibm_db)
+ DATABASES = %w( mysql oracle postgresql sqlite2 sqlite3 frontbase ibm_db )
DEFAULT_DATABASE = 'sqlite3'
- default_options :db => (ENV["RAILS_DEFAULT_DATABASE"] || DEFAULT_DATABASE),
- :shebang => DEFAULT_SHEBANG, :freeze => false
mandatory_options :source => "#{File.dirname(__FILE__)}/../../../../.."
+ default_options :db => (ENV["RAILS_DEFAULT_DATABASE"] || DEFAULT_DATABASE),
+ :shebang => DEFAULT_SHEBANG, :with_dispatchers => false, :freeze => false
+
def initialize(runtime_args, runtime_options = {})
super
+
usage if args.empty?
usage("Databases supported for preconfiguration are: #{DATABASES.join(", ")}") if (options[:db] && !DATABASES.include?(options[:db]))
+
@destination_root = args.shift
@app_name = File.basename(File.expand_path(@destination_root))
end
def manifest
- # Use /usr/bin/env if no special shebang was specified
- script_options = { :chmod => 0755, :shebang => options[:shebang] == DEFAULT_SHEBANG ? nil : options[:shebang] }
- dispatcher_options = { :chmod => 0755, :shebang => options[:shebang] }
-
- # duplicate CGI::Session#generate_unique_id
- md5 = Digest::MD5.new
- now = Time.now
- md5 << now.to_s
- md5 << String(now.usec)
- md5 << String(rand(0))
- md5 << String($$)
- md5 << @app_name
-
- # Do our best to generate a secure secret key for CookieStore
- secret = ActiveSupport::SecureRandom.hex(64)
-
record do |m|
- # Root directory and all subdirectories.
- m.directory ''
- BASEDIRS.each { |path| m.directory path }
-
- # Root
- m.file "fresh_rakefile", "Rakefile"
- m.file "README", "README"
-
- # Application
- m.template "helpers/application.rb", "app/controllers/application.rb", :assigns => { :app_name => @app_name, :app_secret => md5.hexdigest }
- m.template "helpers/application_helper.rb", "app/helpers/application_helper.rb"
- m.template "helpers/test_helper.rb", "test/test_helper.rb"
- m.template "helpers/performance_test.rb", "test/performance/browsing_test.rb"
-
- # database.yml and routes.rb
- m.template "configs/databases/#{options[:db]}.yml", "config/database.yml", :assigns => {
- :app_name => @app_name,
- :socket => options[:db] == "mysql" ? mysql_socket_location : nil
- }
- m.template "configs/routes.rb", "config/routes.rb"
-
- # Initializers
- m.template "configs/initializers/inflections.rb", "config/initializers/inflections.rb"
- m.template "configs/initializers/mime_types.rb", "config/initializers/mime_types.rb"
- m.template "configs/initializers/new_rails_defaults.rb", "config/initializers/new_rails_defaults.rb"
-
- # Environments
- m.file "environments/boot.rb", "config/boot.rb"
- m.template "environments/environment.rb", "config/environment.rb", :assigns => { :freeze => options[:freeze], :app_name => @app_name, :app_secret => secret }
- m.file "environments/production.rb", "config/environments/production.rb"
- m.file "environments/development.rb", "config/environments/development.rb"
- m.file "environments/test.rb", "config/environments/test.rb"
-
- # Scripts
- %w( about console dbconsole destroy generate performance/benchmarker performance/profiler performance/request process/reaper process/spawner process/inspector runner server plugin ).each do |file|
- m.file "bin/#{file}", "script/#{file}", script_options
- end
-
- # Dispatches
- m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options
- m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options
- m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options
-
- # HTML files
- %w(404 422 500 index).each do |file|
- m.template "html/#{file}.html", "public/#{file}.html"
- end
-
- m.template "html/favicon.ico", "public/favicon.ico"
- m.template "html/robots.txt", "public/robots.txt"
- m.file "html/images/rails.png", "public/images/rails.png"
-
- # Javascripts
- m.file "html/javascripts/prototype.js", "public/javascripts/prototype.js"
- m.file "html/javascripts/effects.js", "public/javascripts/effects.js"
- m.file "html/javascripts/dragdrop.js", "public/javascripts/dragdrop.js"
- m.file "html/javascripts/controls.js", "public/javascripts/controls.js"
- m.file "html/javascripts/application.js", "public/javascripts/application.js"
-
- # Docs
- m.file "doc/README_FOR_APP", "doc/README_FOR_APP"
+ create_directories(m)
+ create_root_files(m)
+ create_app_files(m)
+ create_config_files(m)
+ create_script_files(m)
+ create_test_files(m)
+ create_public_files(m)
+ create_documentation_file(m)
+ create_log_files(m)
+ end
+ end
- # Logs
- %w(server production development test).each { |file|
- m.file "configs/empty.log", "log/#{file}.log", :chmod => 0666
- }
+ def after_generate
+ if options[:template]
+ Rails::TemplateRunner.new(@destination_root, options[:template])
end
end
@@ -123,57 +60,199 @@ class AppGenerator < Rails::Generator::Base
"Preconfigure for selected database (options: #{DATABASES.join('/')}).",
"Default: #{DEFAULT_DATABASE}") { |v| options[:db] = v }
+ opt.on("-D", "--with-dispatchers",
+ "Add CGI/FastCGI/mod_ruby dispatches code to generated application skeleton",
+ "Default: false") { |v| options[:with_dispatchers] = v }
+
opt.on("-f", "--freeze",
"Freeze Rails in vendor/rails from the gems generating the skeleton",
"Default: false") { |v| options[:freeze] = v }
+
+ opt.on("-m", "--template=path", String,
+ "Use an application template that lives at path (can be a filesystem path or URL).",
+ "Default: (none)") { |v| options[:template] = v }
+
+ end
+
+
+ private
+ def create_directories(m)
+ m.directory ''
+
+ # Intermediate directories are automatically created so don't sweat their absence here.
+ %w(
+ app/controllers
+ app/helpers
+ app/models
+ app/views/layouts
+ config/environments
+ config/initializers
+ config/locales
+ db
+ doc
+ lib
+ lib/tasks
+ log
+ public/images
+ public/javascripts
+ public/stylesheets
+ script/performance
+ test/fixtures
+ test/functional
+ test/integration
+ test/performance
+ test/unit
+ vendor
+ vendor/plugins
+ tmp/sessions
+ tmp/sockets
+ tmp/cache
+ tmp/pids
+ ).each { |path| m.directory(path) }
+ end
+
+ def create_root_files(m)
+ m.file "fresh_rakefile", "Rakefile"
+ m.file "README", "README"
+ end
+
+ def create_app_files(m)
+ m.file "helpers/application_controller.rb", "app/controllers/application_controller.rb"
+ m.file "helpers/application_helper.rb", "app/helpers/application_helper.rb"
+ end
+
+ def create_config_files(m)
+ create_database_configuration_file(m)
+ create_routes_file(m)
+ create_locale_file(m)
+ create_initializer_files(m)
+ create_environment_files(m)
+ end
+
+ def create_documentation_file(m)
+ m.file "doc/README_FOR_APP", "doc/README_FOR_APP"
end
+ def create_log_files(m)
+ %w( server production development test ).each do |file|
+ m.file "configs/empty.log", "log/#{file}.log", :chmod => 0666
+ end
+ end
+
+ def create_public_files(m)
+ create_dispatch_files(m)
+ create_error_files(m)
+ create_welcome_file(m)
+ create_browser_convention_files(m)
+ create_rails_image(m)
+ create_javascript_files(m)
+ end
+
+ def create_script_files(m)
+ %w(
+ about console dbconsole destroy generate runner server plugin
+ performance/benchmarker performance/profiler performance/request
+ ).each do |file|
+ m.file "bin/#{file}", "script/#{file}", {
+ :chmod => 0755,
+ :shebang => options[:shebang] == DEFAULT_SHEBANG ? nil : options[:shebang]
+ }
+ end
+ end
+
+ def create_test_files(m)
+ m.file "helpers/test_helper.rb", "test/test_helper.rb"
+ m.file "helpers/performance_test.rb", "test/performance/browsing_test.rb"
+ end
+
+
+ def create_database_configuration_file(m)
+ m.template "configs/databases/#{options[:db]}.yml", "config/database.yml", :assigns => {
+ :app_name => @app_name,
+ :socket => options[:db] == "mysql" ? mysql_socket_location : nil }
+ end
+
+ def create_routes_file(m)
+ m.file "configs/routes.rb", "config/routes.rb"
+ end
+
+ def create_initializer_files(m)
+ %w(
+ backtrace_silencers
+ inflections
+ mime_types
+ new_rails_defaults
+ ).each do |initializer|
+ m.file "configs/initializers/#{initializer}.rb", "config/initializers/#{initializer}.rb"
+ end
+
+ m.template "configs/initializers/session_store.rb", "config/initializers/session_store.rb",
+ :assigns => { :app_name => @app_name, :app_secret => ActiveSupport::SecureRandom.hex(64) }
+ end
+
+ def create_locale_file(m)
+ m.file "configs/locales/en.yml", "config/locales/en.yml"
+ end
+
+ def create_environment_files(m)
+ m.template "environments/environment.rb", "config/environment.rb",
+ :assigns => { :freeze => options[:freeze] }
+
+ m.file "environments/boot.rb", "config/boot.rb"
+ m.file "environments/production.rb", "config/environments/production.rb"
+ m.file "environments/development.rb", "config/environments/development.rb"
+ m.file "environments/test.rb", "config/environments/test.rb"
+ end
+
+
+ def create_dispatch_files(m)
+ if options[:with_dispatchers]
+ dispatcher_options = { :chmod => 0755, :shebang => options[:shebang] }
+
+ m.file "dispatches/config.ru", "config.ru"
+ m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options
+ m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options
+ m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options
+ end
+ end
+
+ def create_error_files(m)
+ %w( 404 422 500 ).each do |file|
+ m.file "html/#{file}.html", "public/#{file}.html"
+ end
+ end
+
+ def create_welcome_file(m)
+ m.file 'html/index.html', 'public/index.html'
+ end
+
+ def create_browser_convention_files(m)
+ m.file "html/favicon.ico", "public/favicon.ico"
+ m.file "html/robots.txt", "public/robots.txt"
+ end
+
+ def create_rails_image(m)
+ m.file "html/images/rails.png", "public/images/rails.png"
+ end
+
+ def create_javascript_files(m)
+ %w( prototype effects dragdrop controls application ).each do |javascript|
+ m.file "html/javascripts/#{javascript}.js", "public/javascripts/#{javascript}.js"
+ end
+ end
+
+
def mysql_socket_location
- MYSQL_SOCKET_LOCATIONS.find { |f| File.exist?(f) } unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
- end
-
-
- # Installation skeleton. Intermediate directories are automatically
- # created so don't sweat their absence here.
- BASEDIRS = %w(
- app/controllers
- app/helpers
- app/models
- app/views/layouts
- config/environments
- config/initializers
- db
- doc
- lib
- lib/tasks
- log
- public/images
- public/javascripts
- public/stylesheets
- script/performance
- script/process
- test/fixtures
- test/functional
- test/integration
- test/performance
- test/unit
- vendor
- vendor/plugins
- tmp/sessions
- tmp/sockets
- tmp/cache
- tmp/pids
- )
-
- MYSQL_SOCKET_LOCATIONS = [
- "/tmp/mysql.sock", # default
- "/var/run/mysqld/mysqld.sock", # debian/gentoo
- "/var/tmp/mysql.sock", # freebsd
- "/var/lib/mysql/mysql.sock", # fedora
- "/opt/local/lib/mysql/mysql.sock", # fedora
- "/opt/local/var/run/mysqld/mysqld.sock", # mac + darwinports + mysql
- "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4
- "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5
- "/opt/lampp/var/mysql/mysql.sock" # xampp for linux
- ]
-end
+ [
+ "/tmp/mysql.sock", # default
+ "/var/run/mysqld/mysqld.sock", # debian/gentoo
+ "/var/tmp/mysql.sock", # freebsd
+ "/var/lib/mysql/mysql.sock", # fedora
+ "/opt/local/lib/mysql/mysql.sock", # fedora
+ "/opt/local/var/run/mysqld/mysqld.sock", # mac + darwinports + mysql
+ "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4
+ "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5
+ "/opt/lampp/var/mysql/mysql.sock" # xampp for linux
+ ].find { |f| File.exist?(f) } unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
+ end
+end \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/applications/app/scm/git.rb b/railties/lib/rails_generator/generators/applications/app/scm/git.rb
new file mode 100644
index 0000000000..445de6ab42
--- /dev/null
+++ b/railties/lib/rails_generator/generators/applications/app/scm/git.rb
@@ -0,0 +1,16 @@
+module Rails
+ class Git < Scm
+ def self.clone(repos, branch=nil)
+ `git clone #{repos}`
+
+ if branch
+ `cd #{repos.split('/').last}/`
+ `git checkout #{branch}`
+ end
+ end
+
+ def self.run(command)
+ `git #{command}`
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/applications/app/scm/scm.rb b/railties/lib/rails_generator/generators/applications/app/scm/scm.rb
new file mode 100644
index 0000000000..f6c08cad39
--- /dev/null
+++ b/railties/lib/rails_generator/generators/applications/app/scm/scm.rb
@@ -0,0 +1,8 @@
+module Rails
+ class Scm
+ private
+ def self.hash_to_parameters(hash)
+ hash.collect { |key, value| "--#{key} #{(value.kind_of?(String) ? value : "")}"}.join(" ")
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/applications/app/scm/svn.rb b/railties/lib/rails_generator/generators/applications/app/scm/svn.rb
new file mode 100644
index 0000000000..22b5966d25
--- /dev/null
+++ b/railties/lib/rails_generator/generators/applications/app/scm/svn.rb
@@ -0,0 +1,7 @@
+module Rails
+ class Svn < Scm
+ def self.checkout(repos, branch = nil)
+ `svn checkout #{repos}/#{branch || "trunk"}`
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/applications/app/template_runner.rb b/railties/lib/rails_generator/generators/applications/app/template_runner.rb
new file mode 100644
index 0000000000..0083e0d5a5
--- /dev/null
+++ b/railties/lib/rails_generator/generators/applications/app/template_runner.rb
@@ -0,0 +1,363 @@
+require File.dirname(__FILE__) + '/scm/scm'
+require File.dirname(__FILE__) + '/scm/git'
+require File.dirname(__FILE__) + '/scm/svn'
+
+require 'open-uri'
+require 'fileutils'
+
+module Rails
+ class TemplateRunner
+ attr_reader :behavior, :description, :root
+
+ def initialize(root, template) # :nodoc:
+ @root = Dir.pwd + "/" + root
+
+ puts "applying template: #{template}"
+
+ load_template(template)
+
+ puts "#{template} applied."
+ end
+
+ def load_template(template)
+ begin
+ code = open(template).read
+ in_root { self.instance_eval(code) }
+ rescue LoadError
+ raise "The template [#{template}] could not be loaded."
+ end
+ end
+
+ # Create a new file in the Rails project folder. Specify the
+ # relative path from RAILS_ROOT. Data is the return value of a block
+ # or a data string.
+ #
+ # ==== Examples
+ #
+ # file("lib/fun_party.rb") do
+ # hostname = ask("What is the virtual hostname I should use?")
+ # "vhost.name = #{hostname}"
+ # end
+ #
+ # file("config/apach.conf", "your apache config")
+ #
+ def file(filename, data = nil, &block)
+ puts "creating file #{filename}"
+ dir, file = [File.dirname(filename), File.basename(filename)]
+
+ inside(dir) do
+ File.open(file, "w") do |f|
+ if block_given?
+ f.write(block.call)
+ else
+ f.write(data)
+ end
+ end
+ end
+ end
+
+ # Install a plugin. You must provide either a Subversion url or Git url.
+ #
+ # ==== Examples
+ #
+ # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git'
+ # plugin 'restful-authentication', :svn => 'svn://svnhub.com/technoweenie/restful-authentication/trunk'
+ #
+ def plugin(name, options)
+ puts "installing plugin #{name}"
+
+ if options[:git] || options[:svn]
+ in_root do
+ `script/plugin install #{options[:svn] || options[:git]}`
+ end
+ else
+ puts "! no git or svn provided for #{name}. skipping..."
+ end
+ end
+
+ # Adds an entry into config/environment.rb for the supplied gem :
+ def gem(name, options = {})
+ puts "adding gem #{name}"
+
+ sentinel = 'Rails::Initializer.run do |config|'
+ gems_code = "config.gem '#{name}'"
+
+ if options.any?
+ opts = options.inject([]) {|result, h| result << [":#{h[0]} => '#{h[1]}'"] }.join(", ")
+ gems_code << ", #{opts}"
+ end
+
+ in_root do
+ gsub_file 'config/environment.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
+ "#{match}\n #{gems_code}"
+ end
+ end
+ end
+
+ # Run a command in git.
+ #
+ # ==== Examples
+ #
+ # git :init
+ # git :add => "this.file that.rb"
+ # git :add => "onefile.rb", :rm => "badfile.cxx"
+ #
+ def git(command = {})
+ puts "running git #{command}"
+
+ in_root do
+ if command.is_a?(Symbol)
+ Git.run(command.to_s)
+ else
+ command.each do |command, options|
+ Git.run("#{command} #{options}")
+ end
+ end
+ end
+ end
+
+ # Create a new file in the vendor/ directory. Code can be specified
+ # in a block or a data string can be given.
+ #
+ # ==== Examples
+ #
+ # vendor("sekrit.rb") do
+ # sekrit_salt = "#{Time.now}--#{3.years.ago}--#{rand}--"
+ # "salt = '#{sekrit_salt}'"
+ # end
+ #
+ # vendor("foreign.rb", "# Foreign code is fun")
+ #
+ def vendor(filename, data = nil, &block)
+ puts "vendoring file #{filename}"
+ inside("vendor") do |folder|
+ File.open("#{folder}/#{filename}", "w") do |f|
+ if block_given?
+ f.write(block.call)
+ else
+ f.write(data)
+ end
+ end
+ end
+ end
+
+ # Create a new file in the lib/ directory. Code can be specified
+ # in a block or a data string can be given.
+ #
+ # ==== Examples
+ #
+ # lib("crypto.rb") do
+ # "crypted_special_value = '#{rand}--#{Time.now}--#{rand(1337)}--'"
+ # end
+ #
+ # lib("foreign.rb", "# Foreign code is fun")
+ #
+ def lib(filename, data = nil)
+ puts "add lib file #{filename}"
+ inside("lib") do |folder|
+ File.open("#{folder}/#{filename}", "w") do |f|
+ if block_given?
+ f.write(block.call)
+ else
+ f.write(data)
+ end
+ end
+ end
+ end
+
+ # Create a new Rakefile with the provided code (either in a block or a string).
+ #
+ # ==== Examples
+ #
+ # rakefile("bootstrap.rake") do
+ # project = ask("What is the UNIX name of your project?")
+ #
+ # <<-TASK
+ # namespace :#{project} do
+ # task :bootstrap do
+ # puts "i like boots!"
+ # end
+ # end
+ # TASK
+ # end
+ #
+ # rakefile("seed.rake", "puts 'im plantin ur seedz'")
+ #
+ def rakefile(filename, data = nil, &block)
+ puts "adding rakefile #{filename}"
+ inside("lib/tasks") do |folder|
+ File.open("#{folder}/#{filename}", "w") do |f|
+ if block_given?
+ f.write(block.call)
+ else
+ f.write(data)
+ end
+ end
+ end
+ end
+
+ # Create a new initializer with the provided code (either in a block or a string).
+ #
+ # ==== Examples
+ #
+ # initializer("globals.rb") do
+ # data = ""
+ #
+ # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do
+ # data << "#{const} = :entp"
+ # end
+ #
+ # data
+ # end
+ #
+ # initializer("api.rb", "API_KEY = '123456'")
+ #
+ def initializer(filename, data = nil, &block)
+ puts "adding initializer #{filename}"
+ inside("config/initializers") do |folder|
+ File.open("#{folder}/#{filename}", "w") do |f|
+ if block_given?
+ f.write(block.call)
+ else
+ f.write(data)
+ end
+ end
+ end
+ end
+
+ # Generate something using a generator from Rails or a plugin.
+ # The second parameter is the argument string that is passed to
+ # the generator or an Array that is joined.
+ #
+ # ==== Example
+ #
+ # generate(:authenticated, "user session")
+ #
+ def generate(what, args = nil)
+ puts "generating #{what}"
+ args = args.join(" ") if args.class == Array
+
+ in_root { `#{root}/script/generate #{what} #{args}` }
+ end
+
+ # Executes a command
+ #
+ # ==== Example
+ #
+ # inside('vendor') do
+ # run('ln -s ~/edge rails)
+ # end
+ #
+ def run(command)
+ puts "executing #{command} from #{Dir.pwd}"
+ `#{command}`
+ end
+
+ # Runs the supplied rake task
+ #
+ # ==== Example
+ #
+ # rake("db:migrate")
+ # rake("db:migrate", "production")
+ #
+ def rake(command, env = 'development')
+ puts "running rake task #{command}"
+ in_root { `rake #{command} RAILS_ENV=#{env}` }
+ end
+
+ # Just run the capify command in root
+ #
+ # ==== Example
+ #
+ # capify!
+ #
+ def capify!
+ in_root { `capify .` }
+ end
+
+ # Add Rails to /vendor/rails
+ #
+ # ==== Example
+ #
+ # freeze!
+ #
+ def freeze!(args = {})
+ puts "vendoring rails edge"
+ in_root { `rake rails:freeze:edge` }
+ end
+
+ # Make an entry in Rails routing file conifg/routes.rb
+ #
+ # === Example
+ #
+ # route "map.root :controller => :welcome"
+ #
+ def route(routing_code)
+ sentinel = 'ActionController::Routing::Routes.draw do |map|'
+
+ in_root do
+ gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
+ "#{match}\n #{routing_code}\n"
+ end
+ end
+ end
+
+ protected
+
+ # Get a user's input
+ #
+ # ==== Example
+ #
+ # answer = ask("Should I freeze the latest Rails?")
+ # freeze! if ask("Should I freeze the latest Rails?") == "yes"
+ #
+ def ask(string)
+ puts string
+ gets.strip
+ end
+
+ # Do something in the root of the Rails application or
+ # a provided subfolder; the full path is yielded to the block you provide.
+ # The path is set back to the previous path when the method exits.
+ def inside(dir = '', &block)
+ folder = File.join(root, dir)
+ FileUtils.mkdir_p(folder) unless File.exist?(folder)
+ FileUtils.cd(folder) { block.arity == 1 ? yield(folder) : yield }
+ end
+
+ def in_root
+ FileUtils.cd(root) { yield }
+ end
+
+ # Helper to test if the user says yes(y)?
+ #
+ # ==== Example
+ #
+ # freeze! if yes?("Should I freeze the latest Rails?")
+ #
+ def yes?(question)
+ answer = ask(question).downcase
+ answer == "y" || answer == "yes"
+ end
+
+ # Helper to test if the user does NOT say yes(y)?
+ #
+ # ==== Example
+ #
+ # capify! if no?("Will you be using vlad to deploy your application?")
+ #
+ def no?(question)
+ !yes?(question)
+ end
+
+ def gsub_file(relative_destination, regexp, *args, &block)
+ path = destination_path(relative_destination)
+ content = File.read(path).gsub(regexp, *args, &block)
+ File.open(path, 'wb') { |file| file.write(content) }
+ end
+
+ def destination_path(relative_destination)
+ File.join(root, relative_destination)
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/lib/rails_generator/generators/components/controller/USAGE b/railties/lib/rails_generator/generators/components/controller/USAGE
index d4fae60c81..362872e84a 100644
--- a/railties/lib/rails_generator/generators/components/controller/USAGE
+++ b/railties/lib/rails_generator/generators/components/controller/USAGE
@@ -6,24 +6,25 @@ Description:
path like 'parent_module/controller_name'.
This generates a controller class in app/controllers, view templates in
- app/views/controller_name, a helper class in app/helpers, and a functional
- test suite in test/functional.
+ app/views/controller_name, a helper class in app/helpers, a functional
+ test suite in test/functional and a helper test suite in test/unit/helpers.
Example:
`./script/generate controller CreditCard open debit credit close`
Credit card controller with URLs like /credit_card/debit.
- Controller: app/controllers/credit_card_controller.rb
- Views: app/views/credit_card/debit.html.erb [...]
- Helper: app/helpers/credit_card_helper.rb
- Test: test/functional/credit_card_controller_test.rb
+ Controller: app/controllers/credit_card_controller.rb
+ Functional Test: test/functional/credit_card_controller_test.rb
+ Views: app/views/credit_card/debit.html.erb [...]
+ Helper: app/helpers/credit_card_helper.rb
+ Helper Test: test/unit/helpers/credit_card_helper_test.rb
Modules Example:
`./script/generate controller 'admin/credit_card' suspend late_fee`
Credit card admin controller with URLs /admin/credit_card/suspend.
- Controller: app/controllers/admin/credit_card_controller.rb
- Views: app/views/admin/credit_card/debit.html.erb [...]
- Helper: app/helpers/admin/credit_card_helper.rb
- Test: test/functional/admin/credit_card_controller_test.rb
-
+ Controller: app/controllers/admin/credit_card_controller.rb
+ Functional Test: test/functional/admin/credit_card_controller_test.rb
+ Views: app/views/admin/credit_card/debit.html.erb [...]
+ Helper: app/helpers/admin/credit_card_helper.rb
+ Helper Test: test/unit/helpers/admin/credit_card_helper_test.rb
diff --git a/railties/lib/rails_generator/generators/components/controller/controller_generator.rb b/railties/lib/rails_generator/generators/components/controller/controller_generator.rb
index 77b2220d57..dc126e8a98 100644
--- a/railties/lib/rails_generator/generators/components/controller/controller_generator.rb
+++ b/railties/lib/rails_generator/generators/components/controller/controller_generator.rb
@@ -2,13 +2,14 @@ class ControllerGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
# Check for class naming collisions.
- m.class_collisions "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper"
+ m.class_collisions "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper", "#{class_name}HelperTest"
# Controller, helper, views, and test directories.
m.directory File.join('app/controllers', class_path)
m.directory File.join('app/helpers', class_path)
m.directory File.join('app/views', class_path, file_name)
m.directory File.join('test/functional', class_path)
+ m.directory File.join('test/unit/helpers', class_path)
# Controller class, functional test, and helper class.
m.template 'controller.rb',
@@ -26,6 +27,11 @@ class ControllerGenerator < Rails::Generator::NamedBase
class_path,
"#{file_name}_helper.rb")
+ m.template 'helper_test.rb',
+ File.join('test/unit/helpers',
+ class_path,
+ "#{file_name}_helper_test.rb")
+
# View template for each action.
actions.each do |action|
path = File.join('app/views', class_path, file_name, "#{action}.html.erb")
diff --git a/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb
new file mode 100644
index 0000000000..591e40900e
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class <%= class_name %>HelperTest < ActionView::TestCase
+end
diff --git a/railties/lib/rails_generator/generators/components/helper/USAGE b/railties/lib/rails_generator/generators/components/helper/USAGE
new file mode 100644
index 0000000000..ef27ca617e
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/helper/USAGE
@@ -0,0 +1,24 @@
+Description:
+ Stubs out a new helper. Pass the helper name, either
+ CamelCased or under_scored.
+
+ To create a helper within a module, specify the helper name as a
+ path like 'parent_module/helper_name'.
+
+ This generates a helper class in app/helpers and a helper test
+ suite in test/unit/helpers.
+
+Example:
+ `./script/generate helper CreditCard`
+
+ Credit card helper.
+ Helper: app/helpers/credit_card_helper.rb
+ Test: test/unit/helpers/credit_card_helper_test.rb
+
+Modules Example:
+ `./script/generate helper 'admin/credit_card'`
+
+ Credit card admin helper.
+ Helper: app/helpers/admin/credit_card_helper.rb
+ Test: test/unit/helpers/admin/credit_card_helper_test.rb
+
diff --git a/railties/lib/rails_generator/generators/components/helper/helper_generator.rb b/railties/lib/rails_generator/generators/components/helper/helper_generator.rb
new file mode 100644
index 0000000000..f7831f7c7a
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/helper/helper_generator.rb
@@ -0,0 +1,25 @@
+class HelperGenerator < Rails::Generator::NamedBase
+ def manifest
+ record do |m|
+ # Check for class naming collisions.
+ m.class_collisions class_path, "#{class_name}Helper", "#{class_name}HelperTest"
+
+ # Helper and helper test directories.
+ m.directory File.join('app/helpers', class_path)
+ m.directory File.join('test/unit/helpers', class_path)
+
+ # Helper and helper test class.
+
+ m.template 'helper.rb',
+ File.join('app/helpers',
+ class_path,
+ "#{file_name}_helper.rb")
+
+ m.template 'helper_test.rb',
+ File.join('test/unit/helpers',
+ class_path,
+ "#{file_name}_helper_test.rb")
+
+ end
+ end
+end
diff --git a/railties/lib/rails_generator/generators/components/helper/templates/helper.rb b/railties/lib/rails_generator/generators/components/helper/templates/helper.rb
new file mode 100644
index 0000000000..3fe2ecdc74
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/helper/templates/helper.rb
@@ -0,0 +1,2 @@
+module <%= class_name %>Helper
+end
diff --git a/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb
new file mode 100644
index 0000000000..591e40900e
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class <%= class_name %>HelperTest < ActionView::TestCase
+end
diff --git a/railties/lib/rails_generator/generators/components/resource/USAGE b/railties/lib/rails_generator/generators/components/resource/USAGE
index 83cc9d7654..e6043f1de1 100644
--- a/railties/lib/rails_generator/generators/components/resource/USAGE
+++ b/railties/lib/rails_generator/generators/components/resource/USAGE
@@ -11,8 +11,8 @@ Description:
You don't have to think up every attribute up front, but it helps to
sketch out a few so you can start working with the resource immediately.
- This creates a model, controller, tests and fixtures for both, and the
- corresponding map.resources declaration in config/routes.rb
+ This creates a model, controller, helper, tests and fixtures for all of them,
+ and the corresponding map.resources declaration in config/routes.rb
Unlike the scaffold generator, the resource generator does not create
views or add any methods to the generated controller.
diff --git a/railties/lib/rails_generator/generators/components/resource/resource_generator.rb b/railties/lib/rails_generator/generators/components/resource/resource_generator.rb
index ea6dd65bde..4ee2fbff63 100644
--- a/railties/lib/rails_generator/generators/components/resource/resource_generator.rb
+++ b/railties/lib/rails_generator/generators/components/resource/resource_generator.rb
@@ -40,6 +40,7 @@ class ResourceGenerator < Rails::Generator::NamedBase
m.directory(File.join('app/views', controller_class_path, controller_file_name))
m.directory(File.join('test/functional', controller_class_path))
m.directory(File.join('test/unit', class_path))
+ m.directory(File.join('test/unit/helpers', class_path))
m.dependency 'model', [name] + @args, :collision => :skip
@@ -49,6 +50,7 @@ class ResourceGenerator < Rails::Generator::NamedBase
m.template('functional_test.rb', File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb"))
m.template('helper.rb', File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb"))
+ m.template('helper_test.rb', File.join('test/unit/helpers', controller_class_path, "#{controller_file_name}_helper_test.rb"))
m.route_resources controller_file_name
end
diff --git a/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb
new file mode 100644
index 0000000000..061f64a5e3
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class <%= controller_class_name %>HelperTest < ActionView::TestCase
+end
diff --git a/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb b/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb
index ff0381da2a..2a5edeedb6 100644
--- a/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb
+++ b/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb
@@ -47,6 +47,7 @@ class ScaffoldGenerator < Rails::Generator::NamedBase
m.directory(File.join('app/views/layouts', controller_class_path))
m.directory(File.join('test/functional', controller_class_path))
m.directory(File.join('test/unit', class_path))
+ m.directory(File.join('test/unit/helpers', class_path))
m.directory(File.join('public/stylesheets', class_path))
for action in scaffold_views
@@ -66,6 +67,7 @@ class ScaffoldGenerator < Rails::Generator::NamedBase
m.template('functional_test.rb', File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb"))
m.template('helper.rb', File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb"))
+ m.template('helper_test.rb', File.join('test/unit/helpers', controller_class_path, "#{controller_file_name}_helper_test.rb"))
m.route_resources controller_file_name
diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb
new file mode 100644
index 0000000000..061f64a5e3
--- /dev/null
+++ b/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class <%= controller_class_name %>HelperTest < ActionView::TestCase
+end
diff --git a/railties/lib/rails_generator/secret_key_generator.rb b/railties/lib/rails_generator/secret_key_generator.rb
index 553811d35d..7dd495a2f5 100644
--- a/railties/lib/rails_generator/secret_key_generator.rb
+++ b/railties/lib/rails_generator/secret_key_generator.rb
@@ -1,3 +1,5 @@
+require 'active_support/deprecation'
+
module Rails
# A class for creating random secret keys. This class will do its best to create a
# random secret key that's as secure as possible, using whatever methods are
diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake
index 5cb27f1f10..a90c1d4a77 100644
--- a/railties/lib/tasks/databases.rake
+++ b/railties/lib/tasks/databases.rake
@@ -1,7 +1,12 @@
namespace :db do
+ task :load_config => :rails_env do
+ require 'active_record'
+ ActiveRecord::Base.configurations = Rails::Configuration.new.database_configuration
+ end
+
namespace :create do
desc 'Create all the local databases defined in config/database.yml'
- task :all => :environment do
+ task :all => :load_config do
ActiveRecord::Base.configurations.each_value do |config|
# Skip entries that don't have a database key, such as the first entry here:
#
@@ -22,7 +27,7 @@ namespace :db do
end
desc 'Create the database defined in config/database.yml for the current RAILS_ENV'
- task :create => :environment do
+ task :create => :load_config do
create_database(ActiveRecord::Base.configurations[RAILS_ENV])
end
@@ -76,7 +81,7 @@ namespace :db do
namespace :drop do
desc 'Drops all the local databases defined in config/database.yml'
- task :all => :environment do
+ task :all => :load_config do
ActiveRecord::Base.configurations.each_value do |config|
# Skip entries that don't have a database key
next unless config['database']
@@ -87,7 +92,7 @@ namespace :db do
end
desc 'Drops the database for the current RAILS_ENV'
- task :drop => :environment do
+ task :drop => :load_config do
config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
begin
drop_database(config)
@@ -393,6 +398,7 @@ end
def drop_database(config)
case config['adapter']
when 'mysql'
+ ActiveRecord::Base.establish_connection(config)
ActiveRecord::Base.connection.drop_database config['database']
when /^sqlite/
FileUtils.rm(File.join(RAILS_ROOT, config['database']))
diff --git a/railties/lib/tasks/framework.rake b/railties/lib/tasks/framework.rake
index 66ab78c3b2..d639214ffe 100644
--- a/railties/lib/tasks/framework.rake
+++ b/railties/lib/tasks/framework.rake
@@ -5,7 +5,6 @@ namespace :rails do
deps = %w(actionpack activerecord actionmailer activesupport activeresource)
require 'rubygems'
require 'rubygems/gem_runner'
- Gem.manage_gems
rails = (version = ENV['VERSION']) ?
Gem.cache.find_name('rails', "= #{version}").first :
@@ -79,7 +78,7 @@ namespace :rails do
end
desc "Update both configs, scripts and public/javascripts from Rails"
- task :update => [ "update:scripts", "update:javascripts", "update:configs" ]
+ task :update => [ "update:scripts", "update:javascripts", "update:configs", "update:application_controller" ]
namespace :update do
desc "Add new scripts to the application script/ directory"
@@ -115,5 +114,24 @@ namespace :rails do
require 'railties_path'
FileUtils.cp(RAILTIES_PATH + '/environments/boot.rb', RAILS_ROOT + '/config/boot.rb')
end
+
+ desc "Rename application.rb to application_controller.rb"
+ task :application_controller do
+ old_style = RAILS_ROOT + '/app/controllers/application.rb'
+ new_style = RAILS_ROOT + '/app/controllers/application_controller.rb'
+ if File.exists?(old_style) && !File.exists?(new_style)
+ FileUtils.mv(old_style, new_style)
+ puts "#{old_style} has been renamed to #{new_style}, update your SCM as necessary"
+ end
+ end
+
+ desc "Generate dispatcher files in RAILS_ROOT/public"
+ task :generate_dispatchers do
+ require 'railties_path'
+ FileUtils.cp(RAILTIES_PATH + '/dispatches/config.ru', RAILS_ROOT + '/config.ru')
+ FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.fcgi', RAILS_ROOT + '/public/dispatch.fcgi')
+ FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.rb', RAILS_ROOT + '/public/dispatch.rb')
+ FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.rb', RAILS_ROOT + '/public/dispatch.cgi')
+ end
end
end
diff --git a/railties/lib/tasks/middleware.rake b/railties/lib/tasks/middleware.rake
new file mode 100644
index 0000000000..e0dcf50307
--- /dev/null
+++ b/railties/lib/tasks/middleware.rake
@@ -0,0 +1,7 @@
+desc 'Prints out your Rack middleware stack'
+task :middleware => :environment do
+ ActionController::Dispatcher.middleware.each do |middleware|
+ puts "use #{middleware.inspect}"
+ end
+ puts "run ActionController::Dispatcher.new"
+end
diff --git a/railties/lib/tasks/misc.rake b/railties/lib/tasks/misc.rake
index 5c99725203..411750bf40 100644
--- a/railties/lib/tasks/misc.rake
+++ b/railties/lib/tasks/misc.rake
@@ -3,6 +3,12 @@ task :environment do
require(File.join(RAILS_ROOT, 'config', 'environment'))
end
+task :rails_env do
+ unless defined? RAILS_ENV
+ RAILS_ENV = ENV['RAILS_ENV'] ||= 'development'
+ end
+end
+
desc 'Generate a crytographically secure secret key. This is typically used to generate a secret for cookie sessions.'
task :secret do
puts ActiveSupport::SecureRandom.hex(64)
diff --git a/railties/lib/tasks/statistics.rake b/railties/lib/tasks/statistics.rake
index dbd0773194..5ab27a0f62 100644
--- a/railties/lib/tasks/statistics.rake
+++ b/railties/lib/tasks/statistics.rake
@@ -4,7 +4,6 @@ STATS_DIRECTORIES = [
%w(Models app/models),
%w(Libraries lib/),
%w(APIs app/apis),
- %w(Components components),
%w(Integration\ tests test/integration),
%w(Functional\ tests test/functional),
%w(Unit\ tests test/unit)
diff --git a/railties/lib/tasks/testing.rake b/railties/lib/tasks/testing.rake
index 328bde7442..4242458672 100644
--- a/railties/lib/tasks/testing.rake
+++ b/railties/lib/tasks/testing.rake
@@ -7,7 +7,7 @@ def recent_tests(source_pattern, test_path, touched_since = 10.minutes.ago)
tests = []
source_dir = File.dirname(path).split("/")
source_file = File.basename(path, '.rb')
-
+
# Support subdirs in app/models and app/controllers
modified_test_path = source_dir.length > 2 ? "#{test_path}/" << source_dir[1..source_dir.length].join('/') : test_path
@@ -18,7 +18,7 @@ def recent_tests(source_pattern, test_path, touched_since = 10.minutes.ago)
# For modified files in app, run tests in subdirs too. ex. /test/functional/account/*_test.rb
test = "#{modified_test_path}/#{File.basename(path, '.rb').sub("_controller","")}"
FileList["#{test}/*_test.rb"].each { |f| tests.push f } if File.exist?(test)
-
+
return tests
end
@@ -63,7 +63,7 @@ namespace :test do
t.test_files = touched.uniq
end
Rake::Task['test:recent'].comment = "Test recent changes"
-
+
Rake::TestTask.new(:uncommitted => "db:test:prepare") do |t|
def t.file_list
if File.directory?(".svn")
@@ -82,7 +82,7 @@ namespace :test do
unit_tests.uniq + functional_tests.uniq
end
-
+
t.libs << 'test'
t.verbose = true
end
diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb
index 3cc61d7932..b5c92c1790 100644
--- a/railties/lib/test_help.rb
+++ b/railties/lib/test_help.rb
@@ -1,21 +1,30 @@
-require_dependency 'application'
-
# Make double-sure the RAILS_ENV is set to test,
# so fixtures are loaded to the right database
silence_warnings { RAILS_ENV = "test" }
require 'test/unit'
require 'active_support/test_case'
-require 'active_record/fixtures'
require 'action_controller/test_case'
+require 'action_view/test_case'
require 'action_controller/integration'
require 'action_mailer/test_case' if defined?(ActionMailer)
-Test::Unit::TestCase.fixture_path = RAILS_ROOT + "/test/fixtures/"
-ActionController::IntegrationTest.fixture_path = Test::Unit::TestCase.fixture_path
+if defined?(ActiveRecord)
+ require 'active_record/test_case'
+ require 'active_record/fixtures'
+
+ class ActiveSupport::TestCase
+ include ActiveRecord::TestFixtures
+ self.fixture_path = "#{RAILS_ROOT}/test/fixtures/"
+ self.use_instantiated_fixtures = false
+ self.use_transactional_fixtures = true
+ end
+
+ ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
-def create_fixtures(*table_names)
- Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names)
+ def create_fixtures(*table_names, &block)
+ Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
+ end
end
begin
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index e1ce32da65..b6edc03391 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -3,22 +3,20 @@ $:.unshift File.dirname(__FILE__) + "/../../actionpack/lib"
$:.unshift File.dirname(__FILE__) + "/../lib"
$:.unshift File.dirname(__FILE__) + "/../builtin/rails_info"
+require 'rubygems'
require 'test/unit'
+gem 'mocha', '>= 0.9.3'
+require 'mocha'
require 'stringio'
require 'active_support'
+require 'active_support/test_case'
-# Wrap tests that use Mocha and skip if unavailable.
def uses_mocha(test_name)
- require 'rubygems'
- gem 'mocha', '>= 0.5.5'
- require 'mocha'
yield
-rescue LoadError
- $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
end
if defined?(RAILS_ROOT)
RAILS_ROOT.replace File.dirname(__FILE__)
else
RAILS_ROOT = File.dirname(__FILE__)
-end
+end \ No newline at end of file
diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb
new file mode 100644
index 0000000000..5955fd2856
--- /dev/null
+++ b/railties/test/backtrace_cleaner_test.rb
@@ -0,0 +1,28 @@
+require 'abstract_unit'
+
+require 'initializer'
+require 'rails/backtrace_cleaner'
+
+class TestWithBacktrace
+ include Test::Unit::Util::BacktraceFilter
+ include Rails::BacktraceFilterForTestUnit
+end
+
+class BacktraceCleanerFilterTest < ActiveSupport::TestCase
+ def setup
+ @test = TestWithBacktrace.new
+ @backtrace = [ './test/rails/benchmark_test.rb', './test/rails/dependencies.rb', '/opt/local/lib/ruby/kernel.rb' ]
+ end
+
+ test "test with backtrace should use the rails backtrace cleaner to clean" do
+ Rails.stubs(:backtrace_cleaner).returns(stub(:clean))
+ Rails.backtrace_cleaner.expects(:clean).with(@backtrace, nil)
+ @test.filter_backtrace(@backtrace)
+ end
+
+ test "filter backtrace should have the same arity as Test::Unit::Util::BacktraceFilter" do
+ assert_nothing_raised do
+ @test.filter_backtrace(@backtrace, '/opt/local/lib')
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/test/fcgi_dispatcher_test.rb b/railties/test/fcgi_dispatcher_test.rb
index 64d054d45c..cc054c24aa 100644
--- a/railties/test/fcgi_dispatcher_test.rb
+++ b/railties/test/fcgi_dispatcher_test.rb
@@ -1,7 +1,6 @@
require 'abstract_unit'
-uses_mocha 'fcgi dispatcher tests' do
-
+begin
require 'fcgi_handler'
module ActionController; module Routing; module Routes; end end end
@@ -296,4 +295,6 @@ class RailsFCGIHandlerPeriodicGCTest < Test::Unit::TestCase
end
end
-end # uses_mocha
+rescue LoadError => e
+ raise unless e.message =~ /fcgi/
+end
diff --git a/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb b/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb
new file mode 100644
index 0000000000..323ee1c4dc
--- /dev/null
+++ b/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb
@@ -0,0 +1,2 @@
+class EngineController
+end \ No newline at end of file
diff --git a/railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb b/railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb
new file mode 100644
index 0000000000..e265712185
--- /dev/null
+++ b/railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb
@@ -0,0 +1,2 @@
+class EngineModel
+end \ No newline at end of file
diff --git a/railties/test/fixtures/plugins/engines/engine/config/routes.rb b/railties/test/fixtures/plugins/engines/engine/config/routes.rb
new file mode 100644
index 0000000000..cca8d1b146
--- /dev/null
+++ b/railties/test/fixtures/plugins/engines/engine/config/routes.rb
@@ -0,0 +1,3 @@
+ActionController::Routing::Routes.draw do |map|
+ map.connect '/engine', :controller => "engine"
+end
diff --git a/railties/test/fixtures/plugins/engines/engine/init.rb b/railties/test/fixtures/plugins/engines/engine/init.rb
new file mode 100644
index 0000000000..f4b00c0fa4
--- /dev/null
+++ b/railties/test/fixtures/plugins/engines/engine/init.rb
@@ -0,0 +1,3 @@
+# My app/models dir must be in the load path.
+require 'engine_model'
+raise 'missing model from my app/models dir' unless defined?(EngineModel)
diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb
index 4f9e824c9f..1d4f2b18b3 100644
--- a/railties/test/gem_dependency_test.rb
+++ b/railties/test/gem_dependency_test.rb
@@ -129,5 +129,19 @@ uses_mocha "Plugin Tests" do
assert_equal '1.0.0', DUMMY_GEM_E_VERSION
end
+ def test_gem_handle_missing_dependencies
+ dummy_gem = Rails::GemDependency.new "dummy-gem-g"
+ dummy_gem.add_load_paths
+ dummy_gem.load
+ assert dummy_gem.loaded?
+ debugger
+ assert_equal 2, dummy_gem.dependencies.size
+ assert_nothing_raised do
+ dummy_gem.dependencies.each do |g|
+ g.dependencies
+ end
+ end
+ end
+
end
end
diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb
index 0901b215e4..01bf1c90bd 100644
--- a/railties/test/generators/generator_test_helper.rb
+++ b/railties/test/generators/generator_test_helper.rb
@@ -145,6 +145,19 @@ class GeneratorTestCase < Test::Unit::TestCase
end
end
+ # Asserts that the given helper test test was generated.
+ # It takes a name or symbol without the <tt>_helper_test</tt> part and an optional super class.
+ # The contents of the class source file is passed to a block.
+ def assert_generated_helper_test_for(name, parent = "ActionView::TestCase")
+ path = "test/unit/helpers/#{name.to_s.underscore}_helper_test"
+ # Have to pass the path without the "test/" part so that class_name_from_path will return a correct result
+ class_name = class_name_from_path(path.gsub(/^test\//, ''))
+
+ assert_generated_class path,parent,class_name do |body|
+ yield body if block_given?
+ end
+ end
+
# Asserts that the given unit test was generated.
# It takes a name or symbol without the <tt>_test</tt> part and an optional super class.
# The contents of the class source file is passed to a block.
@@ -172,19 +185,21 @@ class GeneratorTestCase < Test::Unit::TestCase
# Asserts that the given class source file was generated.
# It takes a path without the <tt>.rb</tt> part and an optional super class.
# The contents of the class source file is passed to a block.
- def assert_generated_class(path, parent = nil)
+ def assert_generated_class(path, parent = nil, class_name = class_name_from_path(path))
+ assert_generated_file("#{path}.rb") do |body|
+ assert_match /class #{class_name}#{parent.nil? ? '':" < #{parent}"}/, body, "the file '#{path}.rb' should be a class"
+ yield body if block_given?
+ end
+ end
+
+ def class_name_from_path(path)
# FIXME: Sucky way to detect namespaced classes
if path.split('/').size > 3
path =~ /\/?(\d+_)?(\w+)\/(\w+)$/
- class_name = "#{$2.camelize}::#{$3.camelize}"
+ "#{$2.camelize}::#{$3.camelize}"
else
path =~ /\/?(\d+_)?(\w+)$/
- class_name = $2.camelize
- end
-
- assert_generated_file("#{path}.rb") do |body|
- assert_match /class #{class_name}#{parent.nil? ? '':" < #{parent}"}/, body, "the file '#{path}.rb' should be a class"
- yield body if block_given?
+ $2.camelize
end
end
diff --git a/railties/test/generators/rails_controller_generator_test.rb b/railties/test/generators/rails_controller_generator_test.rb
index f839ea97e6..43fbe972e2 100644
--- a/railties/test/generators/rails_controller_generator_test.rb
+++ b/railties/test/generators/rails_controller_generator_test.rb
@@ -11,6 +11,7 @@ class RailsControllerGeneratorTest < GeneratorTestCase
assert_generated_controller_for :products
assert_generated_functional_test_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
end
def test_controller_generates_namespaced_controller
@@ -19,24 +20,25 @@ class RailsControllerGeneratorTest < GeneratorTestCase
assert_generated_controller_for "admin::products"
assert_generated_functional_test_for "admin::products"
assert_generated_helper_for "admin::products"
+ assert_generated_helper_test_for "admin::products"
end
def test_controller_generates_namespaced_and_not_namespaced_controllers
- run_generator('controller', %w(products))
-
- # We have to require the generated helper to show the problem because
- # the test helpers just check for generated files and contents but
- # do not actually load them. But they have to be loaded (as in a real environment)
- # to make the second generator run fail
- require "#{RAILS_ROOT}/app/helpers/products_helper"
-
- assert_nothing_raised do
- begin
- run_generator('controller', %w(admin::products))
- ensure
- # cleanup
- Object.send(:remove_const, :ProductsHelper)
- end
+ run_generator('controller', %w(products))
+
+ # We have to require the generated helper to show the problem because
+ # the test helpers just check for generated files and contents but
+ # do not actually load them. But they have to be loaded (as in a real environment)
+ # to make the second generator run fail
+ require "#{RAILS_ROOT}/app/helpers/products_helper"
+
+ assert_nothing_raised do
+ begin
+ run_generator('controller', %w(admin::products))
+ ensure
+ # cleanup
+ Object.send(:remove_const, :ProductsHelper)
end
+ end
end
end
diff --git a/railties/test/generators/rails_helper_generator_test.rb b/railties/test/generators/rails_helper_generator_test.rb
new file mode 100644
index 0000000000..8d05f555e6
--- /dev/null
+++ b/railties/test/generators/rails_helper_generator_test.rb
@@ -0,0 +1,36 @@
+require File.dirname(__FILE__) + '/generator_test_helper'
+
+class RailsHelperGeneratorTest < GeneratorTestCase
+ def test_helper_generates_helper
+ run_generator('helper', %w(products))
+
+ assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
+ end
+
+ def test_helper_generates_namespaced_helper
+ run_generator('helper', %w(admin::products))
+
+ assert_generated_helper_for "admin::products"
+ assert_generated_helper_test_for "admin::products"
+ end
+
+ def test_helper_generates_namespaced_and_not_namespaced_helpers
+ run_generator('helper', %w(products))
+
+ # We have to require the generated helper to show the problem because
+ # the test helpers just check for generated files and contents but
+ # do not actually load them. But they have to be loaded (as in a real environment)
+ # to make the second generator run fail
+ require "#{RAILS_ROOT}/app/helpers/products_helper"
+
+ assert_nothing_raised do
+ begin
+ run_generator('helper', %w(admin::products))
+ ensure
+ # cleanup
+ Object.send(:remove_const, :ProductsHelper)
+ end
+ end
+ end
+end
diff --git a/railties/test/generators/rails_resource_generator_test.rb b/railties/test/generators/rails_resource_generator_test.rb
index 45e4850ef5..1f5bd0ef1e 100644
--- a/railties/test/generators/rails_resource_generator_test.rb
+++ b/railties/test/generators/rails_resource_generator_test.rb
@@ -1,7 +1,6 @@
require 'generators/generator_test_helper'
class RailsResourceGeneratorTest < GeneratorTestCase
-
def test_resource_generates_resources
run_generator('resource', %w(Product name:string))
@@ -10,6 +9,7 @@ class RailsResourceGeneratorTest < GeneratorTestCase
assert_generated_fixtures_for :products
assert_generated_functional_test_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
assert_generated_migration :create_products
assert_added_route_for :products
end
@@ -22,8 +22,8 @@ class RailsResourceGeneratorTest < GeneratorTestCase
assert_generated_fixtures_for :products
assert_generated_functional_test_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
assert_skipped_migration :create_products
assert_added_route_for :products
end
-
end
diff --git a/railties/test/generators/rails_scaffold_generator_test.rb b/railties/test/generators/rails_scaffold_generator_test.rb
index de6b38dafe..926607f55c 100644
--- a/railties/test/generators/rails_scaffold_generator_test.rb
+++ b/railties/test/generators/rails_scaffold_generator_test.rb
@@ -2,7 +2,6 @@ require 'generators/generator_test_helper'
require 'abstract_unit'
class RailsScaffoldGeneratorTest < GeneratorTestCase
-
def test_scaffolded_names
g = Rails::Generator::Base.instance('scaffold', %w(ProductLine))
assert_equal "ProductLines", g.controller_name
@@ -43,6 +42,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_generated_unit_test_for :product
assert_generated_fixtures_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
assert_generated_stylesheet :scaffold
assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb"
@@ -58,6 +58,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_generated_unit_test_for :product
assert_generated_fixtures_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
assert_generated_stylesheet :scaffold
assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb"
assert_skipped_migration :create_products
@@ -93,6 +94,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_generated_unit_test_for :product
assert_generated_fixtures_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
assert_generated_stylesheet :scaffold
assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb"
@@ -126,6 +128,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_generated_unit_test_for :product
assert_generated_fixtures_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
assert_generated_stylesheet :scaffold
assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb"
assert_skipped_migration :create_products
@@ -140,10 +143,10 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase
assert_generated_unit_test_for :products
assert_generated_fixtures_for :products
assert_generated_helper_for :products
+ assert_generated_helper_test_for :products
assert_generated_stylesheet :scaffold
assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb"
assert_skipped_migration :create_products
assert_added_route_for :products
end
-
end
diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb
index 5147eeb482..dad9e55e61 100644
--- a/railties/test/initializer_test.rb
+++ b/railties/test/initializer_test.rb
@@ -18,7 +18,6 @@ class ConfigurationMock < Rails::Configuration
end
class Initializer_load_environment_Test < Test::Unit::TestCase
-
def test_load_environment_with_constant
config = ConfigurationMock.new("#{File.dirname(__FILE__)}/fixtures/environment_with_constant.rb")
assert_nil $initialize_test_set_from_env
@@ -210,7 +209,7 @@ uses_mocha "Initializer plugin loading tests" do
def test_all_plugins_are_loaded_when_registered_plugin_list_is_untouched
failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
load_plugins!
- assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip
+ assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip
end
def test_all_plugins_loaded_when_all_is_used
@@ -218,7 +217,7 @@ uses_mocha "Initializer plugin loading tests" do
only_load_the_following_plugins! plugin_names
load_plugins!
failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
- assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :gemlike, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip
+ assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip
end
def test_all_plugins_loaded_after_all
@@ -226,7 +225,7 @@ uses_mocha "Initializer plugin loading tests" do
only_load_the_following_plugins! plugin_names
load_plugins!
failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
- assert_plugins [:stubby, :a, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip
+ assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip
end
def test_plugin_names_may_be_strings
@@ -253,6 +252,7 @@ uses_mocha "Initializer plugin loading tests" do
assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib'))
end
+
private
def load_plugins!
@@ -260,5 +260,64 @@ uses_mocha "Initializer plugin loading tests" do
@initializer.load_plugins
end
end
+end
+
+uses_mocha 'i18n settings' do
+ class InitializerSetupI18nTests < Test::Unit::TestCase
+ def test_no_config_locales_dir_present_should_return_empty_load_path
+ File.stubs(:exist?).returns(false)
+ assert_equal [], Rails::Configuration.new.i18n.load_path
+ end
+
+ def test_config_locales_dir_present_should_be_added_to_load_path
+ File.stubs(:exist?).returns(true)
+ Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
+ assert_equal [ "my/test/locale.yml" ], Rails::Configuration.new.i18n.load_path
+ end
+
+ def test_config_defaults_should_be_added_with_config_settings
+ File.stubs(:exist?).returns(true)
+ Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
+
+ config = Rails::Configuration.new
+ config.i18n.load_path << "my/other/locale.yml"
+ assert_equal [ "my/test/locale.yml", "my/other/locale.yml" ], config.i18n.load_path
+ end
+
+ def test_config_defaults_and_settings_should_be_added_to_i18n_defaults
+ File.stubs(:exist?).returns(true)
+ Dir.stubs(:[]).returns([ "my/test/locale.yml" ])
+
+ config = Rails::Configuration.new
+ config.i18n.load_path << "my/other/locale.yml"
+
+ # To bring in AV's i18n load path.
+ require 'action_view'
+
+ Rails::Initializer.run(:initialize_i18n, config)
+ assert_equal [
+ File.expand_path("./test/../../activesupport/lib/active_support/locale/en.yml"),
+ File.expand_path("./test/../../actionpack/lib/action_view/locale/en.yml"),
+ "my/test/locale.yml",
+ "my/other/locale.yml" ], I18n.load_path.collect { |path| path =~ /^\./ ? File.expand_path(path) : path }
+ end
+
+ def test_setting_another_default_locale
+ config = Rails::Configuration.new
+ config.i18n.default_locale = :de
+ Rails::Initializer.run(:initialize_i18n, config)
+ assert_equal :de, I18n.default_locale
+ end
+ end
end
+
+class RailsRootTest < Test::Unit::TestCase
+ def test_rails_dot_root_equals_rails_root
+ assert_equal RAILS_ROOT, Rails.root.to_s
+ end
+
+ def test_rails_dot_root_should_be_a_pathname
+ assert_equal File.join(RAILS_ROOT, 'app', 'controllers'), Rails.root.join('app', 'controllers').to_s
+ end
+end \ No newline at end of file
diff --git a/railties/test/plugin_loader_test.rb b/railties/test/plugin_loader_test.rb
index f429bae15c..23b81ddbf6 100644
--- a/railties/test/plugin_loader_test.rb
+++ b/railties/test/plugin_loader_test.rb
@@ -1,5 +1,8 @@
require 'plugin_test_helper'
+$:.unshift File.dirname(__FILE__) + "/../../actionpack/lib"
+require 'action_controller'
+
# Mocks out the configuration
module Rails
def self.configuration
@@ -7,136 +10,152 @@ module Rails
end
end
-uses_mocha "Plugin Loader Tests" do
-
- class TestPluginLoader < Test::Unit::TestCase
- ORIGINAL_LOAD_PATH = $LOAD_PATH.dup
+class TestPluginLoader < Test::Unit::TestCase
+ ORIGINAL_LOAD_PATH = $LOAD_PATH.dup
- def setup
- reset_load_path!
+ def setup
+ reset_load_path!
- @configuration = Rails::Configuration.new
- @configuration.plugin_paths << plugin_fixture_root_path
- @initializer = Rails::Initializer.new(@configuration)
- @valid_plugin_path = plugin_fixture_path('default/stubby')
- @empty_plugin_path = plugin_fixture_path('default/empty')
+ @configuration = Rails::Configuration.new
+ @configuration.plugin_paths << plugin_fixture_root_path
+ @initializer = Rails::Initializer.new(@configuration)
+ @valid_plugin_path = plugin_fixture_path('default/stubby')
+ @empty_plugin_path = plugin_fixture_path('default/empty')
- @failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
+ @failure_tip = "It's likely someone has added a new plugin fixture without updating this list"
- @loader = Rails::Plugin::Loader.new(@initializer)
- end
+ @loader = Rails::Plugin::Loader.new(@initializer)
+ end
- def test_should_locate_plugins_by_asking_each_locator_specifed_in_configuration_for_its_plugins_result
- locator_1 = stub(:plugins => [:a, :b, :c])
- locator_2 = stub(:plugins => [:d, :e, :f])
- locator_class_1 = stub(:new => locator_1)
- locator_class_2 = stub(:new => locator_2)
- @configuration.plugin_locators = [locator_class_1, locator_class_2]
- assert_equal [:a, :b, :c, :d, :e, :f], @loader.send(:locate_plugins)
- end
+ def test_should_locate_plugins_by_asking_each_locator_specifed_in_configuration_for_its_plugins_result
+ locator_1 = stub(:plugins => [:a, :b, :c])
+ locator_2 = stub(:plugins => [:d, :e, :f])
+ locator_class_1 = stub(:new => locator_1)
+ locator_class_2 = stub(:new => locator_2)
+ @configuration.plugin_locators = [locator_class_1, locator_class_2]
+ assert_equal [:a, :b, :c, :d, :e, :f], @loader.send(:locate_plugins)
+ end
- def test_should_memoize_the_result_of_locate_plugins_as_all_plugins
- plugin_list = [:a, :b, :c]
- @loader.expects(:locate_plugins).once.returns(plugin_list)
- assert_equal plugin_list, @loader.all_plugins
- assert_equal plugin_list, @loader.all_plugins # ensuring that locate_plugins isn't called again
- end
+ def test_should_memoize_the_result_of_locate_plugins_as_all_plugins
+ plugin_list = [:a, :b, :c]
+ @loader.expects(:locate_plugins).once.returns(plugin_list)
+ assert_equal plugin_list, @loader.all_plugins
+ assert_equal plugin_list, @loader.all_plugins # ensuring that locate_plugins isn't called again
+ end
- def test_should_return_empty_array_if_configuration_plugins_is_empty
- @configuration.plugins = []
- assert_equal [], @loader.plugins
- end
+ def test_should_return_empty_array_if_configuration_plugins_is_empty
+ @configuration.plugins = []
+ assert_equal [], @loader.plugins
+ end
- def test_should_find_all_availble_plugins_and_return_as_all_plugins
- assert_plugins [:stubby, :plugin_with_no_lib_dir, :gemlike, :acts_as_chunky_bacon, :a], @loader.all_plugins.reverse, @failure_tip
- end
+ def test_should_find_all_availble_plugins_and_return_as_all_plugins
+ assert_plugins [ :engine, :stubby, :plugin_with_no_lib_dir, :gemlike, :acts_as_chunky_bacon, :a], @loader.all_plugins.reverse, @failure_tip
+ end
- def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched
- assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip
- end
+ def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched
+ assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip
+ end
- def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil
- @configuration.plugins = nil
- assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip
- end
+ def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil
+ @configuration.plugins = nil
+ assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip
+ end
- def test_should_return_specific_plugins_named_in_config_plugins_array_if_set
- plugin_names = [:acts_as_chunky_bacon, :stubby]
- only_load_the_following_plugins! plugin_names
- assert_plugins plugin_names, @loader.plugins
- end
+ def test_should_return_specific_plugins_named_in_config_plugins_array_if_set
+ plugin_names = [:acts_as_chunky_bacon, :stubby]
+ only_load_the_following_plugins! plugin_names
+ assert_plugins plugin_names, @loader.plugins
+ end
- def test_should_respect_the_order_of_plugins_given_in_configuration
- plugin_names = [:stubby, :acts_as_chunky_bacon]
- only_load_the_following_plugins! plugin_names
- assert_plugins plugin_names, @loader.plugins
- end
+ def test_should_respect_the_order_of_plugins_given_in_configuration
+ plugin_names = [:stubby, :acts_as_chunky_bacon]
+ only_load_the_following_plugins! plugin_names
+ assert_plugins plugin_names, @loader.plugins
+ end
- def test_should_load_all_plugins_in_natural_order_when_all_is_used
- only_load_the_following_plugins! [:all]
- assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip
- end
+ def test_should_load_all_plugins_in_natural_order_when_all_is_used
+ only_load_the_following_plugins! [:all]
+ assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip
+ end
- def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used
- only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all]
- assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :gemlike, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip
- end
+ def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used
+ only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all]
+ assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip
+ end
- def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all
- only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon]
- assert_plugins [:stubby, :a, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip
- end
+ def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all
+ only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon]
+ assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip
+ end
- def test_should_accept_plugin_names_given_as_strings
- only_load_the_following_plugins! ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir]
- assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip
- end
+ def test_should_accept_plugin_names_given_as_strings
+ only_load_the_following_plugins! ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir]
+ assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip
+ end
- def test_should_add_plugin_load_paths_to_global_LOAD_PATH_array
- only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
- stubbed_application_lib_index_in_LOAD_PATHS = 4
- @loader.stubs(:application_lib_index).returns(stubbed_application_lib_index_in_LOAD_PATHS)
+ def test_should_add_plugin_load_paths_to_global_LOAD_PATH_array
+ only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
+ stubbed_application_lib_index_in_LOAD_PATHS = 4
+ @loader.stubs(:application_lib_index).returns(stubbed_application_lib_index_in_LOAD_PATHS)
- @loader.add_plugin_load_paths
+ @loader.add_plugin_load_paths
- assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/stubby'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS
- assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS
- end
+ assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/stubby'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS
+ assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS
+ end
- def test_should_add_plugin_load_paths_to_Dependencies_load_paths
- only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
+ def test_should_add_plugin_load_paths_to_Dependencies_load_paths
+ only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
- @loader.add_plugin_load_paths
+ @loader.add_plugin_load_paths
- assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib'))
- assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib'))
- end
+ assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib'))
+ assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib'))
+ end
- def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths
- only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
+ def test_should_add_engine_load_paths_to_Dependencies_load_paths
+ only_load_the_following_plugins! [:engine]
- @loader.add_plugin_load_paths
+ @loader.add_plugin_load_paths
- assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib'))
- assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib'))
+ %w( models controllers helpers ).each do |app_part|
+ assert ActiveSupport::Dependencies.load_paths.include?(
+ File.join(plugin_fixture_path('engines/engine'), 'app', app_part)
+ ), "Couldn't find #{app_part} in load path"
end
+ end
+
+ def test_engine_controllers_should_have_their_view_path_set_when_loaded
+ only_load_the_following_plugins!([ :engine ])
- def test_should_add_all_load_paths_from_a_plugin_to_LOAD_PATH_array
- plugin_load_paths = ["a", "b"]
- plugin = stub(:load_paths => plugin_load_paths)
- @loader.stubs(:plugins).returns([plugin])
+ @loader.send :add_engine_view_paths
+
+ assert_equal [ File.join(plugin_fixture_path('engines/engine'), 'app', 'views') ], ActionController::Base.view_paths
+ end
- @loader.add_plugin_load_paths
+ def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths
+ only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon]
- plugin_load_paths.each { |path| assert $LOAD_PATH.include?(path) }
- end
+ @loader.add_plugin_load_paths
+
+ assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib'))
+ assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib'))
+ end
+
+ def test_should_add_all_load_paths_from_a_plugin_to_LOAD_PATH_array
+ plugin_load_paths = ["a", "b"]
+ plugin = stub(:load_paths => plugin_load_paths)
+ @loader.stubs(:plugins).returns([plugin])
- private
+ @loader.add_plugin_load_paths
- def reset_load_path!
- $LOAD_PATH.clear
- ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path }
- end
+ plugin_load_paths.each { |path| assert $LOAD_PATH.include?(path) }
end
-end
+
+ private
+ def reset_load_path!
+ $LOAD_PATH.clear
+ ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path }
+ end
+end \ No newline at end of file
diff --git a/railties/test/plugin_locator_test.rb b/railties/test/plugin_locator_test.rb
index 363fa27f15..5a8c651e5a 100644
--- a/railties/test/plugin_locator_test.rb
+++ b/railties/test/plugin_locator_test.rb
@@ -47,7 +47,7 @@ uses_mocha "Plugin Locator Tests" do
end
def test_should_return_all_plugins_found_under_the_set_plugin_paths
- assert_equal ["a", "acts_as_chunky_bacon", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort
+ assert_equal ["a", "acts_as_chunky_bacon", "engine", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort
end
def test_should_find_plugins_only_under_the_plugin_paths_set_in_configuration
diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb
index e1872ebf33..e274e1aa6e 100644
--- a/railties/test/rails_info_controller_test.rb
+++ b/railties/test/rails_info_controller_test.rb
@@ -25,7 +25,7 @@ ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id'
end
-class Rails::InfoControllerTest < Test::Unit::TestCase
+class Rails::InfoControllerTest < ActionController::TestCase
def setup
@controller = Rails::InfoController.new
@request = ActionController::TestRequest.new
diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb
index 3e91e2f2ee..9befd44a58 100644
--- a/railties/test/rails_info_test.rb
+++ b/railties/test/rails_info_test.rb
@@ -61,14 +61,14 @@ EOS
assert_property 'Goodbye', 'World'
end
- def test_component_version
+ def test_framework_version
assert_property 'Active Support version', ActiveSupport::VERSION::STRING
end
- def test_components_exist
- Rails::Info.components.each do |component|
- dir = File.dirname(__FILE__) + "/../../" + component.gsub('_', '')
- assert File.directory?(dir), "#{component.classify} does not exist"
+ def test_frameworks_exist
+ Rails::Info.frameworks.each do |framework|
+ dir = File.dirname(__FILE__) + "/../../" + framework.gsub('_', '')
+ assert File.directory?(dir), "#{framework.classify} does not exist"
end
end
diff --git a/railties/test/secret_key_generation_test.rb b/railties/test/secret_key_generation_test.rb
index 7269f98ce5..2c7c3d5dfe 100644
--- a/railties/test/secret_key_generation_test.rb
+++ b/railties/test/secret_key_generation_test.rb
@@ -1,4 +1,4 @@
-require 'test/unit'
+require 'abstract_unit'
# Must set before requiring generator libs.
if defined?(RAILS_ROOT)
@@ -22,7 +22,7 @@ require 'rails_generator'
require 'rails_generator/secret_key_generator'
require 'rails_generator/generators/applications/app/app_generator'
-class SecretKeyGenerationTest < Test::Unit::TestCase
+class SecretKeyGenerationTest < ActiveSupport::TestCase
SECRET_KEY_MIN_LENGTH = 128
APP_NAME = "foo"
diff --git a/railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification b/railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification
new file mode 100644
index 0000000000..70a36b9a8c
--- /dev/null
+++ b/railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification
@@ -0,0 +1,39 @@
+--- !ruby/object:Gem::Specification
+name: dummy-gem-f
+version: !ruby/object:Gem::Version
+ version: 1.3.0
+platform: ruby
+authors:
+- "Nobody"
+date: 2008-10-03 00:00:00 -04:00
+dependencies:
+- !ruby/object:Gem::Dependency
+ name: absolutely-no-such-gem
+ type: :runtime
+ version_requirement:
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 1.0.0
+ version:
+files:
+- lib
+- lib/dummy-gem-f.rb
+require_paths:
+- lib
+required_ruby_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: "0"
+ version:
+required_rubygems_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: "0"
+ version:
+requirements: []
+specification_version: 2
+summary: Dummy Gem F
diff --git a/railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb b/railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb
new file mode 100644
index 0000000000..0271c8c48a
--- /dev/null
+++ b/railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb
@@ -0,0 +1 @@
+DUMMY_GEM_F_VERSION="1.0.0"
diff --git a/railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification b/railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification
new file mode 100644
index 0000000000..5483048c1c
--- /dev/null
+++ b/railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification
@@ -0,0 +1,39 @@
+--- !ruby/object:Gem::Specification
+name: dummy-gem-g
+version: !ruby/object:Gem::Version
+ version: 1.3.0
+platform: ruby
+authors:
+- "Nobody"
+date: 2008-10-03 00:00:00 -04:00
+dependencies:
+- !ruby/object:Gem::Dependency
+ name: dummy-gem-f
+ type: :development
+ version_requirement:
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 1.0.0
+ version:
+files:
+- lib
+- lib/dummy-gem-g.rb
+require_paths:
+- lib
+required_ruby_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: "0"
+ version:
+required_rubygems_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: "0"
+ version:
+requirements: []
+specification_version: 2
+summary: Dummy Gem G
diff --git a/railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb b/railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb
new file mode 100644
index 0000000000..8fc056586c
--- /dev/null
+++ b/railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb
@@ -0,0 +1 @@
+DUMMY_GEM_G_VERSION="1.0.0"